const candidate = Array(45).fill().map((v, i)=> i + 1);
//빈배열 45개 만들고, undefined로 45개 채운다, map을 이용해 index에 1을 더한다.
//1부터 45까지 뽑는 코드
const shuffle =[];
while(candidate.length > 0){
const random = Math.floor(Math.random() * candidate.length); // 무작위 인덱스 뽑기
const spliceArray = candidate.splice(random, 1); // 뽑은 값은 배열에 들어 있음. //빼냈던 것의 값이 return으로 나옴.
// ex) [2,4,1] splice(1,1) //[4]
const value = spliceArray[0]; //배열에 들어 있는 값을 꺼내어
shuffle.push(value); //shuffle 배열에 넣기
}
while문은 조건이 간단하면 쓰기가 편하고 조건이 복잡할 때는 for문이 더 편하다.
또, while은 몇번 반복해야되는지 내가 감이 안 올 때 사용하면 좋다. (항상 그런 건 아님.)
피셔예이츠는 코드가 알아서 감소가 되니까 while 쓰면 좋음.
만약 while 안에 i++ 이런식으로 조건이 들어가면 그때는 for을 사용하는 게 좋음.
for(let i=candidate.length; i>0; i--){
const random = Math.floor(Math.random() * i);
const spliceArray = candidate.splice(random, 1);
const value = spliceArray[0];
shuffle.push(value);
}
출처: 제로초님 렛츠기릿 자바스크립트 강의
'Javascript > 알고리즘' 카테고리의 다른 글
[Algorithm] Tim sort (sort 알고리즘 중 하나) (0) | 2022.04.22 |
---|