import java.util.ArrayList; import javax.swing.*; import java.awt.event.*; import java.lang.Math.*; import java.text.DecimalFormat; public class Resolver implements ActionListener { private JTextField[][] grid; private int GRID_SIZE; public Resolver(JTextField[][] grid, int GRID_SIZE) { this.grid = grid; this.GRID_SIZE = GRID_SIZE; } @Override public void actionPerformed(ActionEvent e) { resolution(); } private void resolution() { long depart = System.nanoTime(); ArrayList case_vide = new ArrayList(); do { for (int row = 0; row < this.GRID_SIZE; row++) { for (int col = 0; col < this.GRID_SIZE; col++) { if (grid[row][col].getText().isEmpty()) { if (!case_vide.contains(grid[row][col])) { case_vide.add(grid[row][col]); } //Création de la liste de chiffre acceptable ArrayList chiffre_possible = new ArrayList(); for (int i = 1; i <= GRID_SIZE; i++) { chiffre_possible.add(""+i); } //recherche des chiffres present sur la ligne for (int col2 = 0; col2 < this.GRID_SIZE; col2++) { if (!grid[row][col2].getText().isEmpty()) { chiffre_possible.remove(""+grid[row][col2].getText()); } } //recherche des chiffres sur la colonne for (int row2 = 0; row2 < this.GRID_SIZE; row2++) { if (!grid[row2][col].getText().isEmpty()) { chiffre_possible.remove(""+grid[row2][col].getText()); } } //recherche des chiffres dans la région int rowregion = row/3*3; int colregion = col/3*3; for (int row2 = rowregion; row2 < rowregion + 3; row2++) { for (int col2 = colregion; col2 < colregion + 3; col2++) { if (!grid[row2][col2].getText().isEmpty()) { chiffre_possible.remove(""+grid[row2][col2].getText()); } } } if (chiffre_possible.size() == 1) { grid[row][col].setText(chiffre_possible.getFirst()); case_vide.remove(grid[row][col]); } } } } }while (!case_vide.isEmpty()); double durée = (((System.nanoTime()) - depart )* Math.pow(10,-9)); DecimalFormat df = new DecimalFormat("0.00"); JOptionPane.showMessageDialog(null, "Grille terminé en " + df.format(durée) + " secondes", "Résolution automatique", JOptionPane.INFORMATION_MESSAGE); } }