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

[Week3] 김재원: 킹, 크로스워드, 단풍잎 이야기, 랜선 자르기 #13

Merged
merged 6 commits into from
Nov 6, 2022

Conversation

ashwon12
Copy link
Member

Issue Number

Closed #12


💎 문제 해결


추가로 푼 문제

🔥 특이사항/질문

@ashwon12 ashwon12 self-assigned this Oct 17, 2022
Copy link
Member

@gongdongho12 gongdongho12 left a comment

Choose a reason for hiding this comment

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

윽 시간이 없어서 아직 두개밖에 못봤네요
나중에 다 보겠습니다 :)

src/3week/jaewon/과제.kt Show resolved Hide resolved
Comment on lines +17 to +27
for (i in maxDay downTo 1){
var temp = HOMEWORK(0,0)

work.filter { it.d >= i }.forEach {
if(temp.w < it.w){
temp = it
}
}
answer += temp.w
work.remove(temp)
}
Copy link
Member

Choose a reason for hiding this comment

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

answer 변수 전역변수로 빼지 않아도 되게 sumOf로 처리하면 어떠신가요?

val answer = (maxDay downTo 1).sumOf { i ->
    work.filter { it.d >= i }.maxByOrNull { it.w }?.let {
        work.remove(it)
        it.w
    }?: 0
}

Copy link
Member Author

@ashwon12 ashwon12 Oct 19, 2022

Choose a reason for hiding this comment

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

반복문을 저런식으로도 적용시킬 수가 있나요??!? wow..


import kotlin.math.max

data class HOMEWORK (val d : Int, val w : Int)
Copy link
Member

@gongdongho12 gongdongho12 Oct 18, 2022

Choose a reason for hiding this comment

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

주로 상수에만 전부 대문자 사용하더라구요(물론 정하기 나름이지만...) 클래스는 카멜케이스 + 첫글자 대문자 사용해주시면 좋을것 같아요

Copy link
Member Author

Choose a reason for hiding this comment

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

카멜케이스는 첫글자가 소문자 아닌가요!?!

Copy link
Member

@gongdongho12 gongdongho12 Oct 19, 2022

Choose a reason for hiding this comment

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

그래서 + 입니다 ㅠ 이걸 무슨케이스라고 하지... HomeWork 이런느낌

Copy link
Member Author

@ashwon12 ashwon12 Oct 19, 2022

Choose a reason for hiding this comment

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

파스칼이요!!~!!! 🤓

Comment on lines +20 to +24
work.filter { it.d >= i }.forEach {
if(temp.w < it.w){
temp = it
}
}
Copy link
Member

Choose a reason for hiding this comment

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

필터된 항목중에서 w가 가장 큰 homework를 가져오는 연산인것 같더라구요
이런 느낌은 어떠신가요?

work.filter { it.d >= i }.maxByOrNull { it.w }?.let {
    work.remove(it)
}

src/3week/jaewon/단풍잎 이야기.kt Show resolved Hide resolved
Comment on lines +44 to +76
val canSkill = mutableListOf<List<Int>>()
combination(canSkill,skills, Array<Boolean>(skills.size){false},0,n)
canSkill.forEach {com ->
var count = 0
quest.forEach { it ->
// 지금 퀘스트를 꺨 수 있는 지 확인.
val temp = it.count { com.contains(it) }
if (temp == it.size){ // 두개 다 통과
count++
}
}
if (count == quest.size){
println(quest.size)
exitProcess(0)
}else{
can = max(can,count)
}
}
}
println(can)
}

fun <T> combination(answer: MutableList<List<T>>, el: List<T>, ck: Array<Boolean>, start: Int, target: Int) {
if(target == 0) {
answer.addAll( listOf(el.filterIndexed { index, t -> ck[index] }) )
} else {
for(i in start until el.size) {
ck[i] = true
combination(answer, el, ck, i + 1, target - 1)
ck[i] = false
}
}
}
Copy link
Member

Choose a reason for hiding this comment

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

코틀린은 함수형이다 보니까 combination도 깔끔하게 사용할 수 있더라구요!
(자매품) permutation도 가능합니다!

fun <T> List<T>.combination(num: Int): List<List<T>> {
    if (num == 1) return map { listOf(it) }
    return indices.flatMap {
        val current = get(it)
        subList(it + 1, size).combination(num - 1).map { combination ->
            LinkedList(combination).apply {
                addFirst(current)
            }
        }
    }
}

그러면 사용부에 mutableList로 만든 canSkill을 아래와 같이 정의할 수 있어요

val canSkill = skills.combination(n)

Copy link
Member Author

Choose a reason for hiding this comment

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

헉 이부분 코드는 다시한번 보고 다음에 사용해야 할 때 사용해보아야겠어요.. !!

