01. 이해
전체 학생 중에 일부는 체육복을 도둑 맞았고, 일부는 체육복을 두 벌 들고있다.(세 벌은 놉)
(두 벌 들고 있으면서 도둑 맞은 학생도 있을 수 있음, 그러나 두 벌 다 도둑맞지는 않음)
체육복이 두 벌인 학생들은 자기의 앞,뒤 번호 학생이 체육복이 없다면 빌려줄 수 있다.
체육복을 입을 수 있는 학생의 최댓값을 구해야 한다.
02. 계획
여벌을 들고 있는 학생들이 자신의 앞 뒤 학생들에게 빌려 줄 수 있으면 빌려줘야 하니까
여벌이 있었지만 도둑 맞은 학생을 여벌 옷 리스트에서 지워야함.
(일단 여벌이 있었지만 도둑 맞은 학생은 자기 옷은 있으니까 체육복을 입을 수 있는 학생
수에 더해줘야함)
여벌 옷을 진짜! 빌려 줄 수 있는 학생들을 차례대로 불러서 그 친구의 앞, 뒤에 체육복이
없는 친구가 있는지 보고 빌려주고 체육복을 입을 수 있는 학생 수를 더함
끝나면 반환.
03. 실행
fun solution(n: Int, lost: IntArray, reserve: IntArray): Int {
val alreadySharedStudent = arrayListOf<Int>()
return (1..n).fold(0,
{ answer, student ->
when {
(!lost.contains(student) and !reserve.contains(student)) -> {
answer + 1
}
(lost.contains(student) and reserve.contains(student)) -> {
answer + 1
}
(!lost.contains(student) and reserve.contains(student)) -> {
when {
(student != 1)
and lost.contains(student-1)
and !reserve.contains(student-1)
and (!alreadySharedStudent.contains(student-1)) -> {
alreadySharedStudent.add(student-1)
answer + 2
}
(student != n)
and lost.contains(student+1)
and !reserve.contains(student+1)
and (!alreadySharedStudent.contains(student+1))-> {
alreadySharedStudent.add(student+1)
answer + 2
}
else -> answer + 1
}
}
else -> {
answer
}
}
})
}
04. 회고
계획을 너무 안일하게 짰다. 생각지 못한 엣지 케이스가 너무 많았음.
변수 할당을 하나도 하지 않으려는건 너무 고집이었다.
프로그래머스에 제출하고나서 다른 사람들 코드를 보니까
인자로 받은 array 들은 mutable하게 변경해서 사용하던데
그게 훨씬 좋은 방법인 것 같다.
오랜만에 삽질 거하게 함.