Sudoku validation “no duplicate elements in columns” Js
Hi, the challenge is – Sudoku validation and we need to make sure Each column in the puzzle is exactly 1 through 9. No duplicates.
Example boards:
Solution:
// NO DUPLICATED ELEMENTS IN ROWS= FALSE
const goodPuzzle = [
[8, 3, 5, 4, 1, 6, 9, 2, 7], // row
[2, 9, 6, 8, 5, 7, 4, 3, 1], // row
[4, 1, 7, 2, 9, 3, 6, 5, 8], // row
[5, 6, 9, 1, 3, 4, 7, 8, 2], // row
[1, 2, 3, 6, 7, 8, 5, 4, 9], // row
[7, 4, 8, 5, 2, 9, 1, 6, 3], // row
[6, 5, 2, 7, 8, 1, 3, 9, 4], // row
[9, 8, 1, 3, 4, 5, 2, 7, 6], // row
[3, 7, 4, 9, 6, 2, 8, 1, 5], // row
];
// YES DUPLICATED ELEMENTS IN ROWS = TRUE
// columns
// 0, 1, 2, 3, 4, 5, 6, 7, 8
const badPuzzle = [
[1, 3, 5, 4, 8, 6, 9, 2, 7], // row
[2, 9, 6, 8, 5, 7, 4, 3, 1], // row
[4, 1, 3, 2, 4, 3, 6, 5, 8], // row
[5, 6, 9, 1, 3, 4, 7, 8, 2], // row
[8, 2, 3, 6, 7, 8, 5, 4, 9], // row
[7, 4, 8, 5, 2, 9, 1, 6, 3], // row
[6, 5, 2, 7, 8, 1, 3, 9, 4], // row
[9, 8, 1, 3, 4, 5, 2, 7, 6], // row
[3, 7, 4, 9, 6, 2, 8, 1, 5], // row
];
// Function that go through every column and return result
// Go through every column
function validateColumns(matrix) {
let result;
for (let column = 0; column < matrix.length; column++) {
result = getColumn(matrix, column);
if (result) {
return result
}
}
return result;
}
validateColumns(badPuzzle);
// Getting all the values for every column
function getColumn(anArray, columnNumber) {
let column;
column = anArray.map(function(row) {
return row[columnNumber];
});
return checkForDuplicates(column);
}
// HELPER FUNCTION
// Check for duplicated items in array
function checkForDuplicates(array) {
// To save all the values that are not repited
let helperArray = [];
for (let i = 0; i < array.length; i++) { // To go through every element of the array [2, 3, 4, 5, 6, 7, 7, 8, 9]
// If the helperArray Yes includes this value
if (helperArray.includes(array[i])) {
return `Yes Values repited, and the value repited is: ${array[i]} TRUE` // True
}
// If helperArray does not include that value then save the value into helperArray
helperArray.push(array[i])
}
return false; // False means that the array have not repited elements
}
Result:
By Cristina Rojas.