in reply to Random number of elements from arrays
Your response (in "Re^2: Random number of elements from arrays") has covered most ambiguities; however, it's still unclear whether you want random elements (as described in text) or unique random elements (as shown in all examples). For instance, you've shown "AX1 AX3" in two examples as "2 random elements from @acc"; but you haven't excluded "AX1 AX1" which would also be perfectly valid as "2 random elements from @acc". I'm assuming you want unique random elements.
In the code below, I've used the fact that hash keys are unsorted (i.e. random) and the keys() function only returns each key once (i.e. unique). That's an oversimplification regarding the randomness of hash keys: see the documentation for more complete details. Also note that the code is only intended to demonstrate a technique: you'll need validation, error checking and so on to make it production-ready.
#!/usr/bin/env perl -l use strict; use warnings; my @acc = qw{AX1 AX2 AX3}; my @sec = qw{PB6 PB7 PB8}; my @third = qw{XC2 XC8 XC1}; my %output_for_option = ( 1 => sub { print "@{get_rand_acc()}" }, 2 => sub { my ($acc, $sec) = (get_rand_acc(), get_rand_sec()); print "@{[ map { $acc->[$_] . $sec->[$_] } 0, 1 ]}"; }, 3 => sub { my ($acc, $third) = (get_rand_acc(), get_rand_third()); print "@{[ map { $acc->[$_] . $third->[$_] } 0, 1 ]}"; }, 4 => sub { my ($acc, $sec, $third) = (get_rand_acc(), get_rand_sec(), get_rand_third()); print "@{[ map { $acc->[$_] . $sec->[$_] . $third->[$_] } 0, 1 + ]}"; }, ); while (<>) { chomp; last unless exists $output_for_option{$_}; $output_for_option{$_}->(); } sub get_rand_acc { get_rand_from_array(\@acc) } sub get_rand_sec { get_rand_from_array(\@sec) } sub get_rand_third { get_rand_from_array(\@third) } sub get_rand_from_array { my %h = map { $_ => undef } @{+shift}; return [ (keys %h)[0, 1] ]; }
Here's a couple of sample runs:
$ pm_1172223_rand_array_concat.pl 1 AX3 AX1 2 AX2PB7 AX3PB6 3 AX3XC2 AX1XC8 4 AX1PB8XC2 AX3PB6XC8 5 $
$ pm_1172223_rand_array_concat.pl 1 AX1 AX3 2 AX1PB7 AX2PB8 3 AX1XC1 AX3XC8 4 AX3PB6XC1 AX2PB8XC2 5 $
— Ken
|
|---|