I am creating a quiz program that reads its questions from a text
file into a hash. It will then pull random questions from the hash,
based upon how many questions the person wishes to answer.
Here is the code:
#!/usr/bin/perl -w use strict; srand(); my @array1=(); my $Max_Questions = 30; #Will vary upon how many questions #the person wants to answer my $ref = random(\@array1,$Max_Questions); sub random{ my $array = shift; my $Max = shift; my $lines = 100; #There is a function that gets the #number of lines in the actual data #file, but there will be at least 100. my $num = int(rand($lines)+1); push(@$array,$num); my $length = @$array; my $backcheck = 0; while($length != $Max){ my $numcheck = $num; $num = int(rand($lines)+1); if(($numcheck != $num) && ($num != @$array[$backcheck])){ push(@$array,$num); $length += 1; $backcheck = $length-2; } } my @sorted = sort {$a<=>$b} @$array; print"Element\t\tUnsorted\tSorted\n"; print"-------\t\t--------\t------\n"; for(my $z = 0;$z<$Max;$z++){ print" $z"; print"\t\t @$array[$z]\t\t"; print" $sorted[$z]\n"; } }
And here are the results:
Element Unsorted Sorted ------- -------- ------ 0 83 2 1 99 9 2 63 23 3 24 24 4 41 27 5 2 28 6 72 29 7 65 33 8 33 39 9 27 40 10 85 41 11 78 41 12 94 46 13 96 47 14 84 58 15 58 61 16 29 63 17 28 65 18 68 68 19 71 71 20 41 72 21 97 78 22 88 83 23 9 84 24 40 85 25 39 88 26 61 94 27 46 96 28 23 97 29 47 99
If you look at elements 10 and 11 of the sorted array, you will notice
it has the same value. That is what I am trying to prevent with the code.
Does anyone have a better way I could achieve this?

TStanley
In the end, there can be only one!

In reply to Creating an array of unique numbers by TStanley

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.