나는이 질문에 대한 답을 알고 있지만 그 해결책은 내가 진행하는 방식과 맞지 않으므로 더 간단한 해결책이 있는지 문의하고 있습니다.
나는 세트 인터페이스를 사용하고 있으며 6 개의 난수가 필요하며 세트 인터페이스에서 중복을 가질 수 없습니다.
이것이 제가 현재 가지고있는 것입니다. 제가하는 방식은 이상적이지 않고 종종 충돌을 일으 킵니다.
public void drawLotto(){ //The validation I have here I know isn't the most effective way and is-
Random r = new Random();//resource comsuning but this was the only way I could think of doing it.
int draw[] = new int[6];
int min = 1;
for(int i = 0; i < draw.length; i++){
draw[i] = r.nextInt(lotteryMax-min) + min;
lotteryDraw.add(draw[i]);
}
int size = lotteryDraw.size();
if(size != 6){
drawLotto();
}
for(int i = 0; i < draw.length; i++){
System.out.println(draw[i] + " ,");
}
System.out.println();
}
``
Thank you, any help is appreciated.
문제가있는 이유는 drawLotto ()를 재귀 적으로 호출하여 Random의 새 인스턴스를 생성하기 때문입니다. drawLotto ()가 올바른 목록을 만들 수없는 경우 6 개의 숫자를 모두 다시 시도해야합니다. 이로 인해 응용 프로그램이 많은 양의 메모리를 사용하여 충돌이 발생할 수 있습니다.
이를 수행 할 수있는 한 가지 방법은 6 개의 고유 한 숫자를 찾을 때까지 계속 반복하는 것입니다.
public void drawLotto(){
Random r = new Random();
Set<Integer> draw = new HashSet<>();
int min = 1;
int lotteryMax = 50;
while(draw.size() < 6){
draw.add(r.nextInt(lotteryMax-min) + min);
}
String lotteryDrawing = draw.stream().map(String::valueOf).collect(Collectors.joining(" ,"));
System.out.println(lotteryDrawing);
}
lotteryMax가 필요한 숫자보다 높은지 확인해야하지만
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다