Re: rand()




----- Original Message ----- From: "Bobby" <cybercruiserz@xxxxxxxxx>
Newsgroups: perl.beginners
To: <beginners@xxxxxxxx>
Sent: Monday, July 28, 2008 10:54 AM
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


.



Relevant Pages

  • Re: rand()
    ... 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. ... There will be no duplicates only if there are no duplicates in the original array. ...
    (perl.beginners)
  • 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: 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)
  • Re: Card dealing and random repetition
    ... inspiring for an 'elegant' way to simulate a shuffle. ... The dealer divide the deck in two parts, array ... left-half-deck (here there is a slight probability of 2 card staying ...
    (comp.programming)
  • Re: randomly choose some uniq elements of an array
    ... >> Why do you think it makes sense to shuffle the whole array in order to ... > whole array (i.e. do a length-changing splice) in order to pick three ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)