Lotto번호 랜덤 추출 및 생성

swimming·2023년 3월 23일
0

💡I felt..

의사코드는 꽤 중요하다.
배열과 낯가림정도는 풀어진 듯함.
sort 오름차순 내림차순 이해완료.


pseudocode

  1. 로또 번호 저장할 배열 만들기
  2. 1~45 숫자 중 6개의 숫자 임의 선택 후 배열에 저장(단, 중복 값 없이)
    2-1. 랜덤한 1~45까지의 숫자를 배열에 넣기
    2-2. 그 중 뽑힌 6개만 담을 새로운 배열 생성
    2-3. 중복된 값 제거
  3. 오름차순 정렬
  4. 완성된 배열 데이터를 브라우저 화면에 출력
    4-1. CSS 적용 위한 class 부여
    4-2. CSS 적용
    4-3. 동일하게 숫자 6개만 출력하도록 반복문 내에 document.write() 입력!


HTML

<!DOCTYPE html>
<html lang="kor">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Making Lotto</title>

    <link rel="stylesheet" href="lotto_style.css" />
    <script src="Making_lotto copy.js"></script>

  </head>
  <body></body>
</html>

CSS

.ball{
    margin: 5px;
    background-color: burlywood;
    width: 100px; height: 100px;
    /* border: 1px solid black; */
    display: inline-block;
    border-radius: 50%;
    font-size: 2rem;
    text-align: center;
    line-height: 100px;
}
.ball:hover{
    background-color: rgb(211, 155, 81);
}

JS


let lotto = [];
for (let i = 1; i <= 45; i++) {
  lotto.push(i);
}

let result = [];
for (let i = 0; i < 6; i++) {
  let idx = Math.trunc(Math.random() * lotto.length);

  //랜덤으로 선택한 인덱스의 값
  let num = lotto[idx];

  //배열의 인덱스의 값 제거
  lotto.splice(idx, 1);

  result.push(num);
}

// function compare(a, b) {
//   return b - a;
// }
result.sort(function (a, b) {
  return a - b;
});

for (let i = 0; i < 6; i++) {
  document.write("<span class='ball'>" + result[i] + "</span>");
}

0개의 댓글