Shlomi Fish avatar Shlomi Fish committed 3bbcee5

Added cache.

Comments (0)

Files changed (1)

project-euler/77/Euler77.pm

 my @primes = `primes 2 10000`;
 chomp(@primes);
 
+my @cache;
+
 sub get_combinations
 {
     my ($prefix, $start_from_max_prime_idx, $sum, $out_combinations_ref) = @_;
 
-    my @combinations;
+    my $combinations = [];
     
     if ($sum == 0)
     {
-        @combinations = ([]);
+        push @$combinations, [];
+    }
+    elsif (defined($cache[$sum][$start_from_max_prime_idx]))
+    {
+        $combinations = $cache[$sum][$start_from_max_prime_idx];
     }
     else
     {
                 [$max_prime], 
                 $max_prime_idx, 
                 $sum-$max_prime, 
-                \@combinations
+                $combinations
             );
         }
+
+        $cache[$sum][$start_from_max_prime_idx] = $combinations;
     }
 
-    push @$out_combinations_ref, (map { [@$prefix, @$_] } @combinations);
+
+    push @$out_combinations_ref, (map { [@$prefix, @$_] } @$combinations);
 
     return;
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.