Howdy, welcome to the Monastery!
There's many ways that this could be done. For one, you could check the "candidate" in your loop and get another one from rand if you already saw it before. In the following code, I'm using a hash (associative array) to remember which numbers were already seen:
my $x = 1;
my $y = 20;
my $looptimes = 10;
my %numbers = ();
foreach(1 .. $looptimes) {
my $candidate = -1;
do {
$candidate = int(rand ($y - $x + 1)) + $x;
} while(exists $numbers{$candidate});
$numbers{$candidate} = 1;
}
say join ",", keys %numbers;
If you only care about the result, you could also e.g. take the list of numbers from $x to $y, shuffle it, and then grab the $looptimes numbers. How do I shuffle an array? has more on shuffling arrays; the executive summary is that there's a shuffle function in List::Util (a core module):
use List::Util qw/shuffle/;
my $x = 1;
my $y = 20;
my $looptimes = 10;
my @numbers = shuffle($x .. $y);
say join ",", @numbers[0 .. ($looptimes - 1)];
Though that said I reckon you care more about the "how" than the result.
Since you're starting out, here's a few general suggestions, too.
- use strict, and use warnings. They're your friends, and will catch many common mistakes, typos etc. for you.
- Format your code. Indent loop bodies and other blocks. Add spaces around the equal signs in assignments.
- Use for or foreach loops (exactly the same, BTW) to do something a given number of times; while loops are more appropriate when you don't know how often something'll have to be done.
Hope this helps!
|