오늘부터는 자바응용문제 풀어가며 자바의 알고리즘에 대해 공부를 할 것이다.
(1) 랜덤 닉네임 생성기
사용자는 최소 28가지 이사의 닉네임 중 하나를 랜덤으로 출력 할 수 있다.
(아래 키워드 사용)
기절초풍, 멋있는, 재미있는
도전적인, 노란색의, 바보같은
돌고래, 개발자, 오랑우탄
import java.util.Random;
public class RandomNicknameCreator {
private String[] firstList = {"기철초풍", "멋있는", "재미있는"};
private String[] secondList = {"도전적인", "노란색의", "바보같은"};
private String[] thirdList = {"돌고래", "개발자", "오랑우탄"};
public String createRandomNickname() {
Random random = new Random();
int index = random.nextInt(27);
String first = firstList[index / 9]; // 0~8 => firstList
String second = secondList[(index / 3) % 3]; // 0~8 => secondList
String third = thirdList[index % 3]; // 0~8 => thirdList
return first + " " + second + " " + third;
}
public static void main(String[] args) {
RandomNicknameCreator randomNicknameCreator = new RandomNicknameCreator();
String myNickname = randomNicknameCreator.createRandomNickname();
System.out.println(myNickname);
}
}
해설) import java.util.Random; : 이 선언을 통해 Random 클래스를 사용 할 수 있게한다.
int index = random.nextInt(27); 0부터 26까지의 랜덤한 정수를 생성한다. 총 27개의 조합이 가능하게 함
String first = firstList[index / 9]; : index / 9는 index를 9로 나눈 몫을 구함.
String second = secondList[(index / 3) % 3];
: index / 3는 index를 3으로 나눈 몫을 구함.
String third = thirdList[index % 3];
: index % 3는 index를 3으로 나눈 나머지를 구함.
return first + " " + second + " " + third;
최종적으로 선택된 세 개의 문자열을 겹합하여 최종 닉네임을 반환받아 결과를 출력한다.
랜덤 클래스를 활용하여 결과를 출력할 때 각 배열의 구조를 파악하고 확률을 구현 할 수 있게 하도록 하는것이 이 문제의 핵심이며 구조를 파악하고 Randam의 알고리즘만 정확히 판단한다면 어렵지 않게 문제를 해결 할 수 있다.