简体   繁体   中英

Java: How to randomize an array list without duplicates

import java.util.Random;

public class Sudoku {
  int[][] SquareNumbers = { 
      { 4, 3, 5, 8, 7, 6, 1, 2, 9 }, { 8, 7, 6, 2, 1, 9, 3, 4, 5 }, { 2, 1, 9, 4, 3, 5, 7, 8, 6 },
      { 5, 2, 3, 6, 4, 7, 8, 9, 1 }, { 9, 8, 1, 5, 2, 3, 4, 6, 7 }, { 6, 4, 7, 9, 8, 1, 2, 5, 3 },
      { 7, 5, 4, 1, 6, 8, 9, 3, 2 }, { 3, 9, 2, 7, 5, 4, 6, 1, 8 }, { 1, 6, 8, 3, 9, 2, 5, 7, 4 } };

  Random Digits = new Random(); // random numbers to exchange Rows
  Random HiddenNumbers = new Random();
  int Grid[][] = new int[9][9];

  public int[][] Generator() {
    for (int x = 0; x < Digits.nextInt(); x++) {
      for (int da = 0; da < 3; da++) {

      }
    }

    return SquareNumbers;
  }

  int[][] Hide() {
    for (int i = 0; i < 9; i++)
      for (int j = 0; j < 9; j++)
        Grid[i][j] = SquareNumbers[i][j];

    int Row, Columns, Concealer;

    Concealer = 55 + Digits.nextInt(1);

    for (int i = 0; i < Concealer; i++) {
      Row = HiddenNumbers.nextInt(9);
      Columns = HiddenNumbers.nextInt(9);
      Grid[Row][Columns] = -1;
    }
    return Grid;
  }

  public int[][] getSquareNumbers() {
    return SquareNumbers;
  }

  public void setSquareNumbers(int[][] SquareNumbers) {
    this.SquareNumbers = SquareNumbers;
  }

  private static Sudoku instance = null;

  protected Sudoku() {
    // Exists only to defeat instantiation.
  }

  public static Sudoku getInstance() {
    if (instance == null) {
      instance = new Sudoku();
    }
    return instance;
  }
}

Instead of a double array list, is there a way to randomize it so it works like a Sudoku game? As in it has no duplicates within columns or rows and every three by three smaller grid uses a number once?

One method for generating random sudoku puzzles would be as follows:

  1. Generate a random puzzle satisfying the constraints of a sudoku puzzle
  2. Randomly swap digits (eg replace 2s with 3s, 7s with 1s, etc)
  3. Randomly swap columns or rows within their set of 3 (eg swap the first and third column, or the 5th and 6th)
  4. Randomly switch sets of 3 columns or rows with another set of columns.

While these will look like different puzzles, they will in fact, all be isotropic latin squares (ie all equivalent since they can be reduced to the same puzzle by reordering rows/columns).

If you want a more random solution, this may have already been answered here: https://stackoverflow.com/a/6964044/2471910

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM