2014-11-30 5 views

답변

1
static void placeRandomly2D(int[][] arr, int limit) { 
// generates value [0...limit) half-interval and places it into the 2D array arr 
// at random position; limit must be positive 
    Random rand = new Random(); 
    int value = rand.nextInt(limit); 
    int pos1 = rand.nextInt(arr.length); 
    int pos2 = rand.nextInt(arr[pos1].length); 
    arr[pos1][pos2] = value; 
} 

그리고, 단지 경우에, 1 차원 배열에 대한 버전 :

static void placeRandomly1D(int[] arr, int limit) { 
// generates value [0...limit) half-interval and places it into the 1D array arr 
// at random position; limit must be positive 
    Random rand = new Random(); 
    int value = rand.nextInt(limit); 
    int pos = rand.nextInt(arr.length); 
    arr[pos] = value; 
} 
+2

이 단지 1 차원 배열을 처리하는 것. – recursive

+0

갓 시드 된 RNG의 랜덤 성이 보장되지 않기 때문에 메소드 외부의 곳에 'new Random()'생성을 추출해야합니다. – Vogel612

+0

@ Vogel612 : 이론상으로, 인수 시스템 시간이없는'Random' 생성자가 시드로 간주되기 때문에 다른 호출에서 서로 다른 시드가 예상되므로 서로 다른 호출간에 무작위 결과가 보장됩니다. 그러나'placeRandomly1D()'메쏘드가 같은 밀리 세컨드 내에서 여러 번 호출된다면 동일한 값을 생성 할 것입니다 (생성 된 랜덤 인스턴스는 동일한 시드를 가질 것입니다). 이게 네가 말하는거야? –