in reply to How do I get my code to not repeat numbers and also sort the numbers

First, it's considered good form once you've started asking questions on a piece of code to continue in the same thread, or at least reference the original thread to help monks keep track. In this case, you'd link to How to generate lotto numbers, i.e. How many tickets do you want? 3 and it prints 3..and so on... with [id://843936] -- see Markup in the Monastery.

Since you need something closer to a grab bag, I would suggest you use a list of acceptable numbers. A great utility for mixing them is shuffle in List::Util. The following sample code populates an array with numbers between 1 and 30, mixes the bag, grabs 5 values, and then prints them:

use strict; use warnings; use List::Util qw(shuffle); my @bag = (1 .. 30); # Populate list using the range operator @bag = shuffle(@bag); # Shuffle the bag and store the results my @values = @bag[0..4]; # Get the first 5 results with an array slice print "Your numbers are @values\n";

Replies are listed 'Best First'.
Re^2: Take out repeating numbers with grep
by tangieb01 (Novice) on Jun 10, 2010 at 00:05 UTC

    I was able to get the code to sort. But I am trying to use grep to take out the repeating numbers. How do I do that? This is what I have below.

    for ($i_lottery=0; $i_lottery<$NumberOfTickets; $i_lottery++) { for ($i=0; $i<$NumbersOnTickets; $i++) { $lotto[$i]= int(rand($HighestNumberOnTicket)) + 1; } grep($NumbersOnTickets,@lotto); $NumbersOnTickets=@lotto; @sorted = sort { $a <=> $b } @lotto; print "@sorted"; print "<P>"; }
      Won't filtering out duplicates leave you with too few numbers? If that's what you want, here you go:
      my %seen; my @unique = grep !$seen{$_}++, @numbers;

      This is in perlfaq4

Re^2: How do I get my code to not repeat numbers and also sort the numbers
by tangieb01 (Novice) on Jun 09, 2010 at 23:07 UTC

    Thanks...sorry. I didn't know how to link.

      Don't worry about it. We don't expect you not to make mistakes - we simply expect you to learn from them.