영상
개념
<script>
/*
[문제]
1. 인덱스 2개를 랜덤(0~4)으로 저장하고 각 인덱스의 값을 교환한다.
2. 위 1번을 10회 반복하며 과정을 출력하시오.
[예시]
예) 1, 2 ==> 10,30,20,40,50 // 20 과 30이 교환된다.
예) 4, 1 ==> 10,50,20,40,30 // 50 과 30이 교환된다.
예) 3 3 ==> 10,50,20,40,30 // 같을 땐 아무일도안생긴다.
*/
let arr = [10, 20, 30, 40, 50];
for(let i=0; i<10; i++) {
let index1 = Math.floor(Math.random() * arr.length);
let index2 = Math.floor(Math.random() * arr.length);
let temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
console.log(index1 + ", " + index2 + " ===> " + arr);
document.write(index1 + ", " + index2 + " ===> " + arr + "<br>");
}
document.write(arr + "<br>");
//----------------------------------------------------------
let i = 0;
while(i < 10) {
let index1 = Math.floor(Math.random() * arr.length);
let index2 = Math.floor(Math.random() * arr.length);
let temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
i += 1;
}
document.write(arr + "<br>");
</script>
Java
복사