简体   繁体   English

Java 2D数组随机分配

[英]Java 2D array assigning randomly

I have an array a[5][5] and several values. 我有一个数组a [5] [5]和几个值。 I want to randomly assign values based on random percentages I create. 我想根据我创建的随机百分比随机分配值。 For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. 例如,一个值是6,数组中25%的元素应具有值6。到目前为止,我已经做到了:我创建了随机百分比,并且能够为数组中的不同元素随机分配值。 My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? 我的问题是:超过25%的元素具有6。我的问题是:如何确保在给元素分配6时,数组a [5] [5]中恰好25%的元素具有该值? I'm new to programming and tried several loops and ifs but nothing is working out for me. 我是编程新手,尝试了几次循环和ifs,但没有任何结果适合我。 Please push me towards the right direction. 请把我推向正确的方向。

25% of 25 is about 6. It is not accurate. 25的25%约为6。这是不正确的。 Here is a possible solution. 这是一个可能的解决方案。

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");
     }
}
}

I would do it like this 我会这样

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);
    }

}

I have commented the code to explain what everything does. 我已经注释了代码以解释所有操作。 However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. 但是,它不能防止用户输入错误,并且会对数组的大小进行硬编码,因此应始终避免硬编码。 In this example I did it (and marked where) to be more clear. 在此示例中,我做了(并标记在哪里)以使其更加清晰。 Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. 另外,正如上面评论中提到的那样,对于您所需要的25%中的25%的情况,这是不可能的。 This is because .25 * 25 = 6.25 and you can't have .25 of an element. 这是因为.25 * 25 = 6.25,而元素不能有.25。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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