본문 바로가기

카테고리 없음

javascript) 로또 번호 추첨(난수 중복 방지)

 

  

 

 

 

    

 

*  난수 중복 여부 체크하기

 

<!DOCTYPE html>

<html lang="ko">

<head>

<meta charset="UTF-8">

<title>난수 발생(로또)</title>

</head>

 

<body>

<style>

body { color: black; font-size:15px; font-family: sans-serif; text-align: center; }

button {   color: black;  font-size:15px;   border-color: #777;   background-color: #eee; }

</style>

 

<br>

<input type=text id='idResult' length=15>

<button id='idPlay'>Pick</button>

 

<script>

  window.funPick= function() {

   let lottos = []; //[...Array(45).keys()].map(n => n + 1);

   winResult.value= '';

 

   for (let i= 0; i< 6; i++) {

    let nansu= Math.floor(Math.random() *45) +1;

    while(lottos.includes(nansu)) {

     nansu= Math.floor(Math.random() *45) +1;

    } //winResult.textContent=

    lottos[i]= nansu;

    winResult.value+= ` ${lottos[i]} `;

   }

 }

 

window.addEventListener('load', () => {

 this.btnPlay = document.getElementById("idPlay");

 this.winResult = document.getElementById("idResult");

 btnPlay.addEventListener('mouseup', funPick, false);

});

</script>

 

</body>

</html>

 

 

* 교환 방식으로 애초에 난수 중복을 방지

 

<!DOCTYPE html>

<html lang="ko">

<head>

<meta charset="UTF-8">

<title>난수 발생(로또)</title>

</head>

 

<body>

<style>

body { color: black;  font-size:15px;  font-family: sans-serif;  text-align: center; }

button {  color: black;  font-size:15px;  border-color: #777;  background-color: #eee; }

</style>

 

<br>

<input type=text id='idResult' length=15>

<button id='idPlay'>Pick</button>

 

<script>

const btnPlay = document.getElementById("idPlay");

const winResult = document.getElementById("idResult");

 

function funPick(){

 let lottos = [...Array(45).keys()].map(n => n + 1); // ai 참고

 winResult.value= '';

 

 for (let i= 0; i< 6; i++) {  //아래는 기존 선택된 번호와 중복 피하기 위해 랜덤 범위 조정

  const j = Math.floor(Math.random() * (lottos.length-i))+ i;

  [lottos[i], lottos[j]] = [lottos[j], lottos[i]]; //swap()

  winResult.value+= ` ${lottos[i]} `;

 }

}

 

btnPlay.addEventListener('mouseup', funPick, false);

</script>

 

</body>

</html>