로또 번호(중복 되지 않는 6개짜리 숫자열)

 

예전에 중복 체크할땐

 

for(int i = 0; i<arr.length; i++)

{

    for(int j = i+1; j<arr.length; j++)

    {

        if(arr[i] == arr[j])

            isDuplicate = true;

     }

}

요런 식으로 접근했는데..

 

이걸 풀어서 (배열 이름과 연산자 우선순위는 생략)

if( ([0] != [1] && [0] != [2] && [0] != [3] && [0] != [4] && [0] != [5] ) &&

    ([1] != [2] && [1] != [3] && [1] != [4] && [1] != [5])                     &&

    ([2] != [3] && [2] != [4] && [2] != [5])                                        &&

    ([3] != [4] && [3] != [5])                                                            &&

    ([4] != [5]) )

  {

     isDuplicate = false;

  }

 

요런식으로 하면.. 과연 누가 더 빠를까?? (컴파일러가 첫번째걸 어떻게 최적화 시킬지 궁금)

테스트 GoGo!

 

*****************테스트 결과*******************

(처음엔 milisecond으로 받아봤는데 둘다 0이라서 nanosecon으로 변경 = 백만분의 1초가 단위)

 

첫번째 로직 경과시간:45450
두번째 로직 경과시간:2932

=>결론: 배열 첨자 연산은 cpu레지스터에 올라가 저장되고 다른 연산 없이 비교 연산만 반복해주면

           됨으로 엄청 빠르다??   근데 저따위로 풀어쓰면 ㅠㅠ

 

그만 놀고 공부;;;

 

public class main
{

 public static void main(String[] args)
 {
  // TODO Auto-generated method stub
  int[] n = {0,1,2,3,4,5};
  
  //시간 테스트
  A(n);
  
  B(n);
 }

 public static void A(int[] n)
 {
  //시작 시간
  long st = System.nanoTime();
  
  for(int i=0; i< n.length; i++)
  {
   for(int j=i+1; j<n.length; j++)
   {
    if(n[i] == n[j])
    {
     int a = 1;
    }
   }
  }
  
  System.out.println("경과시간:" + (System.nanoTime() - st));
 }
 
 public static void B(int[] n)
 {
  long st = System.nanoTime();

  if( ((n[0] != n[1]) && (n[0] != n[2]) &&(n[0] != n[3]) &&(n[0] != n[4]) && (n[0] != n[5])) && 
   ((n[1] != n[2]) && (n[1] != n[3]) && (n[1] != n[4]) && (n[1] != n[5])) &&
   ((n[2] != n[3]) && (n[2] != n[4]) && (n[2] != n[5])) &&
   ((n[3] != n[4]) && (n[3] != n[5])) && 
   ((n[4] != n[5]))
   )
  {
   int a = 1;
  }
   
  System.out.println("경과시간:" + (System.nanoTime() - st));
 }
}

 

by givingsheart 2014. 1. 1. 15:42