Alright, here’s a real attempt:
V1 (slower):
ts = timestamp()
mem = heapfree
results = #()
bank = for i = 1 to 1000000 collect i
results[1000000] = undefined
for r = 1 to results.count do
(
local ind = random 1 bank.count
results[r] = bank[ind]
deleteItem bank ind
)
format "Time: %, Memory: %
" (timestamp()-ts) (mem-heapfree)
output: Time: 193635, Memory: 56600400L
v2 (faster):
ts = timestamp()
mem = heapfree
fn sortFn v1 v2 = random -1 1
results = for i = 1 to 1000000 collect i
qsort results sortFn
format "Time: %, Memory: %
" (timestamp()-ts) (mem-heapfree)
output: Time: 17471, Memory: 486304L
v3 (same as v2, less memory):
ts = timestamp()
mem = heapfree
fn sortFn v1 v2 = random -1 1
results = #{1..1000000} as array
qsort results sortFn
format "Time: %, Memory: %
" (timestamp()-ts) (mem-heapfree)
output: Time: 17324, Memory: 239624L
#2 is too bad distributed to be a random (and also too slow)
In what way do you mean bad distributed? Looking at the first several members of the result array seems pretty random…
182857
62009
132850
714306
266778
575397
516856
887176…
EDIT: Ignore my memory readouts, there was not enough heap to count all the way… it is actually 1191513976L :surprised
my_array =#()
for i=0 to 1000000 do(
insertItem i my_array ((random 0 i)+1)
)
it inserts each next number into a random location between 1 and the length of the array.
yep , here is version 2…
fn getRandomNumbers a b =
(
local start = timeStamp()
local fpath = (GetDir #export + "\\random_nums.txt")
deleteFile fpath
local f = createFile fpath
format "#(" to:f
local nums = #{a..b} as array
local random_nums = #()
local line_counter = 0
for n=nums.count to 1 by -1 do
(
local random_pos = random 1 nums.count
line_counter += 1
if line_counter > 100 --next_line
then (format "%,
" nums[random_pos] to:f ; line_counter = 0)
else if nums.count > 1
then (format "%," nums[random_pos] to:f)
else (format "%)
" nums[random_pos] to:f) --if last number, array is cosed
deleteItem nums random_pos
)
close f
local end = timeStamp()
format "Processing took % seconds
" ((end - start) / 1000.0)
)
getRandomNumbers 1 1000000
Processing took 245.09 seconds
ts = timestamp()
mem = heapfree
results = #{1..1000000} as array
for i = 1 to 1000000 do swap results[i] (results[random 1 1000000])
format "Time: %, Memory: %
" (timestamp()-ts) (mem-heapfree)
Time: 1233, Memory: 56002608L
DO I WIN? :deal:
this is the minimal memory for creating an array of 1000000 integers… is returning an array a requisite of the challenge or can I directly write to a stream?
it’s not true… you allocate double memory… for bitarray first and for array after. also swap is not memory free
As far as I can tell, the memory allocation for a bitarray is negligible, so is the usage of swap.
even this code uses up 56mb:
arr=#()
arr[1000000]=1000000
for i = 1 to 1000000 do arr[i]=i
Is there something obvious I am missing?
Matan, that looks very similar to mine. I knew I should have encrypted it…