diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..1c6ccc3 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,21 @@ +## 자동차 이름 입력받기 + +- 자동차 이름을 입력받는다. +- 이름이 하나일 경우를 처리한다. +- 입력은 쉼표로 구분한다. 쉼표와 문자가 아닌 다른 기호가 들어오면 예외 처리한다. +- 6자 이상의 이름은 예외 처리한다. + +## 시도 횟수 입력받기 + +- 시도할 횟수를 입력받는다. + +## 라운드 시작, 자동차 주행 + +- 시도할 횟수만큼 라운드 (랜던 연산을 모든 자동차에게 수행하는 작업) 를 시작한다. +- 0부터 9까지 각각의 자동차별로 랜덤 연산을 수행하고, 무작위 값이 4 이상일 때 race 배열에서 해당 인덱스의 요소값을 올린다. +- 요소값을 올리면서 최대값도 저장하여 최대값을 구할 수 있도록 한다. + +## 라운드 종료 + +- 모든 연산을 실행하고 난 뒤, carStatus 배열에서 인덱스 별 값을 확인해 출력할 수 있게 한다. +- 또한 구한 최대값을 통해 공동 우승자 또는 단독 우승자를 찾아 출력할 수 있도록 한다. diff --git a/src/App.js b/src/App.js index c38b30d..ec180fe 100644 --- a/src/App.js +++ b/src/App.js @@ -1,5 +1,69 @@ +import { Console } from "@woowacourse/mission-utils"; +import { MissionUtils } from "@woowacourse/mission-utils"; + +class InputError extends Error { + constructor(message) { + super(message); + this.name = "[ERROR]"; + } +} + class App { - async play() {} + async play() { + const names = await this.getCarname(); + const times = await this.getTimes(); + const race = Array(names.length).fill(0); + let max = 0; + + Console.print("\n실행 결과"); + + for (let i = 0; i < times; i++) { + names.forEach((name, index, array) => { + race[index] = + MissionUtils.Random.pickNumberInRange(0, 9) >= 4 + ? race[index] + 1 + : race[index]; + max = race[index] > max ? race[index] : max; + Console.print(`${name} : ${"-".repeat(race[index])}`); + }); + Console.print(""); + } + + Console.print( + `최종 우승자 : ${names + .filter((name) => race[names.indexOf(name)] >= max) + .join(", ")}` + ); + } + async getCarname() { + try { + const input = await Console.readLineAsync( + "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)\n" + ); + const names = Array.from(input.split(",").map((name) => name.trim())); + if (names.length < 2) { + throw new InputError( + "이름을 올바르게 입력해 주세요. (쉼표로 구분, 2개 이상의 이름)\n" + ); + } + return names; + } catch (error) { + throw error; + } + } + + async getTimes() { + try { + const input = await Console.readLineAsync("시도할 횟수는 몇 회인가요?\n"); + const times = parseInt(input); + if (isNaN(input)) { + throw new InputError("[ERROR] 숫자가 잘못된 형식입니다."); + } + return times; + } catch (error) { + throw error; + } + } } export default App;