Created
April 17, 2020 19:23
-
-
Save joriki/1e7b7a917f3555edad9cf85b097fd51a to your computer and use it in GitHub Desktop.
Find all magic 4x4 squares in which the sum in each 2x2 subsquare is the magic sum; see https://math.stackexchange.com/questions/3629762.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Question3629762 { | |
static class Constraint { | |
int [] cells; | |
int sum; | |
public Constraint(int [] cells) { | |
this.cells = cells; | |
} | |
} | |
static List<Constraint> [] constraints = new List [16]; | |
static int count; | |
public static void main(String [] args) { | |
for (int i = 0;i < constraints.length;i++) | |
constraints [i] = new ArrayList<>(); | |
for (int x = 0;x < 3;x++) | |
for (int y = 0;y < 3;y++) { | |
int p = x + (y << 2); | |
addConstraint(p,p + 1,p + 4,p + 5); | |
} | |
addConstraint(0,5,10,15); | |
addConstraint(3,6,9,12); | |
for (int i = 0;i < 4;i++) { | |
addConstraint(i,i + 4,i + 8,i + 12); | |
addConstraint(4 * i,4 * i + 1,4 * i + 2,4 * i + 3); | |
} | |
recurse(new int [16],new boolean [16],0); | |
System.out.println(count); | |
} | |
static void addConstraint (int ... cells) { | |
if (cells.length != 4) | |
throw new Error(); | |
Constraint constraint = new Constraint(cells); | |
for(int c : cells) | |
constraints [c].add(constraint); | |
} | |
static void recurse(int [] square,boolean [] used,int index) { | |
if (index == 16) { | |
System.out.println(Arrays.toString(square)); | |
count++; | |
} | |
else { | |
for (square [index] = 0;square [index] < 16;square [index]++) { | |
if (used [square [index]]) | |
continue; | |
if (((index == 3 || index == 12 || index == 15) && square [index] > square [0]) || | |
(index == 4 && square [index] > square [1])) | |
break; | |
boolean constraintsFulfilled = true; | |
for (Constraint constraint : constraints [index]) { | |
constraint.sum += square [index]; | |
constraintsFulfilled &= index != constraint.cells [3] || constraint.sum == 30; | |
} | |
if (constraintsFulfilled) { | |
used [square [index]] = true; | |
recurse (square,used,index + 1); | |
used [square [index]] = false; | |
} | |
for (Constraint constraint : constraints [index]) | |
constraint.sum -= square [index]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment