SAE21_2023/SudokuGenerator.java

52 lines
1.9 KiB
Java
Raw Normal View History

2024-04-03 11:25:04 +02:00
import javax.swing.*;
import java.io.*;
2024-04-02 16:20:29 +02:00
public class SudokuGenerator {
2024-04-03 10:46:17 +02:00
public static int[][] generateGrid() {
2024-04-03 11:25:04 +02:00
// grille par défaut
2024-04-03 10:46:17 +02:00
int[][] grid = {
{0, 0, 0, 9, 0, 5, 0, 0, 4},
{5, 0, 3, 0, 0, 4, 0, 8, 7},
{0, 0, 0, 7, 0, 0, 6, 0, 3},
{9, 0, 0, 0, 3, 4, 0, 8, 0},
{0, 4, 0, 0, 1, 0, 0, 7, 0},
{0, 2, 0, 5, 7, 0, 0, 0, 6},
{4, 0, 9, 0, 0, 2, 0, 0, 0},
{6, 0, 7, 9, 0, 3, 0, 2, 1},
{2, 0, 0, 6, 5, 0, 0, 0, 0}
};
return grid;
}
2024-04-03 11:25:04 +02:00
public static int[][] readGridFromFile() {
int[][] grid = new int[9][9];
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
for (int i = 0; i < 9; i++) {
String line = reader.readLine();
// Vérifier la longueur de la ligne lue
if (line.length() != 9) {
JOptionPane.showMessageDialog(null, "Invalid file format. Please select a file with correct Sudoku grid format.");
return generateGrid(); // Charger la grille par défaut en cas d'erreur
}
for (int j = 0; j < 9; j++) {
char ch = line.charAt(j);
if (ch >= '1' && ch <= '9') {
grid[i][j] = Character.getNumericValue(ch);
} else {
grid[i][j] = 0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return grid;
}
2024-04-03 10:46:17 +02:00
}