random으로 숫자 n개 뽑기

frenchkebab·2021년 9월 18일
0

javascript 지식

목록 보기
6/36

random으로 1~45 중 7개 숫자 뽑기

렛츠기릿 자바스크립트 강의에서 배운 2 가지의 random으로 숫자 뽑기 방식을 정리하였습니다.


숫자 야구 게임 방식

const arr = Array(45).fill().map((val, i) => { return i + 1 });
const answer = [];
for(int i = 0; i < 7; i++) {
  const index = Math.floor(Math.random() * arr.length);
  answer.push(arr.splice(index, 1)[0]);  // splice는 배열을 return함을 유의
}

1~45 중 random으로 숫자를 1개씩 7번 뽑기
splice배열반환함에 유의하자!


로또 추첨 방식 (피셔-예이츠 셔플)

const arr = Array(45).fill().map((val, i) => { return i + 1 });
const shuffle = [];
while(arr.length > 0) {
  const index = Math.floor(Math.random() * arr.length);
  const value = arr.splice(index, 1)[0]; // splice는 배열을 return함을 유의
  shuffle.push(value);
}

1~45 숫자를 random으로 섞은 후 앞에서 7개를 빼내기


profile
Blockchain Dev Journey

0개의 댓글