Loading solver…
Problem: fill a square grid with distinct numbers so every row, column, and diagonal has the same sum.
This page exercises the cp_sat_api
WASM module by building and solving a magic square model directly in the browser.
Latest solution:
import { BoundedLinearExpr, CpModel, CpSat, Domain, 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).withName(`cell_${index}`));
model.addAllDifferent(cells);
const target = (size * (numCells + 1)) / 2;
const addSum = (indices: number[]) =>
model.add(new BoundedLinearExpr(sum(indices.map((index) => cells[index])), new Domain(target, 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));
console.log(await model.modelStats({ executor: 'worker' }));
console.log(await model.exportModelText({ executor: 'worker' }));
// Individual proto inspection returns a detached snapshot.
console.log(cells[0].proto.domain);
const result = await CpSat.solve(model, {
executor: 'worker',
numWorkers: 4,
logSearchProgress: true,
});
if (result.hasSolution) {
console.log(cells.map((cell) => result.value(cell)));
console.log(await model.solutionIsFeasible(result.response!.solution!, { executor: 'worker' }));
}