Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[로또] 정남진 미션 제출합니다. #176

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
8c097e3
docs: README 작성
ErroredPasta Nov 4, 2023
7f85026
feat: 유저에게 로또를 구매할 금액을 입력받는 기능
ErroredPasta Nov 5, 2023
f8d8879
test: Money 생성 테스트 작성
ErroredPasta Nov 5, 2023
76b8d87
docs: README의 기능 부분 수정
ErroredPasta Nov 8, 2023
ce823fe
feat: (입력 받은 금액 / 1000)만큼 로또를 생성하여 출력
ErroredPasta Nov 8, 2023
150f756
refactor: UI의 View와 Presenter 리팩토링
ErroredPasta Nov 8, 2023
58c2884
test: LottoRepository 테스트 작성
ErroredPasta Nov 5, 2023
ad0073e
fix: 로또 번호가 6개 아닐 경우의 예외 메시지 오타 수정
ErroredPasta Nov 5, 2023
79e89d3
feat: 당첨 번호를 입력 받는 기능
ErroredPasta Nov 5, 2023
8fe0801
test: WinningNumbers 생성 테스트
ErroredPasta Nov 8, 2023
08c4c44
test: Lotto 생성 테스트 추가
ErroredPasta Nov 8, 2023
6ffa698
feat: 보너스 숫자를 입력받는 기능
ErroredPasta Nov 8, 2023
d964b63
fix: 숫자를 입력해야할 때 숫자를 입력 하지 않을 경우 올바른 예외 메시지가 뜨도록 수정
ErroredPasta Nov 8, 2023
9987beb
fix: BonusNumber 생성시 올바르지 않은 범위의 숫자가 주어질 경우 예외 메시지의 오타 수정
ErroredPasta Nov 8, 2023
1d0e772
feat: 생성한 로또와 입력받은 당첨 번호와 보너스 번호를 이용하여 결과를 계산
ErroredPasta Nov 8, 2023
0661c0a
test: Lotto가 당첨 번호와 보너스 번호가 주어졌을 때 결과를 정확히 계산하는지 테스트
ErroredPasta Nov 8, 2023
7383ed0
feat: 수익률 계산 기능
ErroredPasta Nov 8, 2023
0c1b37a
refactor: LottoView의 getBonusNumberDone을 일관성 있게 onGetBonusNumberDone로 수정
ErroredPasta Nov 8, 2023
b7290dc
fix: NoSuchElementException을 처리하지 않도록 수정
ErroredPasta Nov 8, 2023
e62e3a4
refactor: Result에 values가 아니라 entries를 사용하도록 변경
ErroredPasta Nov 8, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 로또

## 프로젝트 개요

이 프로젝트는 사용자로 부터 금액을 입력 받아서 가상으로 로또를 무작위로 생성, 사용자가 당첨 번호와 보너스 번호를 입력하여 당첨 결과와 수익률을 계산하는 프로그램입니다.

## 기능

1. **금액 입력** : 사용자가 로또를 구매에 사용할 금액을 입력합니다.
- 금액이 1000원으로 나누어 떨어지도록 입력해야 합니다.
- 금액으로 숫자를 입력해야 합니다.
2. **무작위 로또 생성** : (사용자가 입력한 금액 / 1000)만큼의 로또를 무작위 번호로 생성하여 오름차순으로 출력합니다.
- 생성할 때 정렬된 리스트로 생성합니다.
3. **당첨 번호 입력** : 사용자가 당첨 번호를 입력합니다.
- 입력으로 숫자를 입력해야 합니다.
- 숫자들은 ,로 구분됩니다.
- 숫자를 6개 입력해야 합니다.
- 숫자들은 1 ~ 45 사이의 값이어야 합니다.
- 숫자들중 중복이 존재하지 않아야 합니다.
4. **보너스 번호 입력** : 사용자가 보너스 번호를 입력합니다.
- 입력으로 숫자를 입력해야 합니다.
- 숫자가 1 ~ 45 사이의 값이어야 합니다.
- 숫자가 당첨 번호와 중복이 되면 안됩니다.
5. **당첨 통계 계산** : 생성된 로또 번호와 사용자가 입력한 당첨 번호와 보너스 번호를 이용하여 당첨 통계를 계산하고 출력합니다.
6. **수익률 계산** : 사용자가 입력한 금액과 당첨 통계를 이용하여 수익률을 계산하여 출력합니다.

## 사용 방법

