【问题标题】:Java 2D array assigning randomlyJava 2D 数组随机分配
【发布时间】:2014-12-29 00:11:01
【问题描述】:

我有一个数组 a[5][5] 和几个值。我想根据我创建的随机百分比随机分配值。例如,一个值为 6,数组中 25% 的元素的值应为 6。到目前为止,我已经创建了随机百分比,并且能够为数组中的不同元素随机分配值。我的问题是:超过 25% 的元素有 6。我的问题是:如何确保在分配 6 的元素时,数组 a[5][5] 中恰好 25% 的元素具有该值?我是编程新手,尝试了几个循环和 ifs,但对我来说没有任何效果。请把我推向正确的方向。

【问题讨论】:

  • 请发布您的代码,以便我们帮助改进它
  • 您是如何创建随机百分比以及如何 您是否能够为数组中的不同元素?帮助我们帮助您。
  • 对于一个 5x5 数组有 25 个元素,您将永远无法准确地获得其中的 25%,因为 25% 是 1/4,而 25 个元素是不能被 4 整除。

标签: java arrays random


【解决方案1】:

我会这样做

import java.util.Random;
import java.util.Scanner;

 class Random2darray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // Create array; you specified 5x5 but you probably shouldn't hard code like this
        int[][] numbers = new int[5][5];
        //Create a scanner to get user input
        Scanner scanner = new Scanner(System.in);
        //I am not doing anything to make sure they give a decimal so the program won't work 
        //right if you are not giving a decimal
        System.out.println("How much do you want to fill? Enter a decimal.");
        //Get a double
        double populatePercentage = scanner.nextDouble();
        System.out.println("What number do you want to fill with?");
        //Get an int
        int fillNumber = scanner.nextInt();
        //Don't hardcode like this
        int fillTimes = numberOfTimesToFill(25, populatePercentage);
        //This is declared outside of the loops because otherwise it will be 
        //reset each time the loop runs
        int count = 0;
        //Create a random number generator; default seed is current time which is good enough for this
        Random rand = new Random();
        //Fill the array with numbers
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                //Check if you have filled with given number enough times
                if(count < fillTimes){
                    numbers[i][j] = fillNumber;
                    //Increment count by 1; this is how you are keeping track
                    count++;
                }else{
                    //Otherwise pick a random number generator
                    //This will pick a random int between 0 - 50 inclusive
                    int randomNumber = rand.nextInt(51);
                    //This will make sure that you are not generating random numbers that are the same
                    //as the number you are filling with; This says if it is the same generate a new number
                    while(randomNumber == fillNumber){
                        randomNumber = rand.nextInt(51);
                    }
                    //Once we know its random fill the spot in the array 
                    numbers[i][j] = randomNumber;
                }
            }
        }
        //Print the array out
        printArray(numbers);
    }

    private static void printArray(int[][] numbers) {
        //Just loop through and print every number
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                //Print with formatting: this says print a digit (%d) followed by a 
                //tab(\t) and then specifies what number I want to print
                System.out.printf("%d\t", numbers[i][j]);
            }
            //Print a new line after each row
            System.out.printf("\n");
        }
    }

    private static int numberOfTimesToFill(int elements, double populatePercentage) {
        System.out.println((int)(populatePercentage * elements));
        //Cast to an int to truncate the decimal part of the number because you can't have 
        //a fraction of an element
        return (int)(populatePercentage * elements);
    }

}

我已经对代码进行了注释,以解释一切的作用。然而,它并不能防止用户输入错误,并且会对数组的大小进行硬编码,因此您应该始终尽量避免硬编码。在这个例子中,为了更清楚,我做了(并标记了位置)。同样正如上面 cmets 中提到的,对于您想要 25 的 25% 的情况是不可能的。这是因为 .25 * 25 = 6.25 并且您不能拥有 .25 的元素。

【讨论】:

    【解决方案2】:

    25 的 25% 大约是 6。它不准确。这是一个可能的解决方案。

    import java.util.Random;
    import java.util.Scanner;
    
    public class Matrix25 {
    public static void main(String[] args) {
      int[][] Matrix = new int[5][5];
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter the number you want to fill the array to 25%: ");
      int number = scanner.nextInt();
      int percentage=25;
      generateMatrix(Matrix,number,percentage);
      printMatrix(Matrix);        
    }
    
    public static void generateMatrix(int Matrix[][],int num, int perc) {        
        int n;
        int max=Matrix.length*Matrix[0].length;
        int[] numbers = new int[max];
        Random rnd = new Random();
        int m = (int)(max * (perc/100.0));
        int x=num>m?m-1:m;
        for(int i=0;i<max;i++)
                numbers[i]=(i<x)?num:i+1;
    
        for(int i=0;i<Matrix.length;i++)
            for(int j=0;j<Matrix[i].length;j++) {
                n=rnd.nextInt(max);   
                Matrix[i][j]=numbers[n];
                numbers[n]=numbers[max-1];
                max--;
            }
    }
    
    public static void printMatrix(int Matrix[][]) {
         for(int i=0;i<Matrix.length;i++) {
            for(int j=0;j<Matrix[i].length;j++) 
                    System.out.printf("%3d\t",Matrix[i][j]);
            System.out.print("\n");
         }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多