繁体   English   中英

Java 2D数组随机分配

[英]Java 2D array assigning randomly

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

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

我会这样

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

}

我已经注释了代码以解释所有操作。 但是,它不能防止用户输入错误,并且会对数组的大小进行硬编码,因此应始终避免硬编码。 在此示例中,我做了(并标记在哪里)以使其更加清晰。 另外,正如上面评论中提到的那样,对于您所需要的25%中的25%的情况,这是不可能的。 这是因为.25 * 25 = 6.25,而元素不能有.25。

暂无
暂无

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

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