in reply to Select three random numbers between 1..10

You have the write code to select a single random element from the array. To get unique random numbers, you need to remove that element from the array and then keep selecting from the shorter set. splice lets you do this in one operation.
my @num; my @array = 1 .. 10; for (1..3) { push @num, splice(@array, rand(@array), 1); }

Replies are listed 'Best First'.
Re: Select three random numbers between 1..10
by Abigail-II (Bishop) on Mar 16, 2004 at 21:23 UTC
    You have the write code to select a single random element from the array. To get unique random numbers, you need to remove that element from the array and then keep selecting from the shorter set.
    Luckely, you don't have to. While it hardly matters for an array of 10 elements, the principle doesn't scale. splice is an expensive operation, whose expected run time is Θ (N) for a single delete. If you have to select k elements from an array of size N, you have an expected running time of Θ (k * N). OTOH, if you perform a partial Fisher-Yates shuffle (you only need to get k elements), your running time reduces to O (k) (after setting up the array).

    Abigail

      I didn't think about the efficiency of splice. I originally had it coded to shuffle after selecting the element. In other words, select the random element, swap the last element with the selected one, and shorten the array. Technically, the array does not need to be shortened.