in reply to random index in array - no duplicates

another thing (not optimized but i hope clear enough) not exactly for the same use (i needed to keep the values of a column) so it is more an array to anonymise some labels. i use it for blind tests
my @tab_anonyme; for $i (0..$#my_data) { $tab_anonyme[$i][0] = $my_data[$i][0]; # data to keep $tab_anonyme[$i][1] = int ( rand (100) ) + 1; # anonyme label } # verification my $flag_duplicate; do { $flag_duplicate = "false"; for $i (0..$#tab_anonyme) { for $i2 (0..$#tab_anonyme) { if ($i2 == $i) { next; } # no testing of a value against i +tself if ( $tab_anonyme[$i][1] == $tab_anonyme[$i2][1] ) { $tab_anonyme[$i2][1] = int ( rand (100) ) + 1; $flag_duplicate = "true"; } } } } while ( $flag_doublon eq "true" );
two problems

- in rand(X), if X is smaller than the number of lines of the array @mydata => infinite loop, make it four or five time bigger

- time taken is not very predictible

Replies are listed 'Best First'.
Re^2: random index in array - no duplicates
by Anonymous Monk on Jul 08, 2016 at 13:41 UTC

    The answer is still shuffle. Your problem can be broken down in two parts: (1) constructing a list of random labels; (2) assembling the required data structure. Shuffle solves the first part, tutorials (perldsc, perllol) for working with structured data may help you with the latter.

    use List::Util qw( shuffle ); my @data = map { [$_, undef] } qw( v1 v2 v3 v4 v5 ); my @shuf = shuffle 0..$#data; my @tab = map { [$data[$_][0], $shuf[$_]] } 0..$#data; use Data::Dumper; print Data::Dumper->Dump([\@data, \@tab], [qw(*data *tab)]);

    Please, if you need help or advice with your programming tasks, post them as new questions in Seekers of Perl Wisdom.