반응형
안녕하세요. pitang입니다.
메서드 활용 응용문제 2개를 살펴보겠습니다.
RandomSeat
정수를 매개변수로 받아서 1부터 매개변수까지의 값을 배열에 랜덤 하게 넣어 반환해주는 함수 seat을 생성하세요.
조건 - 숫자는 중복되지 않고 swap을 이용하지 않습니다.
ex) 입력 - 10, 출력 - [1~10가 랜덤하게 섞여있는 길이가 10인 배열
<console>
[7, 3, 2, 4, 10, 1, 6, 9, 8, 5]
⬇️⬇️⬇️ 정답은 더보기를 눌러주세요 ⬇️⬇️⬇️
더보기
public class RandomSeat {
public static void main(String[] args) {
int[] arr = seat(10);
System.out.println(Arrays.toString(arr));
}
static int[] seat(int size) {
int[] arr = new int[size];
int index = 0;
start:while(true) {
int ran = (int)(Math.random() * size) + 1;
for(int i = 0; i < index; i++) {
if(arr[i] == ran) {
continue start;
}
}
arr[index] = ran;
index++;
if(index == size) break;
}
return arr;
}
}
RandomLotto
무작위로 생성된 로또번호를 이용하여 당첨되기까지 금액을 알아보는 프로그램입니다.
lotto 함수는 1 ~ 45 까지의 중복되지 않는 랜덤수를 배열에 넣어 반환하는 메서드이다.
이 메서드의 실행 결과는 당첨번호가 된다.
조건 - 입력 - x,
출력 - 길이가 6인 배열
run 함수는 당첨배열을 받아서 당첨되기까지 랜덤 한 금액을 계산하는 메서드이다.
조건 - 입력 - 당첨배열,
출력 - long(당첨되기까지의 금액)
<console>
당첨번호 : [29, 25, 16, 14, 37, 34]
당첨되기까지 필요한 금액 : 3724913000
⬇️⬇️⬇️ 정답은 더보기를 눌러주세요 ⬇️⬇️⬇️
더보기
public class RandomLotto {
public static void main(String[] args) {
int[] arr = lotto();
System.out.println("당첨번호 : " + Arrays.toString(arr));
long value = run(lotto());
System.out.println("당첨되기까지 필요한 금액 : " + value);
}
static int[] lotto() {
int[] arr = new int[6];
int index = 0;
ex:while(true) {
if(index == 6) break;
int num = (int)(Math.random() * 45) + 1;
for(int i = 0; i < index; i++) {
if(num == arr[i]) continue ex;
}
arr[index] = num;
index++;
}
return arr;
}
static long run(int[] arr) {
long count = 0;
Arrays.sort(arr);
while(true) {
int[] arr2 = lotto();
Arrays.sort(arr2);
// System.out.println(count);
if(Arrays.equals(arr, arr2)) {
return count * 1000;
} else {
count++;
}
}
}
}
감사합니다.
*m1맥북을 사용 중입니다.*
728x90
반응형
'알고리즘 > 기타퀴즈' 카테고리의 다른 글
quiz 03 Package (0) | 2021.09.01 |
---|---|
quiz02 Package (0) | 2021.09.01 |
MethodQuiz01, MethodQuiz02 (0) | 2021.08.31 |
Quiz22, Quiz23 (0) | 2021.08.30 |
Quiz20, Quiz21 (정렬방법) (0) | 2021.08.30 |