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


In reply to Re: Lottery using arrays by Athanasius
in thread Lottery using arrays by perlguru22

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.