Created
June 4, 2015 14:50
-
-
Save notbenh/dadf9b597cb9616cd257 to your computer and use it in GitHub Desktop.
a few ideas on how to replicate items based on two arrayrefs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Test::More; | |
=head1 GOAL | |
Given two 'matched' arrayrefs : | |
my $items = ['a','b']; | |
my $qty = [ 2 , 4 ]; | |
Build an array (@goal) such that each item in the first array is duplicated the | |
number of times based on the value of the 'matched' second array. Thus given | |
the example $items and $qty, the value of @goal should be (qw{a a b b b b}). | |
=cut | |
# For testing, let's use far more complex data | |
my $items = [qw{ a b c d e f g }]; | |
my $qty = [ 2, 4, 8, 16, 8, 4, 2 ]; | |
my @goal = (qw{ a a | |
b b b b | |
c c c c c c c c | |
d d d d d d d d d d d d d d d d | |
e e e e e e e e | |
f f f f | |
g g | |
}); | |
sub map_and_sub { | |
my ($items,$qty) = @_; | |
sub rep { | |
my ($value,$count) = @_; | |
map{$value} 1..$count; | |
} | |
return map{ rep( $items->[$_], $qty->[$_]) } 0..scalar(@$items)-1; | |
}; | |
sub nested_map { | |
my ($items,$qty) = @_; | |
return map{my $i=$_; map{$items->[$i]} 1..$qty->[$i] } 0..scalar(@$items)-1; | |
}; | |
sub nested_foreach { | |
my ($items,$qty) = @_; | |
my @built; | |
foreach my $index (0..scalar(@$items)-1){ | |
foreach my $i (1..$qty->[$index]){ | |
push @built, $items->[$index]; | |
} | |
} | |
return @built; | |
}; | |
is_deeply [map_and_sub($items,$qty)], \@goal, q{map and sub}; | |
is_deeply [nested_map($items,$qty)], \@goal, q{nested map}; | |
is_deeply [nested_foreach($items,$qty)], \@goal, q{nested foreach}; | |
use Benchmark qw{:all}; | |
cmpthese( 999999, { | |
map_and_sub => sub{ map_and_sub($items,$qty) }, | |
nested_map => sub{ nested_map($items,$qty) }, | |
nested_foreach => sub{ nested_foreach($items,$qty) }, | |
}); | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment