Hi Monks!
I have the following task:
I have an empty array of length say 600 and a number, say 10.
I want to create 1000 such arrays (and subsequently strings using 'join') by randomly assigning 10 positions in each array to be 'X' while the remaining 590 will be '-'.
I did the following:
@array=(); for($i=1; $i<=10; $i++) { $random_number = rand(600); if($array[$random_number] ne 'X' ) {$array[$random_number]='X';} else {$random_number = rand(600);} } for ($j=0; $j<600; $j++) { if($array[$j] ne 'X') {$array[$j]='-'} } $joined_new_string=join('', @array);

My problem is that I must be doing something wrong, because not all 600 strings produced have 10 positions with 'X' each. And I am suspecting that in my first for loop, I must somehow "remove" the position that is assigned a 'X' in each randomization, because if, for example, in the first run, I assign the 'X' in position 55, the next rand(600) might also give 55 and I will miss one assignment.
How can this be solved?

In reply to Difficulty in randomization by Anonymous Monk

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.