영상
문제
<script>
/*
[문제]
[1] arr배열에 1~10까지의 랜덤 숫자 3개를 저장 후 출력하시오.
[2] 단, 숫자 3개는 서로 중복되면 안 된다.
[3] 숫자 3개의 합은 반드시 20이어야 한다.
[예시]
[3, 10, 7] o
[5, 10, 5] x
*/
let arr = [0, 0, 0];
</script>
Java
복사
해설
<script>
/*
[문제]
[1] arr배열에 1~10까지의 랜덤 숫자 3개를 저장 후 출력하시오.
[2] 단, 숫자 3개는 서로 중복되면 안 된다.
[3] 숫자 3개의 합은 반드시 20이어야 한다.
[예시]
[3, 10, 7] o
[5, 10, 5] x
*/
let arr = [0, 0, 0];
let total = 0;
let count = 0;
while(true) {
let num = Math.floor(Math.random() * 10) + 1;
let check = false;
for(let i=0; i<count; i++) {
if(num == arr[i]) {
check = true;
break;
}
}
if(check == false) {
arr[count] = num;
total += arr[count];
count += 1;
}
if(count == 3) {
if(total == 20) {
break;
} else {
total = 0;
count = 0;
}
}
}
document.write(arr);
</script>
Java
복사