# Sudoku validation “no duplicate elements in rows” Js

Hi, the challenge is – Sudoku validation and we need to make sure that Each row in the puzzle is exactly 1 through 9. No duplicates.

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
[1, 3, 5, 4, 8, 6, 9, 2, 7], // row
[2, 9, 6, 8, 5, 7, 4, 3, 1], // row
[4, 1, 7, 2, 4, 3, 6, 5, 8], // row DUPLICATED NUMBER HERE (4)!
[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
];

// Function that evaluate if the matrix have a duplicated numbers in the rows
function validateRows(puzzle) {
// to save the final result
let result;

// Each row in the puzzle is exactly 1 through 9. No duplicates.
// for to go through every row in the matrix
for (let i = 0; i < puzzle.length; i++) {
const sortedRow = puzzle[i].slice().sort(); // .slice() is creating a new instance array of each row (puzzle[i]) in that way the original array is not affected

// Calling and getting the return of checkForDuplicates function of each row
result = checkForDuplicates(sortedRow);

// True means that the sortedRow have repited elements
if (result) {
return result; // Return true (text)
}
}

// Return False means that the array have not repited elements
return result;
}

// Function that help us to know if an array have a duplicated elements
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
}

// Calling and getting the return of validateRows function