Here is a first shot, I get perl to allocate me a zero filled string of the correct size. calculate a chance step based on number of numbers left to find. Pick a random number then decrement this in countstep increments each time if find an unset bit in my string. once this is < 0 I look for the next unset bit (if I am not on one), set the bit and return its index.
I can think of a couple of optimisations, moving the endpoints would be a help. for the early numbers I may partiton the space and dive into about the right subblock searching from there although this does risk reducing the randomness...#!/usr/local/bin/perl use strict; my $number=1000; my $string; vec $string, $number, 1; while ($number) { my $chance_step = 1/$number; my $rand=rand; my $i=0; while ($rand > 0) { if (vec $string, $i++, 1) { next } else { $rand-=$chance_step } } while (vec $string, $i, 1){$i++} vec($string, $i, 1)=1; print "$i, "; $number-- }
Cheers,
R.
In reply to Re: Generating 0 .. N Randomly and Efficiently
by Random_Walk
in thread Generating 0 .. N Randomly and Efficiently
by Limbic~Region
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |