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

Step1 #1779

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Step1 #1779

Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions src/main/kotlin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
## 🚀 2단계 - 문자열 계산기
- [ ] 사용자가 입력한 문자열 값에 따라 사칙 연산을 수행할 수 있는 계산기를 구현해야 한다.
- [ ] 문자열 계산기는 사칙 연산의 계산 우선순위가 아닌 입력 값에 따라 계산 순서가 결정된다.
- [ ] 즉, 수학에서는 곱셈, 나눗셈이 덧셈, 뺄셈 보다 먼저 계산해야 하지만 이를 무시한다.
- [ ] 예를 들어 "2 + 3 * 4 / 2"와 같은 문자열을 입력할 경우 2 + 3 * 4 / 2 실행 결과인 10을 출력해야 한다.
- [ ] 덧셈
- [ ] 뺄셈
- [ ] 곱셈
- [ ] 나눗셈
- [ ] 입력값이 null이거나 빈 공백 문자일 경우 IllegalArgumentE ception throw
- [ ] 사칙연산 기호가 아닌 경우 IllegalArgumentE ception throw
- [ ] 사칙 연산을 모두 포함하는 기능 구현
- [ ] 공백 문자열을 빈 공백 문자로 분리하려면 String 클래스의 split(" ") 메소드를 활용한다.
- [ ] 반복적인 패턴을 찾아 반복문으로 구현한다.
- [ ] Parameterized Tests 활용
- [ ] 연산자 먼저 시작되는 엣지 케이스
- [ ] 연산자와 숫자의 개수가 올바르지 않은 케이스
45 changes: 45 additions & 0 deletions src/main/kotlin/calc/Calculator.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package calc

class Calculator(
private val input: String
) {
init {
require(
input.split(" ").withIndex()
.all { (idx, value) ->
if (idx % 2 == 0) value.isNumber() else value.isOperator()
}
) { "형식 지켜랴 ㅋ" }
}

fun calc(): Int {
val elements = input.split(" ")
.filterNot { it.isBlank() }
.groupBy { it.isNumber() }

val expressions = elements[false] ?: emptyList()
val numbers = (elements[true] ?: emptyList())
.map { it.toInt() }
.toCollection(ArrayDeque())

for (expr in expressions) {
val operand1 = numbers.removeFirst()
val operand2 = numbers.removeFirst()

val result = when (expr) {
"+" -> operand1 + operand2
"-" -> operand1 - operand2
"*" -> operand1 * operand2
"/" -> operand1 / operand2
else -> throw IllegalArgumentException()
}

numbers.addFirst(result)
}

return numbers.last()
}
}

private fun String.isNumber() = toIntOrNull() != null
private fun String.isOperator() = this in setOf("+", "-", "*", "/")
18 changes: 18 additions & 0 deletions src/test/kotlin/CalculatorTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import calc.Calculator
import io.kotest.assertions.throwables.shouldThrowWithMessage
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe

class CalculatorTest : StringSpec({
"계산 잘~ 해봐 " {
val result = Calculator("5 + 1 / 3").calc()
result shouldBe 2
}

"형식 지키는지 보자" {
shouldThrowWithMessage<IllegalArgumentException>("형식 지켜랴 ㅋ") {
Calculator("223 h d23")
}

}
})