Price fraction: Difference between revisions

Content added Content deleted
(Add Quackery)
(Updated to work with Nim 1.4. Done heavy restructuring and simplification, but kept the algorithm.)
Line 2,769: Line 2,769:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils, math
<lang nim>import random, strformat


# Representation of a standard value as an int (actual value * 100).
const
type StandardValue = distinct int
pricemap: array[0 .. 19, int] = [10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100]


proc `<`(a, b: StandardValue): bool {.borrow.}
# outputs an int (=>float*100)
proc floatToPrice100(f: float): int =
# indx: 0.1-0.05->0, 0.06-0.10->1, 0.11-0.15->2, .....
var valu: int = toInt(f*100)
if valu == 0:
result = 10
else:
dec(valu)
# inc indx every 5 of valu, so value of 1..100 translates to indx of 0..19
var indx: int = 2*int(valu/10)+int((valu%%10)/5)
result = pricemap[indx]


const Pricemap = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]
# str representation of an int (that is a representation of a float price)
proc price100ToStr(p: int): string =
if p < 10:
result = "0.0" & $p
if p < 100:
result = "0." & $p
else:
result = "1.00"


randomize()
var i: int = 0


proc toStandardValue(f: float): StandardValue =
for x in 0 .. 10:
## Convert a float to a standard value (decimal value multiplied by 100).
i = random(101)
## Index: 0.01..0.05 -> 0, 0.06..0.10 -> 1, 0.11..0.15 -> 2...
echo("Price for ", i.price100ToStr(), ", is: ", float(i/100).floatToPrice100().price100ToStr())</lang>
var value = int(f * 100)
if value == 0: return StandardValue(10)
dec value
# Increment index every 5 of value, so value in 1..100 translates to index in 0..19.
let index = 2 * (value div 10) + (value mod 10) div 5
result = StandardValue(Pricemap[index])


proc `$`(price: StandardValue): string =
## Return the string representation of a standard value.
if price < StandardValue(10): "0.0" & $int(price)
elif price < StandardValue(100): "0." & $int(price)
else: "1.00"


when isMainModule:
randomize()
for _ in 0 .. 10:
let price = rand(1.01)
echo &"Price for {price:.2f} is {price.toStandardValue()}"</lang>
{{out}}
{{out}}
A random output something like:
A random output looking something like this:
<pre>Price for 0.73, is: 0.82
<pre>Price for 0.88 is 0.94
Price for 0.29, is: 0.44
Price for 0.58 is 0.70
Price for 0.25, is: 0.38
Price for 0.67 is 0.78
Price for 0.52, is: 0.66
Price for 0.53 is 0.66
Price for 0.66, is: 0.78
Price for 0.56 is 0.66
Price for 0.23, is: 0.38
Price for 0.02 is 0.10
Price for 0.62, is: 0.74
Price for 0.61 is 0.70
Price for 0.26, is: 0.44
Price for 0.41 is 0.58
Price for 0.70, is: 0.78
Price for 0.22 is 0.38
Price for 0.69, is: 0.78
Price for 0.91 is 0.98
Price for 0.39, is: 0.54</pre>
Price for 0.42 is 0.58</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==