Today's post "Find combination of numbers whose sum equals X" got me wondering about this: what's the "best" (= fastest, most memory-efficient, etc.) way to implement a (typically recursive) "pick without replacement" algorithm like this? Here's an example with splice, plus grepping the indicies, as choroba used here. Who has more ideas?
use warnings; use strict; use Benchmark qw/cmpthese/; my @numbers = ( 0..20 ); my $index = 3; my @expect = ( 0..2,4..20 ); use constant TEST => 0; cmpthese(-2, { splice => sub { my @output = @numbers; splice @output, $index, 1; join("\0", @output) eq join("\0", @expect) or die if TEST; }, grep => sub { # https://www.perlmonks.org/?node_id=11123877 my @output = @numbers[ grep $_ != $index, 0 .. $#numbers ]; join("\0", @output) eq join("\0", @expect) or die if TEST; }, }); __END__ Rate grep splice grep 835107/s -- -68% splice 2575950/s 208% --
In reply to Fastest way to "pick without replacement" by haukex
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |