반업주부의 일상 배움사

JS 배열 섞기 본문

IT 인터넷/Node.js

JS 배열 섞기

Banjubu 2023. 5. 13. 20:32
반응형

 

피셔-예이츠 셔플(Fisher-Yates shuffle)을 활용한 배열 섞기

function shuffle(array) {
  for (let index = array.length - 1; index > 0; index--) {
    // 무작위 index 값을 만든다. (0 이상의 배열 길이 값)
    const randomPosition = Math.floor(Math.random() * (index + 1));

    // 임시로 원본 값을 저장하고, randomPosition을 사용해 배열 요소를 섞는다.
    const temporary = array[index];
    array[index] = array[randomPosition];
    array[randomPosition] = temporary;
  }
}

 

참고: https://7942yongdae.tistory.com/96

반응형
LIST
Comments