Create a Matrix with Random Numbers with no Repeat Vertically or Horizontally

A code for reference picked from here and converted to javascript

let size = 9;
let board = [];

for (let x = 0; x < size; x++) {
    board[x] = createOrderedArray();
    do {
        shuffle(board[x]);
    } while (!compare2DArray(board[x], board, 0, x));
}

console.log(board);

function shuffle(arr) {
    let count = arr.length;

    for (let x = 0; x < count; x++) {
        swap(arr, x, Math.floor(Math.random() * count));
    }
}

function createOrderedArray() {
    let temp = [];
    let startVal = 1;
    for (let i = 0; i < size; i++) {
        temp[i] = startVal + i;
    }
    return temp;
}

//Return TRUE if arrays are COMPLETELY different
function compareArray(arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;

    for (let x = 0; x < arr1.length; x++) {
        if (arr1[x] == arr2[x])
            return false;
    }
    return true;
}

//Return TRUE if array vs arrays is COMPLETELY different
function compare2DArray(arr1, arr2, begin, end) {
    for (let x = begin; x < end; x++)
        if (!compareArray(arr1, arr2[x]))
            return false;

    return true;
}

function swap(arr, a, b) {
    let temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}

Leave A Comment

Your email address will not be published.