This was harder than I expected, I have been plagued by off by one errors and infinite loops but here is a version with a couple of optimations
It starts out nice and fast but bogs down for big sets looking for those last few unused values and I must admit it is pig ugly code. I think overall Limbic~Region's way of doing it is preferable.
#!/usr/local/bin/perl use strict; use integer; $!++; my $number=10000; my $num_per_block=10; my $string; my $start=0; my $end=$number-1; vec $string, $end, 1; while ($number) { my $block_size=(($end-$start+1)/$number)*$num_per_block; my $rand=int rand($number+1); my $found=1; # optimist my $guess_block=int($rand / $block_size); my $i=$start+($guess_block*$block_size); my $fiddled_rand=$rand-($guess_block*$num_per_block); while ($fiddled_rand > -1) { if (vec $string, $i, 1) { if ($i==$end+1) { # we ran off the end without getting a good number $found=0; last; } }else{ $fiddled_rand--; } $i++; } unless ($found) { $i=$start; while ($rand) { unless (vec $string, $i++, 1) { $rand--; } } } print "$i+"; vec($string, ($i-1), 1)=1; while (vec $string, $start, 1){$start++} while (vec $string, $end, 1){$end--} $number--; }
I have another cunning plan to prevent that horrible slowdown near the end but it is at the cost of more memory (step 1 is thrown this abomination away ;)
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: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |