【问题标题】:Populate 2D array with range of random integers, but keep a fixed number of X elements always the same使用随机整数范围填充二维数组,但保持固定数量的 X 元素始终相同
【发布时间】:2021-12-09 11:33:51
【问题描述】:

我生成从 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

有什么方法可以实现吗?

【问题讨论】:

  • ThreadLocalRandom.current().ints(0, rows * columns).distinct().limit(5).forEach(i -&gt; array[i / rows][i % rows] = 0);

标签: java arrays multidimensional-array


【解决方案1】:

您可以先评估矩阵为零的随机位置:

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 

【讨论】:

    【解决方案2】:

    试试这个。

    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]
    

    【讨论】:

      【解决方案3】:

      好吧,为了让它更笼统,我有点过火了。

      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]
      
      
      • 首先检查不变量以确保计数为
      • 创建一个由 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;
              
      }
      

      【讨论】:

        【解决方案4】:
        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] + " ");
              }
            }
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2014-01-11
        • 2014-05-10
        • 1970-01-01
        • 1970-01-01
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多