애플리케이션을 실행한 후, 화면의 지시에 따라 금액 및 당첨 번호, 보너스 번호를 입력합니다.
11 changes: 10 additions & 1 deletion src/main/kotlin/lotto/Application.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
package lotto

import camp.nextstep.edu.missionutils.Randoms
import lotto.data.repository.LottoRepositoryImpl
import lotto.ui.presenter.LottoPresenter
import lotto.ui.view.ConsoleLottoView

fun main() {
TODO("프로그램 구현")
val view = ConsoleLottoView()
val repository = LottoRepositoryImpl(randomNumberDataSource = Randoms::pickUniqueNumbersInRange)
val presenter = LottoPresenter(view = view, repository = repository)

LottoSimulator(view = view, presenter = presenter).start()
}
9 changes: 0 additions & 9 deletions src/main/kotlin/lotto/Lotto.kt

This file was deleted.

20 changes: 20 additions & 0 deletions src/main/kotlin/lotto/LottoSimulator.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package lotto

import lotto.ui.presenter.LottoPresenter
import lotto.ui.view.LottoView

class LottoSimulator(
private val view: LottoView,
private val presenter: LottoPresenter
) {
fun start() {
view.bindPresenter(presenter = presenter)

view.onStart()
view.onGetMoneyDone()
view.onGetLottoesDone()
view.onGetWinningNumbersDone()
view.onGetBonusNumberDone()
view.onGetResultsDone()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package lotto.data.datasource

fun interface RandomNumberDataSource {
fun pickUniqueNumbersInRange(startInclusive: Int, endInclusive: Int, count: Int): List<Int>
}
24 changes: 24 additions & 0 deletions src/main/kotlin/lotto/data/repository/LottoRepositoryImpl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package lotto.data.repository

import lotto.data.datasource.RandomNumberDataSource
import lotto.domain.model.Lotto
import lotto.domain.repository.LottoRepository

class LottoRepositoryImpl(
private val randomNumberDataSource: RandomNumberDataSource
) : LottoRepository {
override fun getLottoes(amount: Int): List<Lotto> {
val lottoes = mutableListOf<Lotto>()
repeat(amount) {
val numbers = randomNumberDataSource.pickUniqueNumbersInRange(
Lotto.MIN_NUMBER,
Lotto.MAX_NUMBER,
Lotto.NUMBER_OF_LOTTO_NUMBERS
).sortedBy { it }

lottoes.add(Lotto(numbers = numbers))
}

return lottoes
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package lotto.domain.exception

class DuplicatedNumberExistException(message: String) : RuntimeException(message)
13 changes: 13 additions & 0 deletions src/main/kotlin/lotto/domain/model/BonusNumber.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package lotto.domain.model

@JvmInline
value class BonusNumber(val number: Int) {
init {
require(number in Lotto.validRange) { NUMBER_NOT_IN_VALID_RANGE_MESSAGE }
}

companion object {
const val NUMBER_NOT_IN_VALID_RANGE_MESSAGE = "숫자가 ${Lotto.MIN_NUMBER}~${Lotto.MAX_NUMBER} 사이에 존재해야 합니다."
const val NUMBER_EXISTS_IN_WINNING_NUMBERS = "이미 숫자가 당첨 번호에 존재합니다."
}
}
51 changes: 51 additions & 0 deletions src/main/kotlin/lotto/domain/model/Lotto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package lotto.domain.model

import lotto.domain.model.Result.*

class Lotto(private val numbers: List<Int>) {
init {
require(numbers.size == NUMBER_OF_LOTTO_NUMBERS) { MISMATCH_NUMBER_OF_LOTTO_NUMBERS_MESSAGE }
require(!numbers.containsDuplicatedNumber()) { DUPLICATED_NUMBER_EXIST_MESSAGE }
require(numbers.inValidRange()) { NUMBERS_NOT_IN_VALID_RANGE }
require(numbers.inAscendingOrder()) { NUMBERS_NOT_IN_ASCENDING_ORDER }
}

private fun List<Int>.containsDuplicatedNumber(): Boolean = this.toSet().size != this.size

private fun List<Int>.inValidRange(): Boolean {
this.forEach { if (it !in validRange) return false }
return true
}

private fun List<Int>.inAscendingOrder(): Boolean = this == this.sortedBy { it }

override fun toString(): String = numbers.toString()

fun calculateResult(winningNumbers: WinningNumbers, bonusNumber: BonusNumber): Result {
val sizeOfNumbersInCommon = numbers.intersect(winningNumbers.numbers.toSet()).size

return when (sizeOfNumbersInCommon) {
FIRST_PLACE.matchingNumberCount -> FIRST_PLACE
SECOND_PLACE.matchingNumberCount -> decideSecondOrThirdPlace(bonusNumber = bonusNumber)
FOURTH_PLACE.matchingNumberCount -> FOURTH_PLACE
FIFTH_PLACE.matchingNumberCount -> FIFTH_PLACE
else -> NOTHING
}
}

private fun decideSecondOrThirdPlace(bonusNumber: BonusNumber): Result {
if (bonusNumber.number in numbers) return SECOND_PLACE
return THIRD_PLACE
}

companion object {
const val MIN_NUMBER = 1
const val MAX_NUMBER = 45
val validRange = (MIN_NUMBER..MAX_NUMBER)
const val NUMBER_OF_LOTTO_NUMBERS = 6
const val MISMATCH_NUMBER_OF_LOTTO_NUMBERS_MESSAGE = "${NUMBER_OF_LOTTO_NUMBERS}개의 숫자가 필요합니다."
const val DUPLICATED_NUMBER_EXIST_MESSAGE = "중복된 숫자가 존재합니다."
const val NUMBERS_NOT_IN_VALID_RANGE = "모든 숫자는 반드시 $MIN_NUMBER~$MAX_NUMBER 사이에 존재해야 합니다."
Comment on lines +46 to +48
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

상수들을 정말 잘 사용하신 거 같아요. 최소 값이나 최대 값들이 바뀐다면 유지 보수하기도 편해보이네요!

const val NUMBERS_NOT_IN_ASCENDING_ORDER = "로또 번호가 오름차순이 되도록 해주세요."
}
}
16 changes: 16 additions & 0 deletions src/main/kotlin/lotto/domain/model/Money.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package lotto.domain.model

@JvmInline
value class Money(val amount: Int) {
init {
require(amount >= MIN_MONEY_AMOUNT) { MUST_GREATER_THAN_MIN_MONEY_MESSAGE }
require(amount % DIVISION_AMOUNT == 0) { MUST_BE_DIVIDABLE_BY_DIVISION_AMOUNT_MESSAGE }
}

companion object {
const val MIN_MONEY_AMOUNT = 1_000
const val DIVISION_AMOUNT = 1_000
const val MUST_GREATER_THAN_MIN_MONEY_MESSAGE = "${MIN_MONEY_AMOUNT}원 이상의 금액을 입력해주세요."
const val MUST_BE_DIVIDABLE_BY_DIVISION_AMOUNT_MESSAGE = "금액이 ${DIVISION_AMOUNT}원으로 나누어 져야 합니다."
}
}
10 changes: 10 additions & 0 deletions src/main/kotlin/lotto/domain/model/Result.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package lotto.domain.model

enum class Result(val matchingNumberCount: Int, val prize: Int) {
FIRST_PLACE(matchingNumberCount = 6, prize = 2_000_000_000),
SECOND_PLACE(matchingNumberCount = 5, prize = 30_000_000),
THIRD_PLACE(matchingNumberCount = 5, prize = 1_500_000),
FOURTH_PLACE(matchingNumberCount = 4, prize = 50_000),
FIFTH_PLACE(matchingNumberCount = 3, prize = 5_000),
NOTHING(matchingNumberCount = 2, prize = 0)
}
25 changes: 25 additions & 0 deletions src/main/kotlin/lotto/domain/model/WinningNumbers.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package lotto.domain.model

@JvmInline
value class WinningNumbers(val numbers: List<Int>) {
init {
require(numbers.size == NUMBER_OF_WINNING_NUMBERS) { MISMATCH_NUMBER_OF_WINNING_NUMBERS }
require(!numbers.containsDuplicatedNumber()) { DUPLICATED_NUMBER_EXIST_EXCEPTION_MESSAGE }
require(numbers.inValidRange()) { Lotto.NUMBERS_NOT_IN_VALID_RANGE }
}

private fun List<Int>.containsDuplicatedNumber(): Boolean = this.toSet().size != this.size

private fun List<Int>.inValidRange(): Boolean {
this.forEach { if (it !in Lotto.validRange) return false }
return true
}

operator fun contains(number: Int): Boolean = numbers.contains(number)

companion object {
const val NUMBER_OF_WINNING_NUMBERS = Lotto.NUMBER_OF_LOTTO_NUMBERS
const val MISMATCH_NUMBER_OF_WINNING_NUMBERS = "${NUMBER_OF_WINNING_NUMBERS}개의 숫자가 필요합니다."
const val DUPLICATED_NUMBER_EXIST_EXCEPTION_MESSAGE = "중복된 숫자가 존재합니다."
}
}
7 changes: 7 additions & 0 deletions src/main/kotlin/lotto/domain/repository/LottoRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package lotto.domain.repository

import lotto.domain.model.Lotto

interface LottoRepository {
fun getLottoes(amount: Int): List<Lotto>
}
111 changes: 111 additions & 0 deletions src/main/kotlin/lotto/ui/presenter/LottoPresenter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package lotto.ui.presenter

import lotto.domain.model.*
import lotto.domain.repository.LottoRepository
import lotto.ui.view.LottoView

class LottoPresenter(
private val view: LottoView,
private val repository: LottoRepository
) {
// inline class는 lateinit var 불가
private var _money: Money? = null
private val money get() = requireNotNull(_money)

private lateinit var lottoes: List<Lotto>

private var _winningNumbers: WinningNumbers? = null
private val winningNumbers get() = requireNotNull(_winningNumbers)

private var _bonusNumber: BonusNumber? = null
private val bonusNumber get() = requireNotNull(_bonusNumber)

private lateinit var results: Map<Result, Int>

fun getMoney() {
view.displayMessage(ENTER_MONEY_MESSAGE)

runCatching {
view.getMoney()
}.onSuccess {
_money = it
}.onFailureOtherThanNoSuchElementException { error ->
view.displayErrorMessage(message = error.message)
getMoney()
Comment on lines +28 to +34
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 이런 방법도 있네요. 이런 코드들을 발견할 때마다 리뷰를 하길 잘했다는 생각이 들어요! 배움 주셔서 감사합니다!

}
}

fun getLottoes() {
val numberOfBoughtLottoes = money.amount / Money.DIVISION_AMOUNT
view.displayMessage("\n$numberOfBoughtLottoes$NUMBER_OF_BOUGHT_LOTTOES_MESSAGE")

lottoes = repository.getLottoes(amount = money.amount / Money.DIVISION_AMOUNT)
lottoes.forEach { view.displayMessage(it.toString()) }
}

fun getWinningNumbers() {
view.displayMessage("\n$ENTER_WINNING_NUMBERS_MESSAGE")

runCatching {
view.getWinningNumbers()
}.onSuccess {
_winningNumbers = it
}.onFailureOtherThanNoSuchElementException { error ->
view.displayErrorMessage(message = error.message)
getWinningNumbers()
}
}

fun getBonusNumber() {
view.displayMessage("\n$ENTER_BONUS_NUMBER_MESSAGE")

runCatching {
view.getBonusNumber().also {
require(it.number !in winningNumbers) { BonusNumber.NUMBER_EXISTS_IN_WINNING_NUMBERS }
}
}.onSuccess {
_bonusNumber = it
}.onFailureOtherThanNoSuchElementException { error ->
view.displayErrorMessage(message = error.message)
getBonusNumber()
}
}

fun getResults() {
results = lottoes.map {
it.calculateResult(winningNumbers = winningNumbers, bonusNumber = bonusNumber)
}.groupingBy { result ->
result
}.eachCount()

view.displayResults(results = results)
}

fun getProfit() {
var totalPrize = 0.0f

results.forEach { (result, count) ->
totalPrize += result.prize * count
}

val profit = (totalPrize / money.amount) * PERCENT

view.displayMessage(PROFIT_FORMAT.format(profit))
}

// NoSuchElementException은 테스트에 사용되므로 처리하지 않는다.
private fun <T> kotlin.Result<T>.onFailureOtherThanNoSuchElementException(action: (Throwable) -> Unit) =
onFailure { error ->
if (error is NoSuchElementException) throw error
action(error)
}

companion object {
const val ENTER_MONEY_MESSAGE = "구입금액을 입력해 주세요."
const val NUMBER_OF_BOUGHT_LOTTOES_MESSAGE = "개를 구매했습니다."
const val ENTER_WINNING_NUMBERS_MESSAGE = "당첨 번호를 입력해 주세요."
const val ENTER_BONUS_NUMBER_MESSAGE = "보너스 번호를 입력해 주세요."
const val PERCENT = 100
const val PROFIT_FORMAT = "총 수익률은 %.1f%%입니다."
}
}
Loading