JavaScript로 로또 추첨 번호 뽑기
- Math.random(), Math.floor(), indexOf(), sort() 활용-
수많은 방법이 존재 하겠고..
머리를 굴러 굴러 멍 때리며 어찌할지 모르는 상태로.. 직접 짜보니 토나오고
나중에 이해하고 나니 너무 허무하고..
자자 함께 짜보자구요.
시작. 단순히 생각하고 무식하게 짜보기
우선 로또 추첨 번호 뽑기 하려면 어떻게 해야할지를 천천히 적어본다.
1. 로또 번호는 1~45번까지
2. 랜덤으로 번호를 5개 뽑는다.
3. 2번에서 중복되는 애들은... 있음 어쩌지? 이에 대한 처리도 필요하다.
4. 다뽑음 5개 번호는 작은번호부터 큰번호로 정렬해서 보기 좋게 해준다.
....
그래 아는것 부터 천천히 만들어보자
여기까지 하면 num안에 1~45번까지 쭉 들어간게 나온다..
1. 로또 번호는 1~45번까지
랜덤으로 번호 5개 뽑기...
Math라는 아이가 있다.
Math.random() 이걸 활용하면된다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
(읽어보세요)
그래서
이를 활용,
Math.random() * 45 하면 0~44.##########
이렇게 나온다
So..
방법 1) parseInt써서 정수 처리 혹은 , 2)Math.floor(반내림) 해줘서 소수점 없이 정수 처리 되도록 한다.
근데... 0~44가 나오게 되므로 여기서 +1을 해준다.
즉,
Math.floor(Math.random() * 45) + 1
console에 마구마구 찍어줘본다..
1~45 잘 나오는거 확인..
근데 여기서 하나
Math.floor(Math.random() * nums.length) + 1
요렇게 45라고 하는거 대신 nums.length로 바꿔준다.
랜덤으로 1~45를 나오게 만들었으니 이제 5개의 번호를 저장하면 된다.
var myNums = []; // 여기에 랜덤 숫자 5개를 저장하려 한다.
이제 또 고민이 시작된다.
- for루프를 써서 5번 반복해서 넣자니 중복이 걸린다.
- 중복되는 숫자는 줄이고 5번만 for문을 돌리고 싶은데.. 어쩌지?
우선 5개 랜덤 번호 뽑기
콘솔에 찍어보면 5개 랜덤수가 나오긴 하는데 중복은 있다..
2. 랜덤으로 번호를 5개 뽑는다.
이럴 때 무릎을 탁 치게 해주는 indexOf()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
(읽어보세요)
Syntax
arr.indexOf(searchElement) arr.indexOf(searchElement, fromIndex)
Using indexOf()
The following example uses indexOf()
to locate values in an array.
1 2 3 4 5 6 | <code class= " language-js" style= "word-wrap: normal; margin: 0px; padding: 0px; border: 0px; font-weight: inherit; font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; text-shadow: none; direction: ltr; word-spacing: normal; word-break: normal; line-height: 1.5; tab-size: 4; hyphens: none; position: relative;" ><span class= "token keyword" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(0, 119, 170);" > var </span> array <span class= "token operator" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(166, 127, 89); background: rgba(255, 255, 255, 0.498039);" >=</span> <span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >[</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >2</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> <span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >9</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> <span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >9</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >]</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> array<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >.</span><span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >indexOf</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >2</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token comment" spellcheck= "true" style= "margin: 0px; padding: 0px; border: 0px; display: inherit; color: rgb(112, 128, 144);" > // 0</span> array<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >.</span><span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >indexOf</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >7</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token comment" spellcheck= "true" style= "margin: 0px; padding: 0px; border: 0px; display: inherit; color: rgb(112, 128, 144);" > // -1</span> array<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >.</span><span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >indexOf</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >9</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> <span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >2</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token comment" spellcheck= "true" style= "margin: 0px; padding: 0px; border: 0px; display: inherit; color: rgb(112, 128, 144);" > // 2</span> array<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >.</span><span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >indexOf</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >2</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> <span class= "token operator" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(166, 127, 89); background: rgba(255, 255, 255, 0.498039);" >-</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >1</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token comment" spellcheck= "true" style= "margin: 0px; padding: 0px; border: 0px; display: inherit; color: rgb(112, 128, 144);" > // -1</span> array<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >.</span><span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >indexOf</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >2</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> <span class= "token operator" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(166, 127, 89); background: rgba(255, 255, 255, 0.498039);" >-</span><span class= "token number" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 0, 85);" >3</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token comment" spellcheck= "true" style= "margin: 0px; padding: 0px; border: 0px; display: inherit; color: rgb(112, 128, 144);" > // 0</span></code> |
indexOf(여기에 찾고 싶은 엘리먼트) 하면 위와 같이
찾고자 하는 array 안에 엘리먼트가 있다면 인덱스 값을 알려준다.
그리고 찾고자 하는 엘리먼트가 어레이 안에 없으면 그때 -1을 반환해준다
바로 이아이가 완전 포인트
사실 아래 더보면 while문을 사용해 이를 해결 할 수도 있다.
허나.. 난 for문으로..
우와.. 정말 뭔가 실자락이 보인다.
for문을 돌려 랜덤으로 숫자를 뽑아 myNums에 넣을 때마다 중복된게 있음 넘어가면된다!
콘솔에 찍어보면 우와.. 중복이 사라졌다. 그런데 4개? 나오는 경우도 있네..
그렇다. 5번만 for문이 돌고 중복이 있을 경우 스킵하기때문에 요러하다.
그럼 5개 담고 끝내면 되겠네!
Wow
콘솔에 찍어보면 완벽해 완벽해 이제 끝이 보인다.
3. 2번에서 중복되는 애들은... 있음 어쩌지? 이에 대한 처리도 필요하다.
이제 정렬만 하면된다.
여기서 쓰이는 아이 sort()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
(읽어보세요)
To compare numbers instead of strings, the compare function can simply subtract b
from a
. The following function will sort the array ascending (if it doesn't contain Infinity
and NaN
):
1 2 3 | <code class= " language-js" style= "word-wrap: normal; margin: 0px; padding: 0px; border: 0px; font-weight: inherit; font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; text-shadow: none; direction: ltr; word-spacing: normal; word-break: normal; line-height: 1.5; tab-size: 4; hyphens: none; position: relative;" ><span class= "token keyword" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(0, 119, 170);" > function </span> <span class= "token function" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(221, 74, 104);" >compareNumbers</span><span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >(</span>a<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >,</span> b<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >)</span> <span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >{</span> <span class= "token keyword" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(0, 119, 170);" > return </span> a <span class= "token operator" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(166, 127, 89); background: rgba(255, 255, 255, 0.498039);" >-</span> b<span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >;</span> <span class= "token punctuation" style= "margin: 0px; padding: 0px; border: 0px; color: rgb(153, 153, 153);" >}</span></code> |
4. 다뽑음 5개 번호는 작은번호부터 큰번호로 정렬해서 보기 좋게 해준다.
YAY!
완성
뿌듯뿌듯하다.
여기서 사용된 아이들 최종 정리하자면
for문, if문
Math.random(), Math.floor(), indexOf(), sort()
다음엔 고급과정 splice를 사용해서 만들어 보기로.. 뿅
'JavaScript' 카테고리의 다른 글
JavaScript for문 사용해 구구단 나타내자 (0) | 2017.03.30 |
---|---|
이미지 토글 (0) | 2015.11.10 |
백그라운드 이미지 바꾸기 (0) | 2015.11.09 |
for문 (0) | 2015.11.06 |
자바스크립트로 CSS 변경하기 (0) | 2015.11.05 |