Re: rand()



From: ""Chris Charley""


From: "Bobby" Newsgroups: perl.beginners


Subject: rand()


Hi all,

How do I use the rand function to print out more than one random number for an array? In the example script below i have an array @nums with a list of numbers; how do i print out more than one random numbers from that list (@nums)? Thanks.

You can use 'shuffle' from List::Util.

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw/ shuffle /;

my $max = 3;
my @nums = ("10000","10002","10004","10005","10006","140000","1500000");
my @winner = (shuffle @nums)[0 .. $max - 1];

print "@winner";

'shuffle' does what its name says - shuffles the list items. You will get no duplicates.

Chris

Just to clarify a possible misunderstanding. There will be no duplicates only if there are no duplicates in the original array. 'shuffle' doesn't filter out duplicates - it just shuffles the list.

Chris


.



Relevant Pages

  • Re: rand()
    ... Newsgroups: perl.beginners ... How do I use the rand function to print out more than one random number for an array? ... You can use 'shuffle' from List::Util. ...
    (perl.beginners)
  • Re: Random numbers with no duplicates
    ... >duplicates occurring in them? ... Depends on the relative sizes of the range and the set of random ... Shuffle. ... Use the set to initialise a vector (or array) ...
    (alt.comp.lang.learn.c-cpp)
  • Re: "how to split a string in a random way"
    ... I created an integer array and I pass it along with a ... number to Factorize(). ... This time I send array1 through the Shuffle() method just prior to sending ... Dim array3 As Integer= Utility.GenArray ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Elementary but surprisingly difficult.
    ... the original message from Albert-- the one I first replied to-- described the problem as removing duplicates from an array. ... Now I hate to get all Computer Science on everyone, but the very definition of array denotes an ordering; you can say the "first" item in an array, and it has clear and unambiguously meaning. ... So no, if preserving the original order mattered, "bdeca" wouldn't work, because the original order had a "a" as the *first* element. ... When a duplicate item is found, the "read" pointer is advanced past the item and the write pointer is left where it is. ...
    (comp.lang.forth)
  • Re: round-robin an arraylist
    ... Of all of them the work on the Array is the fastest. ... RemoveAt(), Addparadigm to do the shuffle is only slightly slower than the ... public class RoundRobin { ...
    (microsoft.public.dotnet.languages.csharp)