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

[장희직] - 괄호 회전하기, 후위 표기식, 사과나무, 캐슬 디펜스 #273

Merged
merged 1 commit into from
Jun 2, 2024
Merged
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
40 changes: 40 additions & 0 deletions src/main/kotlin/heejik/65week/괄호 회전하기.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package heejik.`65week`

private class `괄호 회전하기` {
private val open = listOf('[', '(', '{')
private val close = listOf(']', ')', '}')
Comment on lines +4 to +5
Copy link
Member

Choose a reason for hiding this comment

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

닫는 괄호도 미리 만들어두시니 아래에서 코드가 깔끔하고 가독성이 좋아지네요!


fun solution(_s: String): Int {
var answer = 0
var s = _s
for (i in s.indices) {
s.run {
if (check(this)) answer += 1
s = leftRotate(s)
}
}

return answer
}

private fun leftRotate(s: String): String {
return s.substring(1) + s.first()
}

private fun check(s: String): Boolean {
val stack = StringBuilder()

s.forEach { c ->
if (c in open) {
stack.append(c)
} else {
if (close.indexOf(c) == open.indexOf(stack.lastOrNull())) {
Copy link
Member

Choose a reason for hiding this comment

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

요기 혹시 스택이 비었을 때 안터지나요???

Copy link
Member

Choose a reason for hiding this comment

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

아 널이면 값 비교에서 그냥 false를 반환하겠군요

Copy link
Member Author

Choose a reason for hiding this comment

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

맞습니다~!!

stack.deleteAt(stack.length - 1)
} else {
return false
}
}
}
return stack.isEmpty()
}
}
37 changes: 37 additions & 0 deletions src/main/kotlin/heejik/65week/사과나무.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package heejik.`65week`

import java.io.BufferedReader
import java.io.InputStreamReader

private class 사과나무 {

fun solve() = with(BufferedReader(InputStreamReader(System.`in`))) {
val n = this.readLine().toInt()
val appleCounts = readLine().split(' ').map { it.toInt() } as MutableList
val appleSum = appleCounts.sum()
var count1 = 0
var count2 = 0

// 3 의 배수여야 짝수가 더 많이 남아도 커버가 가능하다.
if (appleSum % 3 != 0) {
println("NO")
return
}

// 2의 배수가 나머지 1보다 많아야 1을 커버 가능하다.
for (apple in appleCounts) {
count2 += apple / 2
count1 += apple % 2
Comment on lines +23 to +24
Copy link
Contributor

Choose a reason for hiding this comment

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

오 다시 생각해보니 3의 배수면 3으로 나눈 몫이 물을 주는 횟수가 되니까 홀수가 그 횟수를 초과하면 불가능한가봐요

}

if (count2 >= count1) {
println("YES")
} else {
println("NO")
}
}
}

fun main() {
사과나무().solve()
}
118 changes: 118 additions & 0 deletions src/main/kotlin/heejik/65week/캐슬 디펜스.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package heejik.`65week`

import java.util.PriorityQueue
import kotlin.math.*

private class `캐슬 디펜스` {

data class Pos(
var x: Int,
var y: Int
)

var n = 0
var m = 0
var d = 0
var maxDeadEnemyCount = 0
var archerPosition = listOf<Pos>()
val enemyPosition = mutableListOf<Pos>()
val localEnemyPosition = mutableListOf<Pos>()

fun solve() {
readln().split(' ').map { it.toInt() }.run {
n = this[0]
m = this[1]
d = this[2]
}
repeat(n) { x ->
readln().split(' ').map { it.toInt() }.forEachIndexed { y, i ->
if (i == 1) {
enemyPosition.add(Pos(x = x, y = y))
}
}
}
setArcherPosition(startGame = ::startGame)

println(maxDeadEnemyCount)
}

private fun setArcherPosition(
startGame: () -> Unit,
start: Int = 0,
setArchers: List<Int> = emptyList()
) {
if (setArchers.size == 3) {
archerPosition = setArchers.map { Pos(n, it) }
// 적의 위치 초기화
for (enemy in enemyPosition) {
localEnemyPosition.add(enemy)
}
while (isEndGame().not()) {
startGame()
}
return
}
for (i in start until m) {
setArcherPosition(
startGame = startGame,
start = i + 1,
setArchers = setArchers + i
)
}
}

private fun startGame() {
var deadEnemyCount = 0
while (isEndGame().not()) {
val targets = mutableSetOf<Pos>()
archerPosition.forEach { pos ->
targets.add(getTarget(archer = pos) ?: return@forEach)
}
targets.forEach { targetPos ->
shootTarget(targetPos).also {
deadEnemyCount += 1
}
}
advanceEnemies()
}
maxDeadEnemyCount = max(maxDeadEnemyCount, deadEnemyCount)
}

private fun isEndGame() = localEnemyPosition.isEmpty()


private fun getTarget(archer: Pos): Pos? {
val pq = PriorityQueue<Pair<Int, Pos>> { e1, e2 ->
if (e1.first != e2.first) {
e1.first - e2.first
} else {
e1.second.y - e2.second.y
}
}

localEnemyPosition.forEach { pos ->
val distance = abs(archer.x - pos.x) + abs(archer.y - pos.y)
if (distance <= d) {
pq.add(distance to pos)
}
}

return pq.peek()?.second
}

private fun shootTarget(target: Pos): Boolean {
return localEnemyPosition.remove(target)
}

private fun advanceEnemies() {
for ((idx, pos) in localEnemyPosition.withIndex()) {
localEnemyPosition[idx] = pos.copy(x = pos.x + 1)
}

localEnemyPosition.removeIf { it.x == n }
}
}

fun main() {
`캐슬 디펜스`().solve()
}
55 changes: 55 additions & 0 deletions src/main/kotlin/heejik/65week/후위 표기식.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package heejik.`65week`

private class `후위 표기식` {

val stack = mutableListOf<String>()
val sb = StringBuilder()

fun solve() {
val expression = readln().toList().map { it.toString() }
Copy link
Member

Choose a reason for hiding this comment

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

저는 chunked사용했었는데 toList로도 할 수 있군요

Copy link
Member Author

Choose a reason for hiding this comment

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

ㅎㅎ 그렇슴다!!
image

expression.forEach {
if (it !in "+-*/()") {
Copy link
Contributor

Choose a reason for hiding this comment

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

헐 그냥 스트링으로 해도 in 연산이 되는군요;;

Copy link
Member

Choose a reason for hiding this comment

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

문자열에서 in 으로 한 번에 처리하긴게 엄청 깔끔하고 좋네요!

sb.append(it)
return@forEach
}
if (it == "(") {
stack.add(it)
return@forEach
}
if (it == ")") {
while (true) {
val last = stack.removeLast()
if (last == "(") {
Copy link
Contributor

Choose a reason for hiding this comment

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

항상 올바른 식만 주어져서 반드시 (가 있군요..

break
} else {
sb.append(last)
}
}
}
if (it in "*/") {
if (stack.isNotEmpty() && stack.last() in "*/") {
sb.append(stack.removeLast())
}
stack.add(it)
return@forEach
}
Comment on lines +29 to +35
Copy link
Member

Choose a reason for hiding this comment

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

멋지네요!!!

if (it in "+-") {
while (true) {
if (stack.isEmpty() || stack.last() == "(") {
break
}
sb.append(stack.removeLast())
}
stack.add(it)
}
}
while (stack.isNotEmpty()) {
sb.append(stack.removeLast())
}
println(sb.toString())
}
}

fun main() {
`후위 표기식`().solve()
}