Skip to content

Instantly share code, notes, and snippets.

@CalfordMath
Forked from lhem/sudoku
Last active April 24, 2024 19:39
Show Gist options
  • Select an option

  • Save CalfordMath/0aaa29d5dbaa50a85211253f6febf03f to your computer and use it in GitHub Desktop.

Select an option

Save CalfordMath/0aaa29d5dbaa50a85211253f6febf03f to your computer and use it in GitHub Desktop.
//ref: https://codereview.stackexchange.com/q/199771
//CalfordMath edit notes:
//I placed the "test" lambda inside of "solver" to acheive a single Lambda function (nested recursive).
//I'm not sure this optimizes anything computationally, and perhaps it makes the code less easy to follow,
//but I find it satisfying to have everything wrapped in a single function :)
solver = LAMBDA(grid,
LET(
numbers, SEQUENCE(9),
numgrid, SEQUENCE(9, 9, 0),
pos, XMATCH(0, TOCOL(grid * 1)) - 1,
IF(
ISNA(pos),
grid,
LET(
i, INT(pos / 9),
j, MOD(pos, 9),
row, INDEX(grid, i + 1, ),
col, INDEX(grid, , j + 1),
sqr, INDEX(grid, FLOOR(i, 3) + {1; 2; 3}, FLOOR(j, 3) + {1, 2, 3}),
values, UNIQUE(VSTACK(numbers, col, TOCOL(row), TOCOL(sqr)), , 1),
test, LAMBDA(test, values, function,
IF(COUNT(values),
IFNA(function(@values),
test(test, DROP(values, 1), function)
),
NA()
)
),
test(test, values, LAMBDA(value, solver(IF(numgrid = pos, value, grid))))
)
)
)
);
//example:
//=solver({
//0,0,0,0,0,0,0,9,0;
//0,9,7,0,0,0,4,0,0;
//0,0,8,0,6,0,0,7,0;
//0,0,0,9,8,7,0,0,0;
//0,0,0,0,0,4,0,0,1;
//0,0,0,0,0,6,0,2,4;
//2,0,0,0,0,0,5,0,3;
//0,4,0,0,5,0,0,0,0;
//6,0,0,8,0,0,0,0,0})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment