Price list behind API: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: default comment)
(Added Wren)
Line 161: Line 161:
From 90215.0 ... 95249.0 with 4999 items.
From 90215.0 ... 95249.0 with 4999 items.
From 95250.0 ... 104742.0 with 4864 items.</pre>
From 95250.0 ... 104742.0 with 4864 items.</pre>

=={{header|Wren}}==
{{trans|Python}}
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "random" for Random
import "/math" for Nums
import "/fmt" for Fmt

var rand = Random.new()

var getMaxPrice = Fn.new { |prices| Nums.max(prices) }

var getPrangeCount = Fn.new { |prices, min, max| prices.count { |p| p >= min && p <= max } }

var get5000 = Fn.new { |prices, min, max, n|
var count = getPrangeCount.call(prices, min, max)
var delta = ((max - min)/2).floor
while (count != n && delta > 0) {
max = (count > n) ? max-delta : max+delta
count = getPrangeCount.call(prices, min, max)
delta = (delta/2).floor
}
return [max, count]
}

var getAll5000 = Fn.new { |prices, min, max, n|
var mc = get5000.call(prices, min, max, n)
var pmax = mc[0]
var pcount = mc[1]
var res = [[min, pmax, pcount]]
while (pmax < max) {
var pmin = pmax + 1
mc = get5000.call(prices, pmin, max, n)
pmax = mc[0]
pcount = mc[1]
res.add([pmin, pmax, pcount])
}
return res
}
var numPrices = 1e5
var maxPrice = 1e5
var prices = List.filled(numPrices, 0) // list of prices
for (i in 1..numPrices) prices[i-1] = rand.int(maxPrice + 1)
var actualMax = getMaxPrice.call(prices)
System.print("Using %(numPrices) items with prices from 0 to %(actualMax):")
var res = getAll5000.call(prices, 0, actualMax, 5000)
System.print("Split into %(res.count) bins of approx 5000 elements:")
var total = 0
for (r in res) {
var min = r[0]
var max = r[1]
if (max > actualMax) max = actualMax
var cnt = r[2]
total = total + cnt
Fmt.print(" From $6d to $6d with $4d items", min, max, cnt)
}
if (total != numPrices) {
System.print("Something went wrong - grand total of %(total) doesn't equal %(numPrices)!")
}</lang>

{{out}}
Sample run:
<pre>
Using 100000 items with prices from 0 to 99998:
Split into 20 bins of approx 5000 elements:
From 0 to 5043 with 5000 items
From 5044 to 10102 with 5001 items
From 10103 to 15192 with 5000 items
From 15193 to 20320 with 5000 items
From 20321 to 25368 with 4998 items
From 25369 to 30376 with 5003 items
From 30377 to 35422 with 5001 items
From 35423 to 40337 with 5001 items
From 40338 to 45299 with 5000 items
From 45300 to 50389 with 5001 items
From 50390 to 55402 with 4998 items
From 55403 to 60382 with 5001 items
From 60383 to 65330 with 4999 items
From 65331 to 70278 with 5001 items
From 70279 to 75285 with 4999 items
From 75286 to 80336 with 5000 items
From 80337 to 85289 with 5000 items
From 85290 to 90291 with 5000 items
From 90292 to 95052 with 5001 items
From 95053 to 99998 with 4996 items
</pre>