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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.