0

Hi - Major novice here. I'm trying to write a code that starts with a user defined number (lets say "N"), picks a random number between 1 and N (lets say "R"), pushes R onto an array, subtracts R from N, then picks the next random number from (N-R), pushes the new number onto the array...etc...and loops this until (N-R)==0.

The code I have seems to go into an infinite loop or something... any help would be great and if there's an obvious solution, I apologize in advance. Thanks!

use warnings; use strict;
my @list;
print "Enter number of OTUs:";
my $start = <STDIN>;
do {
my $rand = int(rand($start));
push (@list, $rand);
$start-=$rand;
} until ($start ==0);

print "@list";

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by LSU_223
0

"do" is not really a loop but if you use "until" or "while" with it you can get it to act like a loop. The problem with your code is that $start never has a chance to equal zero so the "do" block just keeps getting repeated over and over. Thix will help you see whats going on:

use warnings;
use strict;
my @list;
print "Enter number of OTUs:";
my $start = <STDIN>;
chomp $start;
do {
my $rand = int(rand($start));
print "rand = $rand\n";
push (@list, $rand);
$start-=$rand;
print "\$start = $start\n";
} until ($start == 0);

print "@list";
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.