숫자 야구 게임 | 무작위 숫자 뽑기 (for문, while문)

uoah·2023년 2월 15일

Training

목록 보기
16/20
post-thumbnail

📝 무작위 숫자를 뽑는 과정

code
Math.random()0 <= x < 1
Math.random() * 90 <= x < 9
Math.floor(Math.random() * 9 +1)x = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  • 숫자 내림 : Math.floor()
  • 숫자 올림 : Math.ceil()
  • 숫자 반올림 : Math.round()

⚠️ 주의

Math.random() 은 완전한 무작위는 아니다. 보안과 관련된 작업(ex. 비밀번호 생성)을 할 때는 Math.random() 으로 생성된 수를 사용하면 위험하다.
이를 위한 window.crypto.getRandomValues() 함수가 따로 있다.


🔗 숫자, 수학 method (Number, Math) 복습하러 가기


const $input = document.querySelector('#input');
const $form =  document.querySelector('#form');
const $logs = document.querySelector('#logs');

const numbers = []

1. 1~9까지 배열 만들기

📍 for문 사용

for(i=0; i < 9; i++){
  numbers.push( i + 1 );
}

console.log(numbers); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

📍 While 문 사용

💬 for 문을 while 문으로 바꾸는 연습도 꼭 해 보자.

let i = 0;
while(i < 9){
  numbers.push(i+1);
  i++;
}

console.log(numbers); // (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

📍 배열과 객체 중 사용하는 기준

  • 값만 필요할 땐 배열(Array)
  • 각각의 값에 속성 이름을 붙여서 값을 구분해야 할 땐 객체(object)

2. 무작위 숫자 4개 뽑기

📍 for 문


const answer = [];
for (let i = 0; i < 4; i++){
  const index = Math.floor(Math.random()*  9);
  answer.push(numbers[index]);
  numbers.splice(index, 1);
}

📍 while문

i = 0;
while (i < 4){
  const index = Math.floor(Math.random() * 9);
  answer.push(numbers[index]);
  numbers.splice(index, 1);
  i++;
}

🚨 문제 발생

const index = Math.floor(Math.random() * 9);

numbers[index]push 하고 numbers 에서 해당 배열 요소를 삭제하더라도 랜덤 숫자의 배열은 줄어 들지 않기 때문에 undefined 가 반환되는 문제가 발생된다.

💡 문제 해결

  const index = Math.floor(Math.random() * numbers.length);

numbers.length 를 하게 되면 numbers 의 배열 요소가 하나씩 삭제 되어 적용되므로, 추후 numbers 의 배열 개수를 바꾸더라도 코드를 일일이 고치지 않아도 된다.


🔗 배열 메서드 splice() 복습하러 가기


0개의 댓글