ExercisesHooks
useLatinSquare
Fill an n×n grid so each element appears once per row and column
State for a Latin-square grid: n elements, each placed n times, so that no element repeats in a row or column. Elements are referred to by their index (0 to n - 1). Used by LatinSquare. Optional onSuccess / onFailure run after check() — see Check callbacks.
With checkOn: "auto", the grid is checked only once every cell is filled.
Options
| Option | Description |
|---|---|
size | Grid size n |
givens | Optional locked cells: givens[row][col] is an element index or null |
checkOn | "manual" (default) or "auto" |
labels, onSuccess, onFailure | As for every exercise hook |
Key returns
| Property | Description |
|---|---|
cells | Flat, row-major list of n² cells. Each is an element index or null |
isGiven | isGiven[cell] is true for locked cells |
remaining | Copies of each element still available: remaining[value] |
conflicts | Set of cells whose element repeats in the same row or column |
place({ cell, value }) | Put a copy of value in cell, replacing what was there |
move({ from, to }) | Move the element from one cell to another; what was in to goes back to the bar |
clear(cell) | Remove the element from cell |
isCorrect | null until checked, then whether the grid is full and has no conflicts |
check | Validate the grid |
reset | Clear every cell except the givens |
All actions ignore locked cells, and place ignores elements with no copies left.
Example
import { useLatinSquare } from '@bside-tech/tbx-ui/hooks';
const size = 3;
const { cells, remaining, conflicts, place, move, clear, check } = useLatinSquare({
size,
givens: [
[0, null, null],
[null, null, null],
[null, null, 0],
],
});
place({ cell: 1, value: 1 }); // row 0, col 1
move({ from: 1, to: 2 }); // row 0, col 2
clear(2);
check(); // false until every cell is filled with no repeats