Price list behind API: Difference between revisions

m (→‎{{header|Phix}}: added syntax colouring the hard way)
Line 209:
From 99667.0 ... 100309.0 with 320 items.
</pre>
 
=={{header|Nim}}==
{{trans|Go}}
<lang Nim>import math, strformat
 
const MinDelta = 1.0
 
type Result = tuple[min, max: float; count: int]
 
 
func getPRangeCount(prices: seq[float]; min, max: float): int =
for price in prices:
if price in min..max:
inc result
 
 
func get5000(prices: seq[float]; min, max: float; n: int): (float, int) =
var
count = prices.getPRangeCount(min, max)
delta = (max - min) / 2
max = max
while count != n and delta >= MinDelta / 2:
if count > n: max -= delta
else: max += delta
max = floor(max)
count = getPRangeCount(prices, min, max)
delta /= 2
result = (max, count)
 
 
func getAll5000(prices: seq[float]; min, max: float; n: int): seq[Result] =
var (pmax, pcount) = prices.get5000(min, max, n)
result = @[(min, pmax, pcount)]
while pmax < max:
let pmin = pmax + 1
(pmax, pcount) = prices.get5000(pmin, max, n)
if pcount == 0:
raise newException(ValueError, &"Price list from {pmin} has too many with same price.")
result.add (pmin, pmax, pcount)
 
 
when isMainModule:
import random, sequtils
randomize()
 
let numPrices = rand(99_000..101_000)
const MaxPrice = 100_000
let prices = newSeqWith(numPrices, rand(1..MaxPrice).toFloat)
let actualMax = max(prices)
echo &"Using {numPrices} items with prices from 0 to {actualMax.int}:"
 
let res = prices.getAll5000(0, actualMax, 5000)
echo &"Split into {res.len} bins of approx 5000 elements:"
var total = 0
for (minf, maxf, count) in res:
let min = minf.toInt
let max = min(maxf, actualMax).toInt
inc total, count
echo &" From {min:6} to {max:6} with {count:4} items"
 
if total != numPrices:
echo &"Something went wrong: grand total of {total} doesn't equal {numPrices}!"</lang>
 
{{out}}
<pre>Using 99244 items with prices from 0 to 100000:
Split into 20 bins of approx 5000 elements:
From 0 to 4933 with 5000 items
From 4934 to 9949 with 4999 items
From 9950 to 15074 with 4998 items
From 15075 to 20081 with 5000 items
From 20082 to 25011 with 5000 items
From 25012 to 30106 with 5000 items
From 30107 to 35208 with 5000 items
From 35209 to 40210 with 4998 items
From 40211 to 45208 with 4996 items
From 45209 to 50271 with 5000 items
From 50272 to 55318 with 4996 items
From 55319 to 60384 with 5000 items
From 60385 to 65323 with 5000 items
From 65324 to 70425 with 5000 items
From 70426 to 75509 with 4998 items
From 75510 to 80536 with 4999 items
From 80537 to 85603 with 4999 items
From 85604 to 90642 with 5000 items
From 90643 to 95681 with 4999 items
From 95682 to 100000 with 4262 items</pre>
 
=={{header|Perl}}==
Anonymous user