Skip to content

Commit

Permalink
fix: return null instead of crashing when no solution is found (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
sven-strothoff committed May 9, 2024
1 parent 4996f06 commit 6b3da49
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/lib/solve.js
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,9 @@
state = freeStates.pop().init(this);
phase1search(state);
freeStates.push(state);
if (solution == null) {
return null;
}
// Trim the trailing space and return
return solution.trim();
};
Expand Down Expand Up @@ -934,6 +937,9 @@
clone.move(upright);
rotation = new Cube().move(upright).center;
uprightSolution = clone.solveUpright(maxDepth);
if (uprightSolution == null) {
return null;
}
solution = [];
ref = uprightSolution.split(' ');
for (m = 0, len = ref.length; m < len; m++) {
Expand Down
6 changes: 6 additions & 0 deletions lib/solve.js
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,9 @@
state = freeStates.pop().init(this);
phase1search(state);
freeStates.push(state);
if (solution == null) {
return null;
}
// Trim the trailing space and return
return solution.trim();
};
Expand Down Expand Up @@ -934,6 +937,9 @@
clone.move(upright);
rotation = new Cube().move(upright).center;
uprightSolution = clone.solveUpright(maxDepth);
if (uprightSolution == null) {
return null;
}
solution = [];
ref = uprightSolution.split(' ');
for (m = 0, len = ref.length; m < len; m++) {
Expand Down
6 changes: 6 additions & 0 deletions spec/cube.spec.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,9 @@ describe 'Cube', ->
Cube.initSolver()
cube = new Cube
expect(cube.solve()).toBe "R L U2 R L F2 R2 U2 R2 F2 R2 U2 F2 L2"

# ignore because Travis is slow
xit 'should return null if no solution is found (maxDepth too low)', ->
Cube.initSolver()
cube = Cube.random()
expect(cube.solve(1)).toBe null
2 changes: 2 additions & 0 deletions src/solve.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,7 @@ Cube::solveUpright = (maxDepth=22) ->
phase1search(state)
freeStates.push(state)

return null if not solution?
# Trim the trailing space and return
solution.trim()

Expand All @@ -687,6 +688,7 @@ Cube::solve = (maxDepth=22) ->
clone.move upright
rotation = new Cube().move(upright).center
uprightSolution = clone.solveUpright maxDepth
return null if not uprightSolution?
solution = []
for move in uprightSolution.split ' '
solution.push faceNames[rotation[faceNums[move[0]]]]
Expand Down

0 comments on commit 6b3da49

Please sign in to comment.