#!/usr/bin/perl
use v5.14;
use warnings;

my @initial = (
	[qw/1 1 1 0/],
	[qw/0 0 0 0/],
	[qw/0 0 0 0/],
	[qw/0 0 0 0/],
  );

my @diffs = (
	[-1,  0],
	[-1,  1],
	[0 ,  1],
	[1 ,  1],
	[1 ,  0],
	[1 , -1],
	[0 , -1],
	[-1, -1]
);

sub sum_for_diff {
	my ($diff) = @_;
	my @result;
	my ($dx, $dy) = @{$diffs[$diff]};
	for my $i (0 .. 3) {
		for my $j (0 .. 3) {
			my $ni = ($i + 4 + $dx) % 4;
			my $nj = ($j + 4 + $dy) % 4;
			$result[$i][$j] = $initial[$ni][$nj];
		}
	}
#	say 'For diff ', $diff, ': ';
#	say join ' ', @$_ for @result;
	@result
}

use Data::Dumper;

my @sum1;
my @sum2;

for my $x (qw/0 2 4 6/) {
	@sum1 = sum_for_diff $x;
	@sum2 = sum_for_diff ($x+1);

	my ($sum1, $sum2, $sumA, $sumB) = (0, 0, 0, 0);
	my $cnt = 0;
	for my $i (0 .. 3) {
		for my $j (0 .. 3) {
			my $sum = $sum1[$i][$j] + $sum2[$i][$j];
			$sum1 += $sum1[$i][$j] << $cnt;
			$sum2 += $sum2[$i][$j] << $cnt;
			$sumA += ($sum&1) << $cnt;
			$sumB += ($sum&2) << ($cnt - 1);
			$cnt++;
		}
	}

	printf "%04X + %04X = %016b %016b\n", $sum1, $sum2, $sumA, $sumB;
}
