Loading solver…

CP-SAT - Magic Square

Problem: fill a square grid with distinct numbers so every row, column, and diagonal has the same sum.

Show code
import { CpModel, CpSat, sum } from 'or-tools-wasm/cp-sat';

const size = 5;
const numCells = size * size;
const model = new CpModel();
const cells = Array.from({ length: numCells }, (_, index) =>
  model.newIntVar(1, numCells, `cell_${index}`));
model.addAllDifferent(cells);
const target = (size * (numCells + 1)) / 2;
const addSum = (indices: number[]) =>
  model.addEquality(sum(indices.map((index) => cells[index])), target);

for (let row = 0; row < size; row += 1) {
  addSum(Array.from({ length: size }, (_, column) => row * size + column));
}
for (let column = 0; column < size; column += 1) {
  addSum(Array.from({ length: size }, (_, row) => row * size + column));
}
addSum(Array.from({ length: size }, (_, index) => index * size + index));
addSum(Array.from({ length: size }, (_, index) => index * size + size - index - 1));

const result = await CpSat.solve(model, {
  executor: 'worker',
  numWorkers: 4,
  logSearchProgress: true,
});
if (result.hasSolution) console.log(cells.map((cell) => result.value(cell)));

This page exercises the cp_sat_api WASM module by building and solving a magic square model directly in the browser.

Model

  • Each grid cell is an integer decision variable.
  • All numbers in the square must be distinct.
  • Every row, column, and diagonal must have the same magic sum.
  • CP-SAT searches for a grid assignment satisfying all arithmetic constraints.

Latest solution:

Run the solver to view a magic square.

Status / Response: