Shlomi Fish avatar Shlomi Fish committed 5bbaa0c

Add the take4.

Comments (0)

Files changed (1)

project-euler/122/euler-122-take4.pl

+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use integer;
+
+use List::MoreUtils qw(uniq);
+use List::Util qw(min);
+use List::UtilsBy qw(min_by);
+use IO::Handle;
+
+STDOUT->autoflush(1);
+
+my $comb1 = '';
+vec($comb1, 1, 1) = 1;
+
+my @compositions = (undef, [$comb1],);
+
+my $limit = 200;
+
+my $power_of_2 = 2;
+
+while ($power_of_2 < $limit)
+{
+    my $v = $compositions[$power_of_2/2][0];
+
+    vec($v, $power_of_2, 1) = 1;
+    push @{$compositions[$power_of_2]}, $v;
+
+    my $less_sig = $power_of_2;
+    $less_sig /= 2;
+
+    while ($less_sig >= 1)
+    {
+        my $v2 = $v;
+        vec($v2, $power_of_2+$less_sig, 1) = 1;
+        push @{$compositions[$power_of_2+$less_sig]}, $v2;
+    }
+    continue
+    {
+        $less_sig /= 2;
+    }
+}
+continue
+{
+    $power_of_2 *= 2;
+}
+
+my $sum = 0;
+
+N_LOOP:
+foreach my $n (1 .. 200)
+{
+    if (!defined($compositions[$n]))
+    {
+        print "${n}: Unavailable\n";
+        next N_LOOP;
+    }
+    my $optimal_comb = min_by { unpack("b*", $_) =~ tr/1/1/ } @{$compositions[$n]};
+
+    my $comb = unpack("b*", $optimal_comb);
+    my $result = -1 + $comb =~ tr/1/1/;
+    print "${n}: $result ($comb)\n";
+
+    $sum += $result;
+}
+
+print "Sum = $sum\n";
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.