2012-11-21 2 views
1

1에서 45 사이의 6 개의 숫자 로또 드로잉을 시뮬레이트하는 프로그램을 작성 중이며 샘플 출력은 3 7 12 27 43 28입니다.하지만 내가하려고하는 것은 인접 숫자가 나타나는 횟수를 세는 것입니다 , 예를 들어 1 4 5 29 26 41은 긍정적 인 답변입니다. 5가 4 이후에옵니다.자바 로또 시뮬레이션

그 중 가장 좋은 방법은 무엇입니까? 같은

내가 시도 예 :

int adjacent=0; 

    for(int i =0; i<6; i++) 
    { 
     int t = test[i]+1; 
     test[i]=(int)(45*Math.random())+1; 

     if(test[i]==t) 
      adjacent++; 

     System.out.print(test[i]+" "); 
    } 

이 작동하지 않습니다.

내가 뭘 잘못하고 있니?

+1

출력 내용은 '1 4 29 5 26 41'이고, 여전히 4와 5를 셉니까? –

+0

아니요 서로 옆에 있어야합니다. – user1816464

+0

결과의 순서가 중요합니까? 로또에 반복이있을 수 있습니까? –

답변

0

내가 방금 작업에 문제가 이런 일에 주위

int adjacent=0; 

for(int i =0; i<6; i++) 
{ 
    //test[i] hasn't been set yet 
    int t = test[i]+1; 
    test[i]=(int)(45*Math.random())+1; 

    //this comparison doesn't make a whole lot of sense 
    if(test[i]==t) 
     adjacent++; 

    System.out.print(test[i]+" "); 
} 

변경을의 순서를 생각 :

int adjacent=0; 

for(int i =0; i<6; i++) 
{ 
    test[i]=(int)(45*Math.random())+1; 

    if(i != 0 && test[i]==(test[i-1]+1)) 
     adjacent++; 

    System.out.print(test[i]+" "); 
} 
:

int adjacent=0; 

for(int i =0; i<6; i++) 
{ 
    test[i]=(int)(45*Math.random())+1; 
    int t = -1; 
    //Make sure this comparison only happens after the second iteration 
    //to avoid index out of bounds 
    if (i != 0) 
    { 
     //Set t to the last number + 1 instead of trying to predict the future 
     t = test[i-1] + 1; 
    } 
    //Now this comparison makes a little more sense 
    //The first iteration will compare to -1 which will always be false 
    if(test[i]==t) 
     adjacent++; 

    System.out.print(test[i]+" "); 
} 

이 더 간단하게 할 수 그냥이에

+0

이렇게하면 8이 그려지고 7이 뒤따 랐을 때 나에게 긍정적 인 결과를 주거나 코드를 오해하고 있습니다. – user1816464

+0

@ user1816464 반대로하면 단축 버전에 더하기 기호가 표시됩니다. 이제 수정되었습니다. –

+0

감사합니다. 이제 작동합니다! 귀하의 모든 설명과 도움을 주셔서 감사합니다! – user1816464

0

나는 그것을 뒤섞어서 5 개를 가져 가야한다고 생각합니다. Collections#Shuffle 당신을 도울 것입니다, 그것은 임의의 기본 소스를 사용하여 지정된 목록을 바꾸어줍니다. 모든 순열은 거의 동일한 가능성으로 발생합니다.

List<Integer> list = ArrayList<Integer>(); 
list.add(1); 
list.add(2); 
Collections.shuffle(list); 
Random rnd = new Random(); 
Integer[] result = new Integer[5]; 
result[0] = list.get(rnd.getNextInt(45)); 
result[1] = list.get(rnd.getNextInt(45)); 
result[2] = list.get(rnd.getNextInt(45)); 
result[3] = list.get(rnd.getNextInt(45)); 
result[4] = list.get(rnd.getNextInt(45)); 

항상 임의 값을 제공하므로 오름차순으로 정렬하도록 정렬해야합니다.

Arrays.sort(result); 

이제 인접한 번호를 찾기 위해 루프를 작성할 수 있습니다.

int adjacent = 0; 
for(int i=1; i<result.length;i++){ 
    int prev = result[i-1]; 
    int now = result[i]; 
    if(prev+1 == now) 
    adjacent++; 
} 
+0

이 질문에 대한 답이 확실하지 않습니다. 그러나 이것은 6 개의 lotto 숫자를 생성하기 위해 Random을 사용하는 것보다 낫습니다. –

+0

질문은 인접한 값을 찾는 것입니다. 처음에 임의의 숫자를 생성하는 방법이 아닙니다. –

+0

예 u r, 나는 그것을하기위한 올바른 방법을 보여주고 싶습니다. 어쨌든 '- 지금 당장이라면?' –

0

6 개의 숫자를 생성하고 배열에 넣은 후에. Arrays.sort()을 사용하십시오. 그런 다음 인접한 배열 항목을 비교할 수 있습니다.

중복을 생성 할 수 있으므로 6 자리 숫자를 생성하는 데는 임의 번호를 사용하지 않는 것이 좋습니다. 이것은 정확하게 당신의 로또 끌기를 시뮬레이트하지 않을 수도 있습니다. Quoi의 대답은 이것에 대한 좋은 제안입니다.

+0

downvote의 이유? –

0

고유 생성을 분리해야합니다 (따라서 신원을 보장하기 위해 아래의 HashSet이 필요합니다) 임의 선택, 정렬, 인접성 결정 :

import java.util.HashSet; 
import java.util.Arrays; 

public class Lotto 
{ 
    public Lotto() 
    { 

    } 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) 
    { 
     Lotto lotto = new Lotto(); 
     lotto.randomizeSelections(5); 
    } 

    private void randomizeSelections(int numOfArrays) 
    { 
     for(int i = 0; i < numOfArrays; i++) 
     { 
      int[] selArry = new int[6]; 
      //to insure that each random selection is unique 
      HashSet<Integer> idntySet = new HashSet<Integer>(); 

      for(int j = 0; j < 6;) 
      { 
       int rndm = (int)(45 * Math.random()) + 1; 

       //add selection to the array only if it has not been randomized before 
       if(!idntySet.contains(rndm)) 
       { 
        selArry[j] = rndm; 

        j++; 
       } 

      } 

      //sort the array for determing adjacency 
      Arrays.sort(selArry); 

      for(int j = 0; j < 6; j++) 
      { 
       int sel = selArry[j]; 
       boolean isAdjcnt = (j > 0 && (sel == selArry[j - 1] + 1)) ? true : false; 

       System.out.println(i + "." + j + ".random = " + sel); 

       if(isAdjcnt) System.out.println("\tAdjacent"); 

      } 
     } 
    } 
} 
관련 문제