Price fraction: Difference between revisions

Updated to work with Nim 1.4. Done heavy restructuring and simplification, but kept the algorithm.
(Add Quackery)
(Updated to work with Nim 1.4. Done heavy restructuring and simplification, but kept the algorithm.)
Line 2,769:
 
=={{header|Nim}}==
<lang nim>import strutilsrandom, mathstrformat
 
# 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: array[0 .. 19, int]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)
## indxIndex: 0.1-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 valu: intvalue = toIntint(f * 100)
if value == 0: return StandardValue(10)
dec value
# incIncrement indxindex every 5 of valuvalue, so value ofin 1..100 translates to indxindex ofin 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 _ ifin p0 <.. 10:
let price = rand(1.01)
echo &"Price for {price:.2f} is {price.toStandardValue()}"</lang>
{{out}}
A random output looking something like this:
<pre>Price for 0.73,88 is: 0.8294
Price for 0.29,58 is: 0.4470
Price for 0.25,67 is: 0.3878
Price for 0.52,53 is: 0.66
Price for 0.66,56 is: 0.7866
Price for 0.23,02 is: 0.3810
Price for 0.62,61 is: 0.7470
Price for 0.26,41 is: 0.4458
Price for 0.70,22 is: 0.7838
Price for 0.69,91 is: 0.7898
Price for 0.39,42 is: 0.5458</pre>
 
=={{header|Objeck}}==
Anonymous user