JSFiddle - React, Tailwind, and code Playground

by magikMaker

JavaScript

function initializeGrid() {
  let grid;
  let initialSum;
  do {
    // Generate a random 3x3 grid
    grid = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => Math.floor(Math.random() * 6)));

    // Calculate the initial sum
    initialSum = grid.flat().reduce((sum, cell) => sum + cell, 0);
  } while (initialSum % 6 !== 0);

  return grid;
}

function clickCell(grid, row, col) {
  // Decrease the clicked cell's value by 1
  grid[row][col] = (grid[row][col] - 1 + 6) % 6;

  // Decrease the values in the same row and column
  for (let i = 0; i < 3; i++) {
    grid[row][i] = (grid[row][i] - 1 + 6) % 6;
    grid[i][col] = (grid[i][col] - 1 + 6) % 6;
  }
}

function isSolved(grid) {
  // Check if all cells are zero
  return grid.every(row => row.every(cell => cell === 0));
}

function findHighestCell(grid) {
  let maxCell = { row: 0, col: 0, value: -1 };

  for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 3; col++) {
      if (grid[row][col] > maxCell.value) {
        maxCell.row = row;
        maxCell.col = col;
        maxCell.value = grid[row][col];
      }
    }
  }

  return maxCell;
}

function solvePuzzle(grid) {
  let moves = 0;

  while (!isSolved(grid)) {
    const highestCell = findHighestCell(grid);
    clickCell(grid, highestCell.row, highestCell.col);
    moves++;
  }

  return moves;
}

function testSolver() {
  const grid = initializeGrid();

  console.log("Initial grid:");
  console.log(grid);

  const initialSum = grid.flat().reduce((sum, cell) => sum + cell, 0);
  console.log("The initial sum is divisible by 6:", initialSum % 6 === 0);

  const moves = solvePuzzle(grid);
  console.log("Grid after solving:");
  console.log(grid);
  console.log("Puzzle solved in", moves, "moves.");
}

// Run the solver
testSolver();