본문 바로가기

프로그래밍/JAVA

[jAVA] 랜덤(Random) 클래스

[ 메서드 ]


Random ( ) : System.현재시간을 종자값(sedd)으로 이용하는 Random 인스턴스 생성

Random (long seed) : 매개변수seed를 종자값으로 이용하는 Random인스턴스 생성

boolean nextBoolean( ) : boolean 타입의 난수를 반환

void nextBytes(byte[] bytes) : bytes 배열에 byte 타입의 난수를 채워서 반환

double nextDouble() : double 타입의 난수를 반환 (0.0 <= x < 1.0)

float nextFloat() : float 타입의 난수를 반환 (0.0 <= x < 1.0)

double nextGaussian() : 평균은 0.0이고, 표준편차는 1.0인 가우시안 분포에 따른 double형의 난수를 반환

int nextInt() : int타입의 난수를 반환

int nextInt(int n) : 0~n의 범위에 있는 int값을 반환 (n은 포함시키지 않음)

long nextLong() : long타입의 난수를 반환 (long의 전범위)

void setSeed(long seed) : 종자값을 주어진 값(seed)으로 변경한다.


Math.random()과 Random의 차이점 : 종자값(seed)을 설정할 수 있다는 것이다.

종자값(seed)는 쉽게 생각해서 "기준점"이라고 생각하면 되겠다.


같은 종자값(1)을 사용하기 때문에 같은 실행결과를 얻는다.



[ 응용 메서드 ]


int getRandom (int from, int to)  :  from~to 범위의 정수(int)값을 반환


class exercise
{
public static void main(String[] args){

for(int i = 0 ; i<10; i++){
System.out.print(getRandom(100,90) + ", ");
}
}

public static int getRandom(int from, int to){

return (int)(Math.random()*((Math.abs(to-from))+1)) + Math.min(from, to);
}
}


getRand의 리턴값을 살펴보자getRand(90, 100) 인 경우


① 0.0<=Math.random()<1.0

② Math.abs(from-to) +1 = 11

③ 0<=(int)(Math.random()*((Math.abs(from-to)+1))<11

④ Math.min(90, 100) 인 경우 최소값 90이 출력

⑤ 90<=(int)(Math.random()*((Math.abs(from,to)+1))+Math.min(from, to)<101

⑥ 90이상 ~100이하의 난수 출력



int [ ] fillRandom ( int [ ] arr, int from, int to ) : 배열 arr을 from~to 범위의 값으로 채워서 반환

int [ ] fillRandom ( int [ ] arr, int [ ] data ) : 배열 arr을 배열 data에 있는 값들로 채워서 반환


위 메서드를 위해서는 맨 처음 응용메서드 getRandom이 필요하다.


class exercise
{
public static void main(String[] args){

int [] result1 = fillRand(new int[10], new int[]{1, 3, 5, 7});
int [] result2 = fillRand(new int[10], 1, 2);

System.out.println(Arrays.toString(result1));
System.out.println(Arrays.toString(result2));
}

public static int[] fillRand(int[] arr, int from, int to){
for(int i = 0 ; i<arr.length; i++){
arr[i] = getRandom(from, to);
}
return arr;
}

public static int[] fillRand(int[] arr, int[] data){
for(int i = 0; i<arr.length; i++){
arr[i] = data[getRandom(0, data.length-1)];
}
return arr;
}

public static int getRandom(int from, int to){
return (int)(Math.random()*((Math.abs(to-from))+1)) + Math.min(from, to);
}
}


fillRand가 두 가지 버전으로 오버로딩 되고 있음을 알 수 있다.

int[] data 부분을 보면 data 배열의 길이 - 1을 해줘야 ArrayIndexOutOfBoundException이 일어나지 않는다.


String [ ] fillDistinctRandom ( String [ ] arr, String [ ] data ) : 배열 arr을 배열 data에 있는 값들로 중복없이 채워서 반환한다.


String [] result3 = fillDistinctRandom(new String[3],                                         new String[]{"A+", "A", "B+", "B", "C+", "C"});

public static String[] fillDistinctRandom(String[] arr, String[] data){
if(arr.length<=0 || data.length<=0) return arr;

HashSet<String> hs = new HashSet<String>(arr.length);

while(hs.size() < Math.min(arr.length, data.length)){
hs.add(data[getRandom(0, data.length-1)]); // getRandom 메서드를 구현해놔야 함.
}

Object[] tmp = hs.toArray();
for(int i = 0 ; i<tmp.length; i++){
arr[i] = (String)tmp[i];
}
return arr;
}



[ 가중치 주기 ] 마치 게임 아이템 뽑기랄까..


class exercise
{
public static void main(String[] args){

String[] data = {"A", "A", "B", "C"};

HashMap<String, Integer> map = new HashMap<String, Integer>();

for(int i = 0 ; i < 100; i++){
String temp = getRandArr(data); // temp는 getRand의 난수
if(map.containsKey(temp)){
Integer value = (Integer)map.get(temp);
map.put(temp, new Integer(value.intValue()+1));
} else {
map.put(temp, new Integer(1));
}
}

Iterator<String> it = map.keySet().iterator();
while(it.hasNext()){
String key = (String)it.next();
Integer value = (Integer)map.get(key);
int intValue = value.intValue();
System.out.println(key + " : " + printGraph('$', intValue) + intValue);

}
}
public static String printGraph(char ch, int value){
char[] bar = new char[value];
for(int i=0; i<bar.length; i++){
bar[i] = ch;
}
return new String(bar);
}
public static String getRandArr(String[] arr){
return arr[getRand(arr.length-1)];
}

public static int getRand(int n){
return getRand(0, n);
}

public static int getRand(int from, int to){
return (int)(Math.random()*(Math.abs(to-from)+1)) + Math.min(from, to);
}
}


'프로그래밍 > JAVA' 카테고리의 다른 글

[JAVA] 제너릭(Generic)  (0) 2016.10.25
[JAVA] 배열(array)  (0) 2016.09.03
[JAVA] 캘린더(Calendar)  (0) 2016.08.31
[jAVA] 해시맵(HashMap)  (0) 2016.08.31
[JAVA] StringBuilder & StringBuffer, Math, Wrapper 클래스  (0) 2016.08.25