簡體   English   中英

使用隨機整數范圍填充二維數組,但保持固定數量的 X 元素始終相同

[英]Populate 2D array with range of random integers, but keep a fixed number of X elements always the same

我生成從 0 到 90 的隨機唯一整數:

   public static int randomNumber() {
      int min = 0;
      int max = 90;
      return min + (int) (Math.random() * ((max - min) + 1));
   }

...並使用這些生成的整數來填充多維 3*5 數組:

   int rows = 3;
   int columns = 5;
   int[][] array = new int[rows][columns];

   public static void populateArray(int[][] array, int rows, int columns) {
      for (int indexRow = 0; indexRow < rows; indexRow++) {
         for (int indexColumn = 0; indexColumn < columns; indexColumn++) {
            array[indexRow][indexColumn] = randomNumber();
         }
      }
   }

......這會產生這樣的事情:

56  64  22  38  78  
73  18  69  39  70  
49  24  3   49  25

但是,我希望數組中固定數量的 5 個隨機元素(不多於 5 個隨機元素)始終為 0,如下所示:

0   64  22  38  0   
73  18  0   39  70  
0   24  3   0   25

有什么方法可以實現嗎?

您可以首先評估矩陣為零的隨機位置:

static int[] zeroPositions(int totalPositions, int zeroPositions){
    int[] result = new int[zeroPositions];
    Random random = new Random();
    for(int i = 0; i < zeroPositions; i++){
        int currentPosition = random.nextInt(totalPositions);
        while (contains(result, currentPosition)){
            currentPosition = (currentPosition + 1) % totalPositions;
        }
        result[i] = currentPosition;
    }
    return result;
}

在上面的代碼中,我省略了一些檢查,例如零位置不大於總位置(以節省空間)。

您在這里和稍后需要的另一個方法是檢查數組是否包含值的方法:

public static boolean contains(int[] source, int value){
    for(int i = 0; i < source.length; i++){
        if(source[i] == value){
            return true;
        }
    }
    return false;
}

現在您應該修改您的randomNumber方法,以便將最小值設為1因為零不會填充單元格。

public static int randomNumber() {
    int min = 1; // skip 0
    int max = 90;
    return min + (int) (Math.random() * ((max - min) + 1));
} 

並修改populateArray方法以測試當前位置是否必須保持為零:

public static void populateArray(int[][] array, int rows, int columns, int[] zeroPositions) {

    for (int indexRow = 0; indexRow < rows; indexRow++) {
        for (int indexColumn = 0; indexColumn < columns; indexColumn++) {
            if(!contains(zeroPositions, indexRow * columns + indexColumn)){
                array[indexRow][indexColumn] = randomNumber();
            }
        }
    }
}

現在讓我們運行一切:

public static void main(String[] args) {
    int rows = 3;
    int cols = 5;
    int[][] matrix = new int[rows][cols];
    populateArray(matrix, rows, cols, zeroPositions(rows * cols, 5));
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println("");
    }
}

最后是一些輸出:

8 58 0 0 28 
39 79 54 0 0 
28 0 30 51 56 

65 81 27 0 0 
17 21 74 0 0 
0 16 47 69 80 

44 0 18 57 30 
0 0 37 76 61 
0 0 38 77 20 

好吧,我有點過火,使它更一般。

int[][] result = create(3,5,5,90);
for (int[] r : result) {
    System.out.println(Arrays.toString(r));
}

印刷

[0, 48, 0, 0, 41]
[0, 32, 0, 0, 0]
[0, 0, 0, 81, 25]

  • 首先檢查不變量以確保計數 <= row * cols
  • 創建一個 0 的數組來填充結果數組
  • 然后在結果數組中生成一個索引數組
  • 然后通過隨機選擇和索引以及要存儲的新數字來填充結果數組。
  • 調整索引數組以不重復之前的索引。
  • 返回結果。
// rows, cols - the array dimensions
// count - is the number of randoms numbers and the 
// max - is the max size of that number.    
public static int[][] create(int rows, int cols, int count, int max) {
    int size = rows * cols;
    if (count > size) {
        throw new IllegalArgumentException(
                "Size and count don't match");
    }
    Random r = new Random();
    // an array of zeroes
    int[][] result = new int[rows][cols];
    // an array of indices into result
    int[] indices = new int[size];
    Arrays.setAll(indices, i->i++);
    // now loop thru filling in result array without
    // repeating any index.
    for (int i = 0; i < count; i++) {
        int pos = r.nextInt(size);
        result[indices[pos]/cols][indices[pos]%cols] = r.nextInt(max)+1;
        indices[pos] = indices[--size];
    }
    return result;
        
}

嘗試這個。

public static void populateArray(int[][] array, int fixedNumber, int fixedNumberCount) {
    int rows = array.length, cols = array[0].length, size = rows * cols;
    List<Integer> list = new ArrayList<>();
    for (int i = 0; i < fixedNumberCount; ++i)
        list.add(fixedNumber);
    for (int i = fixedNumberCount; i < size;) {
        int r = randomNumber();
        if (r == fixedNumber) continue;
        list.add(r);
        ++i;
    }
    Collections.shuffle(list);
    for (int r = 0, i = 0; r < rows; ++r)
        for (int c = 0; c < cols; ++c, ++i)
            array[r][c] = list.get(i);
}

public static void main(String[] args) {
    int[][] array = new int[5][5];
    populateArray(array, 0, 5);
    for (int[] row : array)
        System.out.println(Arrays.toString(row));
}

輸出:

[9, 71, 57, 86, 70]
[0, 0, 17, 70, 22]
[21, 0, 72, 7, 83]
[18, 37, 45, 8, 10]
[42, 8, 0, 85, 0]
import java.security.SecureRandom;
public class RandomNumber{
static int[] createUniqueRandomNumber(int from,int to)
{
 int n=to-from+1;
 int a[] =new int[n];
 for(int i=0;i<n;i++)
 {
  a[i]=i;
 }
 int[] result =new int[n];
  int x=n;
 SecureRandom rd=new SecureRandom();
  for(int i=0;i<n;i++)
  {
   int k=rd.nextInt(x);
    a[k] =a[x-1];
    x--
  }
  return result;
  }
 }
 public static void main(Strin[] args)
  {
   int[] result =createUniqueRandomNumber(4,15);
    for(int i=0;i<resuly.length;i++)
     {
       System.out.println(result[i] + " ");
      }
    }

暫無
暫無

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

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