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)
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |