Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Lottery using arrays

by Athanasius (Archbishop)
on Sep 27, 2012 at 04:19 UTC ( [id://995924]=note: print w/replies, xml ) Need Help??


in reply to Lottery using arrays

Hello perlguru22,

Since this looks like a homework assignment, I won’t solve it for you, but I will give you a few pointers:

  1. use strict; and declare variables as lexicals: my @freq;, my @num = 0 .. 54;

  2. @freq is specified to contain 55 elements, with indexes 0 to 54. So there is no point in setting aside 10,000 elements up front! In fact, you needn’t assign any elements up front; just declare the array as my @freq; and the elements will be autovivified (created as needed) as they are referenced in the for loop.

  3. For random integers in the range 0 to 54 inclusive, the formula is int(rand(55)) — see rand.

So, your solution should begin as follows:

#!/usr/bin/perl use strict; use warnings; my @num = (0 .. 54); my @freq; ++$freq[int(rand(55))] for 1 .. 10_000;

At this point, you have to sort the frequencies in descending order. The problem specification says:

You must then manually sort the frequency array in descending order and when swapping values...

The word “manually”, together with the reference to “swapping values”, rules out any recourse to Perl’s sort function. You will no doubt have been given one or more sorting algorithms in your coursework (for example, bubble sort, selection sort, quicksort — see Sorting_algorithm), and your task is to implement one of these to sort both @freq and @num in parallel.

Hint: The swapping part of your code should be something like this:

{ my $temp = $freq[$i]; # swap frequencies $freq[$i] = $freq[$j]; $freq[$j] = $temp; $temp = $num[$i]; # swap numbers $num[$i] = $num[$j]; $num[$j] = $temp; }

Hope that helps,

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: Lottery using arrays
by choroba (Cardinal) on Sep 27, 2012 at 08:36 UTC
    No temp value is needed when swapping in Perl:
    ($freq[$i], $freq[$j]) = ($freq[$j], $freq[$i]);
    or even (using slices):
    @freq[$i, $j] = @freq[$j, $i];
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://995924]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-24 22:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found