Skip to content

Instantly share code, notes, and snippets.

@CalfordMath
Last active May 11, 2024 04:58
Show Gist options
  • Save CalfordMath/aecef09b271fd8970b37ef8fe4ba5756 to your computer and use it in GitHub Desktop.
Save CalfordMath/aecef09b271fd8970b37ef8fe4ba5756 to your computer and use it in GitHub Desktop.
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:
//https://www.reddit.com/r/excel/comments/18c5pm0/sudoku_solver_in_a_single_formula/
//https://gist.github.com/lhem/938a4e4a624bd2f68b6f7362b7971004
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment