2014-11-02 2 views
0

배열 A [5] [5]와 여러 값이 있습니다. 내가 만든 무작위 비율을 기반으로 임의로 값을 지정하려고합니다. 예를 들어 하나의 값은 6이고 배열 요소의 25 %는 6을 가져야합니다. 내가 지금까지 가지고있는 것 : 난 무작위 비율을 만들었고 어레이의 다른 요소에 값을 무작위로 할당 할 수있었습니다. 내 문제는 : 요소의 25 % 이상 6이 있습니다. 내 질문은 : 6, 정확히 배열의 요소 중 25 % 요소를 할당 할 때 [5] [5] 해당 값을 가질 수 있도록하려면 어떻게해야합니까? 나는 프로그래밍에 익숙하지 않고 몇 가지 루프와 if를 시도했지만 아무것도 작동하지 않습니다. 나를 올바른 방향으로 밀어주십시오.임의로 배열하는 Java 2D 배열

+3

우리가 ** 정확히 * * 임의의 비율을 만들고 않은 방법 ** 그것은 – chiwangc

+1

에 개선을 도울 수 있도록이 코드를 게시하시기 바랍니다 ** 당신이 무작위로 값을 할당 할 수있는 방법 ** * 배열의 다른 요소 *? 우리가 당신을 도울 수 있도록 도와주세요. –

+0

5x5 배열에는 25 개의 요소가 있습니다. 25 %가 1/4이고 25 개의 요소가 4로 나눌 수 없으므로 * 정확하게 * 25 %의 요소를 얻을 수 없습니다. – pjs

답변

0

는 내가 모든 무엇을 설명하는 코드를 댓글을 달았이

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 개의 요소를 가질 수 없기 때문입니다.

1

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