Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

Archivo del blog

sábado, 15 de abril de 2023

Juegos III.1. Generador de Sudokus aleatorios.

En esta versión se añade formato al tablero de juego mediante caracteres ASCII.


Código Java (SudokuGenerator.java):

package sudokugenerator;

import java.util.Random;

public class SudokuGenerator {

    private static final int BOARD_SIZE = 9;
    private static final int SUB_GRID_SIZE = 3;
    private static final int NUM_REMOVES = 20;

    public static void main(String[] args) {
        int[][] board = generateSudoku();
        printBoard(board);
    }

    public static int[][] generateSudoku() {
        int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
        populateBoard(board);
        removeCells(board);
        return board;
    }

    private static void populateBoard(int[][] board) {
        if (!solve(board, 0, 0)) {
            throw new IllegalStateException("No se pudo generar un sudoku válido.");
        }
    }

    private static boolean solve(int[][] board, int row, int col) {
        if (col == BOARD_SIZE) {
            col = 0;
            row++;
            if (row == BOARD_SIZE) {
                return true;
            }
        }

        if (board[row][col] != 0) {
            return solve(board, row, col + 1);
        }

        Random rand = new Random();
        for (int num : rand.ints(1, BOARD_SIZE + 1).distinct().limit(BOARD_SIZE).toArray()) {
            if (isValid(board, row, col, num)) {
                board[row][col] = num;
                if (solve(board, row, col + 1)) {
                    return true;
                }
            }
        }

        board[row][col] = 0;
        return false;
    }

    private static boolean isValid(int[][] board, int row, int col, int num) {
        for (int i = 0; i < BOARD_SIZE; i++) {
            if (board[row][i] == num || board[i][col] == num) {
                return false;
            }
        }

        int r = row - row % SUB_GRID_SIZE;
        int c = col - col % SUB_GRID_SIZE;
        for (int i = r; i < r + SUB_GRID_SIZE; i++) {
            for (int j = c; j < c + SUB_GRID_SIZE; j++) {
                if (board[i][j] == num) {
                    return false;
                }
            }
        }

        return true;
    }

    private static void removeCells(int[][] board) {
        Random rand = new Random();
        for (int i = 0; i < NUM_REMOVES; i++) {
            int row = rand.nextInt(BOARD_SIZE);
            int col = rand.nextInt(BOARD_SIZE);
            board[row][col] = 0;
        }
    }

    private static void printBoard(int[][] board) {
        System.out.println("+-------+-------+-------+");
        for (int i = 0; i < BOARD_SIZE; i++) {
            System.out.print("| ");
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (board[i][j] == 0) {
                    System.out.print("▓ ");
                } else {
                    System.out.print(board[i][j] + " ");
                }
                if (j % 3 == 2) {
                    System.out.print("| ");
                }
            }
            System.out.println();
            if (i % 3 == 2) {
                System.out.println("+-------+-------+-------+");
            }
        }
    }
}


Resultado:

run:
+-------+-------+-------+
| ▓ 6 3 | 9 7 8 | 1 2 5 |
| 9 7 8 | 5 ▓ ▓ | 6 3 4 |
| 5 2 1 | 4 6 3 | 8 ▓ 9 |
+-------+-------+-------+
| 3 5 9 | 7 2 ▓ | ▓ 1 ▓ |
| 2 1 ▓ | 8 ▓ 4 | 3 9 ▓ |
| ▓ ▓ 4 | 1 3 9 | ▓ 5 7 |
+-------+-------+-------+
| 8 ▓ 2 | 3 4 7 | 5 6 1 |
| 1 4 6 | 2 9 ▓ | 7 ▓ 3 |
| 7 ▓ 5 | ▓ 8 1 | ▓ 4 2 |
+-------+-------+-------+
BUILD SUCCESSFUL (total time: 0 seconds)

Con la tecnología de Blogger.