簡體   English   中英

Java:如何隨機化一個沒有重復的數組列表

[英]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;
  }
}

有沒有辦法隨機化它而不是雙數組列表,使其像數獨游戲一樣工作? 因為它在列或行內沒有重復項,並且每三乘三較小的網格使用一個數字一次?

生成隨機數獨謎題的一種方法如下:

  1. 生成一個滿足數獨游戲約束的隨機謎題
  2. 隨機交換數字(例如用 3s 替換 2s,用 1s 替換 7s 等)
  3. 隨機交換 3 組中的列或行(例如交換第一列和第三列,或第五列和第六列)
  4. 用另一組列隨機切換一組 3 列或行。

雖然這些看起來像是不同的謎題,但實際上它們都是各向同性的拉丁方格(即所有等價的,因為它們可以通過重新排序行/列來減少到相同的謎題)。

如果你想要一個更隨機的解決方案,這可能已經在這里回答: https : //stackoverflow.com/a/6964044/2471910

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM