티스토리 뷰
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 = "";
});728x90
'알고리즘' 카테고리의 다른 글
| 자료구조 - 스택(Stack)과 큐(Queue) (0) | 2023.08.03 |
|---|---|
| 자료구조 - 해시 테이블(hash table)이란 무엇인가? (0) | 2023.08.02 |
| 프로그래머스 Lv0 알고리즘 풀이 (0) | 2023.02.21 |
| [알고리즘] 자바스크립트 배열 함수, 내장 함수 등 모음 (0) | 2023.02.20 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 드림코딩
- 깃허브
- 미니 프로젝트
- github
- 항해 프로젝트
- 항해99
- URL
- Flask
- 서버
- 깃헙
- 깃 협업
- 중첩 라우팅
- MongoDB
- 깃사용법
- useState와 useRef 차이
- 리액트 라우터
- 타입스크립트
- 리액트 페이지네이션
- flask 서버
- require와 import 차이
- 리액트
- http란 무엇인가
- import
- 깃
- 호이스팅
- 자바스크립트
- git
- Python
- Til
- 항해
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 |
글 보관함