상세 컨텐츠

본문 제목

[JAVA] 자바 랜덤 함수, 비중복 랜덤 값 뽑기.

Java..Story

by HeyLee 2011. 9. 15. 15:46

본문


이번에 프로젝트 하면서 Random 함수를 쓸일이 좀 많더라구요.


그래서 Random 함수 정리 및 비중복 랜덤값 뽑는 메소드를 만든김에 포스팅 하려고 합니다.


물론 다른 블로그님들 뒤져봐도 저보다 좋게 만드신분들 많으실꺼라 생각되서 부끄럽지만...


공부겸 정리 하는김 하는거니 뭐....


http://developer.android.com/reference/java/util/Random.html -새창으로 열기.

java.util.Random

This class provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.
See Also

 

Public MethodsbooleannextBoolean()

Returns a pseudo-random uniformly distributed boolean.
voidnextBytes(byte[] buf)
Fills buf with random bytes.
doublenextDouble()
Returns a pseudo-random uniformly distributed double in the half-open range [0.0, 1.0).
floatnextFloat()
Returns a pseudo-random uniformly distributed float in the half-open range [0.0, 1.0).
synchronized doublenextGaussian()
Returns a pseudo-random (approximately) normally distributed double with mean 0.0 and standard deviation 1.0.
intnextInt(int n)
Returns a pseudo-random uniformly distributed int in the half-open range [0, n).
intnextInt()
Returns a pseudo-random uniformly distributed int.
longnextLong()
Returns a pseudo-random uniformly distributed long.
synchronized voidsetSeed(long seed)
Modifies the seed using a linear congruential formula presented in The Art of Computer Programming, Volume 2, Section 3.2.1.


대충 여러가지 있습니다. 기본형으로는 대부분 랜덤값 추출이 가능하군요.
저는 인트값에 비중복 값을 뽑을일이 생겨서 비중복으로 랜덤함수를 뽑는 메소드를 만들었습니다..

1. 랜덤 선언.
2.  lenght길이 만큼 배열 메모리 할당
3.  0~lenght까지 랜덤값 추출. 
4. 첫번쨰로 나온 랜덤Int값을 배열 첫번쨰로 저장. 
5. for  문 처음에서 다시 랜덤을 뽑음 이전에 뽑았던 수랑 같다면 새로 NextInt 하고 j 초기화
6. 같지 않다면 배열에 저장후 j-- 하면서 다른 것들과도 조건을 맞춰본다.

1 void randWordPlace(){ 2 //랜덤 석기 10은 단어갯수. 0~10 총 11개. 3 Random rnd = new Random(); 4 rndInt= rnd.nextInt(AnimalList.size()-1); 5 lenght = AnimalList.get(rndInt).mWordLenght; 6 arr = new int[lenght]; 7 //배열에 저장. 랜덤 숫자 0~11의 랜덤 위치. 8 int a= rnd.nextInt(lenght-1); 9 arr[0] = a; 10 for(int k=1; k<lenght; k++) { 11 a = rnd.nextInt(lenght); 12 int j=k-1; 13 while( j>=0 ) { 14 if( arr[j] == a ) { 15 a = rnd.nextInt(lenght); 16 j=k-1; 17 } 18 else { 19 arr[k]=a; 20 j--; 21 } 22 } 23 } 24 }

 
대충 성능은..N제곱 정도 나오지 않을까..생각중입니다~_~; 비중복으로 뽑아야되는 수가 적으면 쓸만하겠네요.. -_-;


비중복 랜덤값 만드는 로직 A~D까지 소개 되어있는데 위 비중복 알고리즘은 A 네요.
젤 구현 간단하면서 젤 속도 느린거?
누군가 처음으로 저 블로그를 썻는지는 몰르겠지만 이놈 저놈 블로그마다 죄다 복사 붙여넣기 되어있는거 하나 링크 그냥 가져왔습니다.
http://blog.naver.com/PostView.nhn?blogId=cheeryca&logNo=40111200707&redirect=Dlog&widgetTypeCall=true


그냥 훨씬 간단한 비중복 랜덤 함수가 되네요.

아나 어렵게 생각한거보다 그냥 젤 간단한게 효율이 좋다늬..

처리 속도에서 N제곱 보다 2N 정도의 처리 차이라면 차라리 2n처리 속력이 좋지 않을까 합니다.

1 import java.util.Random; 2 3 public class test { 4 public static void main(String[] args) { 6 int tmp=0; 7 int size=10; 8 int i=0; 9 int[] test = new int[10]; 10 Random rnd = new Random(); 11 for(i=0;i<10;i++){ 12 test[i]= i; 13 } 14 for(i=0;i<10;i++){ 15 int des =rnd.nextInt(size); 16 tmp = test[i]; 17 test[i]=test[des]; 18 test[des]=tmp; 19 } 20 for(int t=0;t<test.length;t++){ 21 System.out.println(""+test[t]); 22 } 23 } 24 } 







관련글 더보기

댓글 영역