gr0k has asked for the wisdom of the Perl Monks concerning the following question:
A - 10 B - 5 C - 13 D - 3 E - 15 F - 1And we're searching for amount = 16. That would return 3 possible matches:
A + B + F C + D E + FI came up with a way to do it using the Algorithm::Loops module and calculate all possible permutations down to a certain depth and ignore duplicates (such as ABF, AFB, BFA, etc are all the same thing). The problem is, we need to be able to search through potentially billions of combinations which takes a looooong time. I'm hoping to get some help optimizing my code to make it run faster. Right now with some tests I've run, this code can go through about 5 million combinations in about 3 minutes on a 2.4 ghz.
Which prints out:#!/usr/bin/perl use strict; use Algorithm::Loops qw(NestedLoops); my ($rs_ref,$key,$value,$sum,$count,%matches); my $amount = 16; my $depth = 6; $rs_ref->{'A'}->{'amount'} = 10; $rs_ref->{'B'}->{'amount'} = 5; $rs_ref->{'C'}->{'amount'} = 13; $rs_ref->{'D'}->{'amount'} = 3; $rs_ref->{'E'}->{'amount'} = 15; $rs_ref->{'F'}->{'amount'} = 1; my $start_time = time(); $count = NestedLoops( [ ( [keys %{$rs_ref}] ) x $depth ], { OnlyWhen => sub { @_ == keys %{{@_,reverse@_}}; } }, sub { $sum = 0; foreach $key(@_) { $value = $rs_ref->{$key}->{'amount'}; $sum += $value; } if ($sum == $amount) { $matches{join ' ', sort { $a cmp $b} @_} = 1; } }, ); print "Searched $count combinations...\n"; foreach $key (keys %matches) { print "MATCH: $key\n"; } my $end_time = time(); print "Finished in " . ($end_time - $start_time)/60 . " minutes.\n";
Searched 1956 combinations... MATCH: E F MATCH: A B F MATCH: C D Finished in 0.0166666666666667 minutes.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: amount permutations
by kvale (Monsignor) on Mar 04, 2004 at 18:34 UTC | |
by gr0k (Novice) on Mar 04, 2004 at 19:12 UTC | |
by kvale (Monsignor) on Mar 04, 2004 at 19:28 UTC | |
by gr0k (Novice) on Mar 04, 2004 at 19:51 UTC | |
Re: amount permutations
by Abigail-II (Bishop) on Mar 04, 2004 at 17:25 UTC | |
Re: amount permutations
by Limbic~Region (Chancellor) on Mar 04, 2004 at 18:59 UTC | |
by gr0k (Novice) on Mar 04, 2004 at 19:55 UTC | |
by Limbic~Region (Chancellor) on Mar 04, 2004 at 20:01 UTC | |
by gr0k (Novice) on Mar 04, 2004 at 22:27 UTC | |
by Limbic~Region (Chancellor) on Mar 04, 2004 at 22:43 UTC | |
by tye (Sage) on Mar 05, 2004 at 03:37 UTC | |
by Limbic~Region (Chancellor) on Mar 05, 2004 at 13:23 UTC | |
by gr0k (Novice) on Mar 05, 2004 at 15:26 UTC | |
by Limbic~Region (Chancellor) on Mar 05, 2004 at 15:54 UTC | |
| |
Re: amount permutations
by tachyon (Chancellor) on Mar 04, 2004 at 18:49 UTC | |
by gr0k (Novice) on Mar 04, 2004 at 19:13 UTC |