src/3week/jaewon/단풍잎 이야기.kt Show resolved Hide resolved
}
if (count == quest.size){
println(quest.size)
exitProcess(0)
Copy link
Member

Choose a reason for hiding this comment

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

그냥 canSkill의 forEach를 return 해도 되지 않나요? return@forEach
그러면 can만 quest.size로 업데이트하고 출력하게 되니까요!

Copy link
Member Author

Choose a reason for hiding this comment

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

음 바로 실행을 종료시키는게 좋다고 생각했는데 exitProcessimport 해야해서 이 방법을 추천해주시는건가요~?!

Copy link
Member

Choose a reason for hiding this comment

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

혹시 그냥 return 은 종료가 안되신건가요?
사실 이부분은 취향차인데
exitProcess로 종료된다는게 특별히 Intelij에서 강조되는것도 없는데 종료되는 로직이자나요 그래서 저는 되도록 한 함수에서의 종료는 기본적으로 맨 아래로 두는게 나은것 같아요

Comment on lines +44 to +61
val canSkill = mutableListOf<List<Int>>()
combination(canSkill,skills, Array<Boolean>(skills.size){false},0,n)
canSkill.forEach {com ->
var count = 0
quest.forEach { it ->
// 지금 퀘스트를 꺨 수 있는 지 확인.
val temp = it.count { com.contains(it) }
if (temp == it.size){ // 두개 다 통과
count++
}
}
if (count == quest.size){
println(quest.size)
exitProcess(0)
}else{
can = max(can,count)
}
}
Copy link
Member

Choose a reason for hiding this comment

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

정리하면 이런느낌이네요!

skills.combination(n).forEach { com ->
    val questCount = questBox.count { questList -> questList.count { q -> com.contains(q) } == questList.size }
    if (questCount == questBox.size) {
        can = questBox.size
        return@forEach
    } else {
        can = max(can, questCount)
    }
}

src/3week/jaewon/단풍잎 이야기.kt Show resolved Hide resolved
노력했으나 ... 안됐다...
Comment on lines +9 to +13
val size = IntArray(k)
repeat(k){ size[it] = readln().toInt()}

var answer : Long = 0
var high : Long = size.maxOf { it }+1.toLong()
Copy link
Member

Choose a reason for hiding this comment

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

size 만드는걸 아래같이 바꾸면 초기화 없이 가능할거구 아래에 보면
high값을 처리하는데 이부분을 위한 max값도 같이 만들면 좋을것 같아요

var max: Int = 0
val size = Array(k) {
    val v = readln().toInt()
    if (max < v) {
        max = v
    }
    v
}

Copy link
Member

Choose a reason for hiding this comment

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

그리고 코딩하다 보면 각각의 타입에 대한 정의를 추론하기 힘든 경우가 많은데
코틀린은 타입을 필수로 명시하지 않아도 되니까 그런 부분이 더 심하더라구요
size 보다는 sizeArray 형식이 좋지 않을까요?

Copy link
Member

@gongdongho12 gongdongho12 left a comment

Choose a reason for hiding this comment

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

리뷰끝!

Comment on lines +9 to +13
val size = IntArray(k)
repeat(k){ size[it] = readln().toInt()}

var answer : Long = 0
var high : Long = size.maxOf { it }+1.toLong()
Copy link
Member

Choose a reason for hiding this comment

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

그리고 코딩하다 보면 각각의 타입에 대한 정의를 추론하기 힘든 경우가 많은데
코틀린은 타입을 필수로 명시하지 않아도 되니까 그런 부분이 더 심하더라구요
size 보다는 sizeArray 형식이 좋지 않을까요?

Comment on lines +29 to +46
val fishPos = mapOf<Int, Pair<Int,Int>>(
0 to Pair(0,0),
1 to Pair(0,-1),
2 to Pair(-1,-1),
3 to Pair(-1,0),
4 to Pair(-1,1),
5 to Pair(0,1),
6 to Pair(1,1),
7 to Pair(1,0),
8 to Pair(1,-1)
)

val sharkPos = mapOf(
1 to Pair(-1,0),
3 to Pair(1,0),
2 to Pair(0,-1),
4 to Pair(0,1)
)
Copy link
Member

Choose a reason for hiding this comment

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

번호로 만들었을때 0으로 시작하는 경우엔 그냥 리스트 자료구조를 사용하는게 낫지 않으신가요?

Comment on lines +78 to +88
x += fishPos[arrow]!!.first
y += fishPos[arrow]!!.second
fishes[idx] = FISH(x,y,arrow)
}else if(!checkFish(x,y,arrow)){
// 이동할 수 없는 경우
var i = 0
while (i < 8){
arrow = if( arrow == 1) 8 else { arrow-1 } // 45도 반시계로 돌리기
if(checkFish(x,y,arrow)){
x += fishPos[arrow]!!.first
y += fishPos[arrow]!!.second
Copy link
Member

Choose a reason for hiding this comment

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

fishPos[arrow]!! 를 사용했는데 x, y를 가져오기 위해 다시 사용하고 있네요
이부분 사실 가장 좋은 방법은 fish 자체에 operator에 추가하면 사실 first와 second로 뺄 필요도 없게 되지 않을까요?

*
*/

data class FISH (val x : Int, val y : Int, val arrow : Int)
Copy link
Member

Choose a reason for hiding this comment

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

FISH => Fish로 선언하면 좋을것 같아요

data class Fish (var x : Int, var y : Int, val arrow : Int) {
    operator fun plus(pos: Pair<Int, Int>) {
        this.x += pos.first
        this.y += pos.second
    }
}

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.

그리고 Fish 자체에 있으면 좋은 함수로 check, validate, setZero 등이 있으면 용이할 것 같아요

data class Fish(var x: Int, var y: Int, var arrow: Int) {
    operator fun plus(pos: Pair<Int, Int>) {
        this.x += pos.first
        this.y += pos.second
    }
    
    fun validate(first: Int, second: Int): Boolean = this.x == first && this.y == second
    
    fun setZero() {
        this.x = 0
        this.y = 0
        this.arrow = 0
    }
    
    fun check(): Boolean {
        val (posX, posY) = fishPos[arrow]!!
        val newX = x + posX
        val newY = y + posY
        return !((newX == sharkX && newY == sharkY) || (smell.any { smell -> smell.x == newX && smell.y == newY }) || newX > 4 || newY > 4)
    }
}

*/

data class FISH (val x : Int, val y : Int, val arrow : Int)
data class SMELL (val x : Int, val y : Int, var time : Int)
Copy link
Member

Choose a reason for hiding this comment

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

SMELL => Smell

자주 Pair 형태로 더하는 경우가 있는데 이부분도

data class Smell(var x: Int, var y: Int, var time: Int) {
    operator fun plus(pos: Pair<Int, Int>) {
        this.x += pos.first
        this.y += pos.second
    }
}

추가되면 좋을것 같아요

var tKing = kingPos
var tRock = rockPos
for (i in move){
tKing = "${tKing[0]+(pos[i]!!.x)}"+"${tKing[1]+(pos[i]!!.y)}"
Copy link
Member

Choose a reason for hiding this comment

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

"${tKing[0]+(pos[i]!!.x)}"+"${tKing[1]+(pos[i]!!.y)}" 이미 문자열 포매팅 진행하고 추가로 + 연산 진행하는 것 보다는 한 문자열 안에 format 넣어서 "${tKing[0] + (pos[i]!!.x)}${tKing[1] + (pos[i]!!.y)}" 로 사용하면 좋을것 같아요

Copy link
Member

Choose a reason for hiding this comment

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

추가적으로 이부분도 두개나 사용하고 있으니까 확장함수로 해보면 더 좋을것 같아요

private fun String.addPos(pos: Pos) = "${get(0) + pos.x}${get(1) + pos.y}"

//킹이 밖으로 나가지 않았을 경우
if (tKing == rockPos){ // 킹이 움직이는 곳에 돌이 있는 경우
for (i in move){
tRock = "${tRock[0]+pos[i]!!.x}"+"${tRock[1]+pos[i]!!.y}"
Copy link
Member

Choose a reason for hiding this comment

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

동일

Comment on lines +31 to +37
if (tKing[0] in 'A'..'H' && tKing[1] in '1'..'8'){
//킹이 밖으로 나가지 않았을 경우
if (tKing == rockPos){ // 킹이 움직이는 곳에 돌이 있는 경우
for (i in move){
tRock = "${tRock[0]+pos[i]!!.x}"+"${tRock[1]+pos[i]!!.y}"
}
if (tRock[0] in 'A'..'H' && tRock[1] in '1'..'8'){ // 돌이 밖으로 나가지 않을 경우
Copy link
Member

Choose a reason for hiding this comment

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

말이 밖으로 나가지 않는 경우를 두번 사용하고 있는데 String의 확장함수로 넣어주면 좋을것 같아요

private fun String.validate() = get(0) in 'A'..'H' && get(1) in '1'..'8'

val move = readln().toString()
var tKing = kingPos
var tRock = rockPos
for (i in move){
Copy link
Member

Choose a reason for hiding this comment

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

이부분 char 반복문인데 i로 사용하면 Int로 오인할 수 있을것 같아요 c 같은 변수로 정의해보면 좋을것 같아요

Comment on lines +47 to +48
println(kingPos)
println(rockPos)
Copy link
Member

Choose a reason for hiding this comment

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

(minor) println(kingPos + "\n" + rockPos)

@gongdongho12 gongdongho12 added the review complete 리뷰 완료 label Oct 22, 2022
@ashwon12 ashwon12 merged commit 20ebd5a into main Nov 6, 2022
@ashwon12 ashwon12 deleted the week3_jaewon branch November 18, 2022 08:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
review complete 리뷰 완료
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[3주차 문제]
2 participants