implement /api/solve route

This commit is contained in:
StevanFreeborn
2022-05-26 21:37:25 -05:00
parent 9357f7875b
commit 5cbaf153b1
3 changed files with 21 additions and 7 deletions
+7 -2
View File
@@ -6,7 +6,11 @@ class SudokuSolver {
validate(puzzleString) {
return puzzleString.length == 81 && !puzzleString.match(/[^\.\d]/g);
if (puzzleString.length != 81) return 'Expected puzzle to be 81 characters long';
if (puzzleString.match(/[^\.\d]/g)) return 'Invalid characters in puzzle';
return true;
}
@@ -173,7 +177,7 @@ class SudokuSolver {
solve(puzzleString) {
if (!this.validate(puzzleString)) return false;
if (this.validate(puzzleString) != true) return false;
// create character array
let puzzle = puzzleString.split('');
@@ -312,6 +316,7 @@ class SudokuSolver {
let board = generateBoard(puzzle);
let solution = solveFromCell(board, 0, 0);
if (solution == false) return false;
return solution.flat().join('');
}
+11 -2
View File
@@ -1,6 +1,6 @@
'use strict';
const SudokuSolver = require('../controllers/sudoku-solver.js');
const SudokuSolver = require('../controllers/sudoku-solver');
module.exports = function (app) {
@@ -15,9 +15,18 @@ module.exports = function (app) {
.post((req, res) => {
const puzzleString = req.body.puzzle;
console.log(puzzleString);
if (puzzleString == undefined) return res.status(200).json({error: 'Required field missing' });
const validate = solver.validate(puzzleString);
if (validate != true) return res.status(200).json({error: validate});
const solution = solver.solve(puzzleString);
if (solution == false) return res.status(200).json({error: 'Puzzle cannot be solved'});
return res.status(200).json({solution: solution});
});
};
+2 -2
View File
@@ -20,7 +20,7 @@ suite('UnitTests', () => {
const input = puzzlesAndSolutions[0][0].replace(/\./g, '?');
assert.equal(solver.validate(input), false);
assert.equal(solver.validate(input), 'Invalid characters in puzzle');
done();
});
@@ -29,7 +29,7 @@ suite('UnitTests', () => {
const input = puzzlesAndSolutions[0][0] + '0';
assert.equal(solver.validate(input), false);
assert.equal(solver.validate(input), 'Expected puzzle to be 81 characters long');
done();
});