I need to generate a random sequence from two arrays into a third array, with the caveat that the values from both arrays remain in their original order. Ie. It's only the sequence in which they get mixed together that is random. Fairness is not a consideration.

I thought (actually, I still think) that this code should do this, and it does except occasionally it throws a blank (undef) in somewhere and I just cannot see why?

#! perl -slw use strict; while( 1 ) { my @t1 = map{ "T1/$_" } 1 .. 7; my @t2 = map{ "T2/$_" } 1 .. 7; my @seq = map{ shift @{ ( ( rand() < .5 ) and @t1 ) ? \@t1 : \@t2 } } 1 .. @t1 + @t2; print @seq . " :@seq"; <STDIN>; } __END__ P:\test>junk.pl 14 :T2/1 T2/2 T1/1 T1/2 T1/3 T2/3 T2/4 T1/4 T2/5 T2/6 T1/5 T2/7 T1/6 T +1/7 Use of uninitialized value in join or string at P:\test\junk.pl line 1 +0, <STDIN> line 1. 14 :T2/1 T1/1 T1/2 T1/3 T1/4 T2/2 T2/3 T2/4 T1/5 T2/5 T1/6 T2/6 T2/7 14 :T1/1 T1/2 T1/3 T1/4 T1/5 T1/6 T2/1 T2/2 T1/7 T2/3 T2/4 T2/5 T2/6 T +2/7 14 :T1/1 T1/2 T1/3 T1/4 T2/1 T1/5 T1/6 T1/7 T2/2 T2/3 T2/4 T2/5 T2/6 T +2/7 Use of uninitialized value in join or string at P:\test\junk.pl line 1 +0, <STDIN> line 4. 14 :T1/1 T2/1 T1/2 T1/3 T2/2 T2/3 T1/4 T2/4 T2/5 T2/6 T1/5 T1/6 T2/7 Terminating on signal SIGINT(2)

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

Janitored by Arunbear - retitled from 'Why doesn't this code do what I think it should?'


In reply to Stable mixing of 2 arrays into a 3rd by BrowserUk

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.