I have a question about rand() ... I have the following code:
#!/usr/bin/perl my @arr = (); my $counter = 1; for($i=0; $i<32; $i++) { while(1) { $rand = int(rand(32)); # print "testing: $rand\n"; if (grep(/$rand/, @arr) == 0) { print "$counter: $rand\n"; push @arr, $rand; $counter++; last; } } }
The goal is to produce random numbers from 0 to 32, but the sequence has to be without repeating any number, whenever I run this code I always get 23 or 24 numbers, after this the computer keeps generating numbers but I can't make the computer generate the last random numbers.
Any ideas?
I ran the code under Fedora, Cygwin and Active Perl but I get the same behavior on all platforms.
This is the output I get:
$ ./create_random_numbers.pl 1: 29 2: 20 3: 27 4: 31 5: 25 6: 21 7: 19 8: 13 9: 26 10: 12 11: 8 12: 28 13: 11 14: 16 15: 22 16: 17 17: 4 18: 10 19: 23 20: 18 21: 24 22: 15 23: 14 24: 30
After this the scripts "hangs" and the CPU goes to almost 100% usage, I have it running for more that 5 minutes but no luck (I am not expecting to run scripts for more than 5 minutes just to generate random numbers)
Thanks for all the replies what I was looking for is what almut wrote, that little part of the regexp made the difference (/^$rand$/). Although I think the idea of using shuffle is good, I never work with that module before. I think basically now I have my own version of shuffle.
Now my next task will be to test the performance using shuffle and using rand, I will see what is faster.
My final code looks like this:
#!/usr/bin/perl my @arr = (); my $counter = 1; my $range; for($i=0; $i<$range; $i++) { while(1) { $rand = int(rand($range)); if (grep(/^$rand$/, @arr) == 0) { print "$rand\n"; push @arr, $rand; $counter++; last; } } }
In reply to How much random is rand()? by gmoque
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |