Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.8 kB
28
Indexable
Never
/*

STEPS
1. Create a matrix

2. Pick a winning position and fill the matrix with the symbols of that winning position.

3. Find the symbols of the neighbors of each empty space on the matrix.
   Then choose a random symbol that does not contain these symbols and add it to this field.

4. By this way, other fields will be filled without creating a winning position.

*/

const SYMBOLS = ["X", "Y", "Z", "A", "B", "C"];
const winningList = [
    [
        {i: 1, j: 1, symbol: SYMBOLS[0]},
        {i: 1, j: 2, symbol: SYMBOLS[0]},
        {i: 1, j: 3, symbol: SYMBOLS[0]},
    ],
    [
        {i: 2, j: 2, symbol: SYMBOLS[0]},
        {i: 2, j: 3, symbol: SYMBOLS[0]},
        {i: 3, j: 2, symbol: SYMBOLS[0]},
        {i: 3, j: 3, symbol: SYMBOLS[0]},
    ]
];

// create matrix
row_size = 5;
col_size = 5;
let matrix = Array(row_size).fill('0').map(() => Array(col_size).fill('0'));

// select a winning position
const wonPosition = winningList[0];
console.log("Winning Position", wonPosition);

// fill matrix with winning position
wonPosition.forEach(value => {
    matrix[value['i']][value['j']] = value['symbol']
});

// show the filled matrix
console.log('After filling the winning position into the matrix');
matrix.forEach(row => console.log(row));

// find unfilled fields and fill without neighbors symbols
for(let i = 0; i < row_size; i++) {
    for(let j = 0; j < col_size; j++) {
        // if its filled skip
        if (matrix[i][j] !== '0') continue;

        // get neighbors symbols of matrix[i][j]
        const neighbors = findNeighborsCoordinates(matrix, i, j);
        let neighborSymbols = [];
        neighbors.forEach(neighborPosition => {
            let symbol = matrix[neighborPosition['i']][neighborPosition['j']];
            // if it's a filled field add to symbol list
            if (symbol !== '0') {
                neighborSymbols.push(symbol);
            }
        });

        // get random symbol without neighbors symbols and fill the i,j
        matrix[i][j] = getRandomSymbol(neighborSymbols);
    }
}

console.log('After filling the empty coordinates');
matrix.forEach(row => console.log(row));

function getRandomSymbol(exclude = []) {
    const symbols = SYMBOLS.filter(symbol => !exclude.includes(symbol));
    return symbols[Math.floor(Math.random() * symbols.length)]
}

function findNeighborsCoordinates(myArray, i, j) {
    const coords = [];
    const rowLimit = myArray.length - 1;
    const columnLimit = myArray[0].length - 1;

    for (let x = Math.max(0, i - 1); x <= Math.min(i + 1, rowLimit); x++) {
        for (let y = Math.max(0, j - 1); y <= Math.min(j + 1, columnLimit); y++) {
            if (x !== i || y !== j) {
                coords.push({i: x, j: y});
            }
        }
    }
    return coords;
}