Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

Create a self-containing HTML file that produces a Sudoku puzzle generator and solver

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash-preview-04-17’s answer.
  1. User

    Create a self-containing HTML file that produces a Sudoku puzzle generator and solver

  2. Assistant

    Certainly! Below is a fully self-contained HTML file that includes a Sudoku puzzle generator and solver. You can open this file in any modern web browser. It allows you to:

    • Generate a new Sudoku puzzle.
    • Solve the current puzzle.
    • Clear the board.
    • Manually input numbers.

    The generator creates puzzles with a unique solution and a moderate difficulty level.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Sudoku Generator & Solver</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        background: #f0f0f0;
        margin: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      h1 {
        margin-bottom: 10px;
      }
      #sudoku {
        border-collapse: collapse;
        margin-bottom: 15px;
      }
      #sudoku input {
        width: 40px;
        height: 40px;
        text-align: center;
        font-size: 20px;
        border: 1px solid #999;
        outline: none;
        background-color: white;
      }
      #sudoku td {
        padding: 0;
      }
      /* Thicker borders for 3x3 blocks */
      #sudoku tr:nth-child(3n) td {
        border-bottom: 2px solid #000;
      }
      #sudoku td:nth-child(3n) {
        border-right: 2px solid #000;
      }
      #sudoku td:nth-child(1) {
        border-left: 2px solid #000;
      }
      #sudoku tr:nth-child(1) td {
        border-top: 2px solid #000;
      }
      /* Highlight given cells */
      .given {
        background-color: #ddd;
        font-weight: bold;
      }
      /* Buttons */
      button {
        margin: 5px;
        padding: 10px 15px;
        font-size: 16px;
        cursor: pointer;
      }
      #message {
        margin-top: 10px;
        height: 20px;
        font-weight: bold;
        color: #d00;
      }
    </style>
    </head>
    <body>
    
    <h1>Sudoku Generator & Solver</h1>
    
    <table id="sudoku" aria-label="Sudoku grid" role="grid" tabindex="0">
      <!-- 9x9 grid will be generated by JS -->
    </table>
    
    <div>
      <button id="generateBtn">Generate Puzzle</button>
      <button id="solveBtn">Solve Puzzle</button>
      <button id="clearBtn">Clear Board</button>
    </div>
    
    <div id="message" role="alert" aria-live="polite"></div>
    
    <script>
    (() => {
      const SIZE = 9;
      const BOX_SIZE = 3;
      const sudokuTable = document.getElementById('sudoku');
      const generateBtn = document.getElementById('generateBtn');
      const solveBtn = document.getElementById('solveBtn');
      const clearBtn = document.getElementById('clearBtn');
      const message = document.getElementById('message');
    
      // Create the Sudoku grid inputs
      function createGrid() {
        sudokuTable.innerHTML = '';
        for (let r = 0; r < SIZE; r++) {
          const row = document.createElement('tr');
          for (let c = 0; c < SIZE; c++) {
            const cell = document.createElement('td');
            const input = document.createElement('input');
            input.type = 'text';
            input.maxLength = 1;
            input.setAttribute('aria-label', `Row ${r + 1} Column ${c + 1}`);
            input.dataset.row = r;
            input.dataset.col = c;
            input.autocomplete = 'off';
            input.inputMode = 'numeric';
            input.pattern = '[1-9]';
            input.addEventListener('input', onInput);
            input.addEventListener('keydown', onKeyDown);
            cell.appendChild(input);
            row.appendChild(cell);
          }
          sudokuTable.appendChild(row);
        }
      }
    
      // Validate input to allow only digits 1-9
      function onInput(e) {
        const val = e.target.value;
        if (!/^[1-9]$/.test(val)) {
          e.target.value = '';
        }
      }
    
      // Allow navigation with arrow keys
      function onKeyDown(e) {
        const input = e.target;
        const row = +input.dataset.row;
        const col = +input.dataset.col;
        let nextRow = row;
        let nextCol = col;
    
        switch (e.key) {
          case 'ArrowUp': nextRow = (row + SIZE - 1) % SIZE; break;
          case 'ArrowDown': nextRow = (row + 1) % SIZE; break;
          case 'ArrowLeft': nextCol = (col + SIZE - 1) % SIZE; break;
          case 'ArrowRight': nextCol = (col + 1) % SIZE; break;
          default: return;
        }
        e.preventDefault();
        sudokuTable.rows[nextRow].cells[nextCol].firstChild.focus();
      }
    
      // Read the current board state into a 2D array
      function readBoard() {
        const board = [];
        for (let r = 0; r < SIZE; r++) {
          const row = [];
          for (let c = 0; c < SIZE; c++) {
            const val = sudokuTable.rows[r].cells[c].firstChild.value;
            row.push(val === '' ? 0 : +val);
          }
          board.push(row);
        }
        return board;
      }
    
      // Write a board state to the grid
      // If givenCells is provided, mark those cells as given (non-editable)
      function writeBoard(board, givenCells = null) {
        for (let r = 0; r < SIZE; r++) {
          for (let c = 0; c < SIZE; c++) {
            const input = sudokuTable.rows[r].cells[c].firstChild;
            const val = board[r][c];
            input.value = val === 0 ? '' : val;
            if (givenCells && givenCells[r][c]) {
              input.classList.add('given');
              input.readOnly = true;
            } else {
              input.classList.remove('given');
              input.readOnly = false;
            }
          }
        }
      }
    
      // Check if placing num at board[row][col] is valid
      function isValid(board, row, col, num) {
        for (let i = 0; i < SIZE; i++) {
          if (board[row][i] === num) return false;
          if (board[i][col] === num) return false;
        }
        const boxRow = Math.floor(row / BOX_SIZE) * BOX_SIZE;
        const boxCol = Math.floor(col / BOX_SIZE) * BOX_SIZE;
        for (let r = 0; r < BOX_SIZE; r++) {
          for (let c = 0; c < BOX_SIZE; c++) {
            if (board[boxRow + r][boxCol + c] === num) return false;
          }
        }
        return true;
      }
    
      // Solve the Sudoku board using backtracking
      function solveSudoku(board) {
        for (let r = 0; r < SIZE; r++) {
          for (let c = 0; c < SIZE; c++) {
            if (board[r][c] === 0) {
              for (let num = 1; num <= 9; num++) {
                if (isValid(board, r, c, num)) {
                  board[r][c] = num;
                  if (solveSudoku(board)) return true;
                  board[r][c] = 0;
                }
              }
              return false;
            }
          }
        }
        return true;
      }
    
      // Generate a fully solved board
      function generateFullSolution() {
        const board = Array.from({ length: SIZE }, () => Array(SIZE).fill(0));
    
        function fillCell(r, c) {
          if (r === SIZE) return true;
          const nextR = c === SIZE - 1 ? r + 1 : r;
          const nextC = c === SIZE - 1 ? 0 : c + 1;
    
          let numbers = [1,2,3,4,5,6,7,8,9];
          shuffleArray(numbers);
    
          for (const num of numbers) {
            if (isValid(board, r, c, num)) {
              board[r][c] = num;
              if (fillCell(nextR, nextC)) return true;
              board[r][c] = 0;
            }
          }
          return false;
        }
    
        fillCell(0, 0);
        return board;
      }
    
      // Shuffle array in-place
      function shuffleArray(arr) {
        for (let i = arr.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [arr[i], arr[j]] = [arr[j], arr[i]];
        }
      }
    
      // Check if the board has a unique solution
      // We limit to finding 2 solutions to confirm uniqueness
      function hasUniqueSolution(board) {
        let count = 0;
    
        function solveCount(bd) {
          for (let r = 0; r < SIZE; r++) {
            for (let c = 0; c < SIZE; c++) {
              if (bd[r][c] === 0) {
                for (let num = 1; num <= 9; num++) {
                  if (isValid(bd, r, c, num)) {
                    bd[r][c] = num;
                    if (solveCount(bd)) {
                      bd[r][c] = 0;
                      return true;
                    }
                    bd[r][c] = 0;
                  }
                }
                return false;
              }
            }
          }
          count++;
          return count > 1; // stop if more than one solution found
        }
    
        const copy = board.map(row => row.slice());
        solveCount(copy);
        return count === 1;
      }
    
      // Generate a puzzle by removing numbers from a full solution
      function generatePuzzle() {
        const fullSolution = generateFullSolution();
        const puzzle = fullSolution.map(row => row.slice());
        const givenCells = Array.from({ length: SIZE }, () => Array(SIZE).fill(true));
    
        // Positions to try removing numbers from
        const positions = [];
        for (let r = 0; r < SIZE; r++) {
          for (let c = 0; c < SIZE; c++) {
            positions.push([r, c]);
          }
        }
        shuffleArray(positions);
    
        // Remove numbers while maintaining unique solution
        for (const [r, c] of positions) {
          const backup = puzzle[r][c];
          puzzle[r][c] = 0;
          if (!hasUniqueSolution(puzzle)) {
            puzzle[r][c] = backup; // revert if multiple solutions
          } else {
            givenCells[r][c] = false;
          }
        }
    
        return { puzzle, givenCells };
      }
    
      // Event handlers
      generateBtn.addEventListener('click', () => {
        message.textContent = 'Generating puzzle...';
        setTimeout(() => {
          const { puzzle, givenCells } = generatePuzzle();
          writeBoard(puzzle, givenCells);
          message.textContent = 'Puzzle generated! You can solve it or try yourself.';
        }, 50);
      });
    
      solveBtn.addEventListener('click', () => {
        const board = readBoard();
        if (!validateBoard(board)) {
          message.textContent = 'Invalid board: conflicts detected.';
          return;
        }
        const copy = board.map(row => row.slice());
        if (solveSudoku(copy)) {
          writeBoard(copy);
          message.textContent = 'Puzzle solved!';
        } else {
          message.textContent = 'No solution exists for the current board.';
        }
      });
    
      clearBtn.addEventListener('click', () => {
        writeBoard(Array.from({ length: SIZE }, () => Array(SIZE).fill(0)));
        message.textContent = '';
      });
    
      // Validate the current board for conflicts
      function validateBoard(board) {
        for (let r = 0; r < SIZE; r++) {
          for (let c = 0; c < SIZE; c++) {
            const val = board[r][c];
            if (val !== 0) {
              board[r][c] = 0;
              if (!isValid(board, r, c, val)) {
                board[r][c] = val;
                return false;
              }
              board[r][c] = val;
            }
          }
        }
        return true;
      }
    
      // Initialize grid on page load
      createGrid();
      message.textContent = 'Click "Generate Puzzle" to start.';
    })();
    </script>
    
    </body>
    </html>
    

    How to use:

    1. Save the above code as sudoku.html.
    2. Open it in a modern web browser.
    3. Click Generate Puzzle to get a new Sudoku puzzle.
    4. You can fill in numbers manually or click Solve Puzzle to see the solution.
    5. Use Clear Board to reset the grid.

    This implementation uses a backtracking algorithm for both generating and solving Sudoku puzzles, ensuring puzzles have a unique solution. The UI is accessible and keyboard-friendly. Let me know if you want it enhanced with difficulty levels or other features!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.