본문 바로가기
알고리즘

자바스크립트 랜덤숫자 뽑기(중복 제거)

by junvely 2023. 4. 4.

1. 배열에 중복여부를 확인한 후, 원하는 갯수만큼 랜덤숫자 삽입

  function randomArray() {
    const array = [];

    while (array.length < 3) {
      const random = Math.trunc(Math.random() * 10);

      if (!array.includes(random)) { //중복이 없을경우
        array.push(random);
      }
    }
    return array.join("")
  }

 

2. Set객체를 이용해(중복 제거) 랜덤숫자 삽입 후, 스프레드 연산자로 배열로 변경

  function randomArray() {
    let array = new Set();

    while (array.size < 3) {
      array.add(Math.trunc(Math.random() * 10));
    }

    return [...array].join("");
  }

 

 

3. 야구게임(랜덤 숫자 맞추기)

컴퓨터가 숫자를 생성하였습니다. 답을 맞춰보세요!
1번째 시도 : 134
0B0S
2번째 시도 : 238
1B1S
3번째 시도 : 820
2B1S
4번째 시도 : 028
3B
5번째 시도 : 280
3S
4번만에 맞히셨습니다. 
게임을 종료합니다.

답안)

 const input = document.querySelector(".input");
  const button = document.querySelector(".submit");

  function randomArray() {
    let array = new Set();

    while (array.size < 3) {
      array.add(Math.trunc(Math.random() * 10));
    }

    return [...array];
  }

  let count = 1;
  const random = randomArray();

  function baseball(myNum) {
    const myNumArray = myNum.split("");
    let s = 0;
    let b = 0;

    for (let i = 0; i < random.length; i++) {
      if (random[i] == myNumArray[i]) {
        s++;
      } else if (random.includes(parseInt(myNumArray[i]))) {
        b++;
      }
    }

    if (s === 3) {
      console.log(`${count}번만에 맞히셨습니다.\n게임을 종료합니다.`);
      alert(`${count}번만에 맞히셨습니다.\n게임을 종료합니다.`);
    }

    console.log(`${count}번째 시도 : ${myNum}\n${b}B${s}S`);

    count++;
  }

  button.addEventListener("click", () => {
    let num = input.value;
    baseball(num);
    input.value = "";
  });