0부터 20까지 10 개의 임의의 반복되지 않는 숫자가있는 일반 정수로 채워진 배열을 만들어야합니다. 또한이를 수정하여 0에서 20까지의 임의의 숫자를 제외 할 수 있어야합니다.반복되지 않는 난수 배열
어떻게하면됩니까?
0부터 20까지 10 개의 임의의 반복되지 않는 숫자가있는 일반 정수로 채워진 배열을 만들어야합니다. 또한이를 수정하여 0에서 20까지의 임의의 숫자를 제외 할 수 있어야합니다.반복되지 않는 난수 배열
어떻게하면됩니까?
당신은 3 단계에서이 작업을 수행 할 수 있습니다
n
첫번째 요소를 셔플Collections.shuffle
원하는 모든 후보 번호와 목록을 작성 .이 방법을 사용할 수 있습니다. 이 방법은 결정하려면 : 그것은 편집 (20)
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
HashMap<Integer, Integer> duplicateChecker = new HashMap<Integer, Integer>();
int[] arr = new int[randomCount ];
int i = 0;
while(i<randomCount){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(maxRandomNumber);
if(duplicateChecker.containsKey(random)==false){
duplicateChecker.put(random, random);
arr[i]=random;
i++;
}
}
return arr;
}
* 0에서 10 개 개의 고유 한 난수를 생성합니다. 그리고 무한 루프의 가능성을 피하십시오.
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Generate an arrayList of all Integers
for(int i=0;i<maxRandomNumber;i++){
arrayList.add(i);
}
int[] arr = new int[randomCount ];
for(int i=0;i<randomCount;i++){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(arrayList.size());
// Remove integer from location 'random' and assign it to arr[i]
arr[i]=arrayList.remove(random);
}
return arr;
}
글쎄, 이론적으로 이것은 종료 보장되지 않습니다. 런타임은 결정적이지 않습니다. – Mat
@Mat Random.nextInt는 모든 숫자 외에도 균일하게 (다소간) 숫자를 배포하기 때문에 결국 멈 춥니 다. – Trismegistos
어느 시점에서 멈 춥니 다. 그러나 그 점은 별들의 적절한 정렬을 반복 한 메가 실 리온 (megaquazions of iterations) 이후 일 수 있습니다. 런타임이 결정적이지 않습니다. – Mat
대부분의 다른 응답은 솔루션으로 Collections.shuffle 메소드를 제공합니다.
public class RandomWithoutReplacement {
private int [] allowableNumbers;
private int totalRemaining;
/**
* @param upperbound the numbers will be in the range from 0 to upperbound (exclusive).
*/
public RandomWithoutReplacement (int upperbound) {
allowableNumbers = new int[ upperbound ];
for (int i = 0; i < upperbound; i++) {
allowableNumbers[i] = i;
}
totalRemaining = upperbound;
}
}
다음으로 우리는 우리가 다음 수를 얻을 필요가있을 때해야 할 일을 생각 할 수 있습니다 :
는먼저 목록을 구축 할 수 있습니다 : 이론적으로 빠른 또 다른 방법은 다음과 같다.
1) 다른 번호를 요청할 때, 가능한 한 균일하게 선택해야합니다.
2) 일단 선택하면 다시 반복해서는 안됩니다.
다음은 우리가 할 수있는 것입니다. 먼저 allowableNumbers
배열에서 임의로 숫자를 선택하십시오. 그런 다음 어레이에서 제거하십시오. 그런 다음 배열 끝에있는 번호를 제거하고 반환 할 번호의 위치에 놓습니다. 이것은 우리가 두 조건 모두를 보장합니다.
public int nextRandom() {
//Get a random index
int nextIndex = (int) (Math.random() * totalRemaining);
//Get the value at that index
int toReturn = allowableNumbers [ nextIndex ];
//Find the last value
int lastValue = allowableNumbers [ totalRemaining - 1 ];
//Replace the one at the random index with the last one
allowableNumbers[ nextIndex ] = lastValue;
//Forget about the last one
totalRemaining -- ;
return toReturn;
}
그로 인해 기능이 거의 완료되었습니다. 실제 함수의 시작 부분에
public boolean hasNext() {
return totalRemaining > 0;
}
을 그리고 :
난 그냥 경우에 몇 가지 더를 추가
public int nextRandom() {
if (! hasNext())
throw new IllegalArgumentException();
// same as before...
}
그것을해야한다고!
이 방법이 Collections.shuffle보다 더 빠르다고 생각하지 않습니다. 콜렉션 셔플은 exacly 같은 방식으로 작동하지만 배열을 섞은 후에 totalRemaining 변수를 제거 할 수 있기 때문에 적은 메모리를 사용합니다. 추가적으로 클래스는 N 개의 배열을 할당하지만 사용자는 그 번호의 배열을 필요로하므로 자신의 N 개의 배열을 할당하므로 메모리 제약 조건은 Collections.shuffle이 작동하는지 적어도 2 * N이므로 추가로 할당하지 않습니다 memory - 크기 N의 배열은 클래스에있는 것과 동일한 몇 가지 추가 로컬 변수를 더한 것입니다. – Trismegistos
[Collection.shuffle] (http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle (java.util.List)) 설명서를 읽는다면, 셔플하는 데 선형 시간이 걸리는 것을 볼 수 있습니다.이 시간은 구성하는 데 걸리는 선형 시간을 추가합니다. 또한, 메모리 사용량이 2 * N 이상이 아닙니다. 사용자는 대부분 N 개의 난수가 필요하기 때문에 실제로 ** ** ** 2 * N입니다. 사용자가 작은 무작위 하위 집합을 원한다면 내 접근 방식이 더 좋을 것 같고 사용자가 큰 임의의 하위 집합을 원할 경우 Collections.shuffle 접근 방식이 더 좋습니다. –
로컬 변수를 계산하지 않았으므로 2 * N * sizeof (int) 바이트가됩니다. – Trismegistos
글쎄, 난 숫자의 sequance를 두번만큼 많은 임의의 위치에 저장하는 내 솔루션을 게시하지 않을 수 없습니다. 그런 다음 결과 배열로 압축합니다.
int [] myRandomSet = generateNumbers (20, 10);
...
public int[] generateNumbers(int range, int arrayLenght){
int tempArray[];
int resultArray[];
int doubleLocations;
Random generator = new Random();
doubleLocations = range * 2;
tempArray = new int[doubleLocations];
resultArray = new int[arrayLenght];
for (int i=1; i<=range; i++){
if (i != 5 && i != 13){ //exclude some numbers
do{
r = generator.nextInt(doubleLocations);
}while(tempArray[r]!=0);
tempArray[r] = i; //enter the next number from the range into a random position
}
}
int k = 0;
for (int i=0; i<(doubleLocations); i++){
if(tempArray[i] != 0){
resultArray[k] = tempArray[i]; //compact temp array
k++;
if (k == arrayLenght) break;
}
}
return resultArray;
}
무엇 20 개까지 숫자의 ArrayList를 제작, 각 난수 후 전화 목록에서와 배열에 번호를 제거 약.
예를
Random r = new Random();
int[] myArray = new int[10];
ArrayList<Integer> numsToChoose = new ArrayList<Integer>();
int counter = 0;
for(int i = 0; i < 21; i++)
{
numsToChoose.add(i);
}
while(numsToChoose.size() > 11)
{
myArray[counter] = numsToChoose.remove(r.nextInt(numsToChoose.size()));
counter++;
}
단지 루프 10 번, 그래도 난 잘못 될 수 있어야 그런 식으로. 호프 도움이
편집 : 특정 숫자를 제외하려면이 수정하려면 매개 변수로 해당 숫자를 포함하는 배열을 사용하고 루프를 통해 전에 arraylist 각 숫자를 제거하는 루프가 필요합니다 당신은 당신의 난수를 생성합니다.
이 숙제가 있습니까? – asgs