Skip to content

Instantly share code, notes, and snippets.

View CalfordMath's full-sized avatar

Timothy Calford CalfordMath

View GitHub Profile
@CalfordMath
CalfordMath / Minified Sudoku Solver
Last active May 11, 2024 04:58
A 318 character Excel Lambda function that solves any sudoku puzzle fast
S=LAMBDA(p,LET(z,XMATCH(0,TOCOL(--p)),c,LAMBDA(c,x,IF(x>9,0,IF(NOT(OR(INDEX(p,INT((z-1)/9)+1,SEQUENCE(1,9))=x,INDEX(p,SEQUENCE(9),MOD(z-1,9)+1)=x,INDEX(p,SEQUENCE(3,1,INT(((z-1)/27))*3+1),SEQUENCE(1,3,FLOOR(MOD(z-1,9),3)+1))=x)),LET(r,S(IF(SEQUENCE(9,9,1)=z,x,p)),IF(AND(r),r,c(c,x+1))),c(c,x+1)))),IFERROR(c(c,1),p)));
Or a slightly different, even faster solution (332 characters):
S=LAMBDA(p,LET(n,SEQUENCE(9,9,0),z,XMATCH(0,TOCOL(--p))-1,g,LAMBDA(UNIQUE(VSTACK(SEQUENCE(9),TOCOL(INDEX(p,FLOOR(INT(z/9),3)+{1;2;3},FLOOR(MOD(z,9),3)+{1,2,3})),TOCOL(INDEX(p,INT(z/9)+1,)),INDEX(p,,MOD(z,9)+1)),,1)),c,LAMBDA(c,L,x,IF(x>ROWS(L),FALSE,LET(s,S(IF(n=z,INDEX(L,x),p)),IF(MIN(s)>0,s,c(c,L,x+1))))),IFERROR(c(c,g(),1),p)))
//=S(A1:I9) or
//=S({8,0,0,0,0,0,0,0,0;0,0,3,6,0,0,0,0,0;0,7,0,0,9,0,2,0,0;0,5,0,0,0,7,0,0,0;0,0,0,0,4,5,7,0,0;0,0,0,1,0,0,0,3,0;0,0,1,0,0,0,0,6,8;0,0,8,5,0,0,0,1,0;0,9,0,0,0,0,4,0,0})
//credits:
@CalfordMath
CalfordMath / sudoku
Last active April 24, 2024 19:39 — forked from lhem/sudoku
//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(
@CalfordMath
CalfordMath / Sudoku Solver - Excel Formulas Only, (No VBA)
Last active May 4, 2024 23:51
A Lambda Function with nested recursion that receives a 9x9 puzzle range (i.e. B2:J10) and outputs a 9x9 spilled range with the completed puzzle. No VBA. Just formulas. No specific cell references beyond the input range. It takes about 3 minutes and 3 seconds to solve the world's current hardest sudoku puzzle on an average fast computer. It inco…
Sudoku = LAMBDA(Puzzle,
LET(
Options, MAKEARRAY(27, 27, LAMBDA(r, c, MOD(c - 1, 3) + 1 + 3 * MOD(r - 1, 3))),
numgrid, SEQUENCE(9, 9, 1),
UpdatedPuzzle, LET(
ApplyLogic, LAMBDA(ApplyLogic, Puzzle, Options,
LET(
Candidates, MAKEARRAY(
27,
27,