이번 글에서는, 리스트의 최댓값을 구하고, 그 최댓값이 위치한 인덱스를 함께 찾는 두 가지 방식에 대해 정리 해 보겠습니다.
특히, 최댓값 문제를 풀면서 알게되어 두 번째 방식에서 사용한 withIndex 문법에 대해 중점적으로 살펴보겠습니다.
문제 정의
9개의 정수를 입력받아 리스트에 저장한 뒤, 다음 두 가지를 출력하는 프로그램을 작성합니다:
- 리스트의 최댓값
- 최댓값이 위치한 인덱스(1부터 시작)
풀이 방법 1: 간단한 라이브러리 함수 활용
먼저, 코틀린의 내장 함수를 활용한 간단한 풀이 방법입니다.
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val maxNums = mutableListOf<Int>()
repeat(9) {
val b = br.readLine().toInt()
maxNums.add(b)
}
bw.write("${maxNums.max()}\n")
bw.write("${maxNums.indexOf(maxNums.max()) + 1}\n")
bw.flush()
bw.close()
}
코드 설명
- max() 함수:
- maxNums.max()는 리스트에서 최댓값을 바로 반환합니다.
- indexOf 함수:
- maxNums.indexOf(maxNums.max())는 최댓값의 인덱스를 반환합니다.
- 인덱스를 1부터 출력하기 위해 + 1을 추가합니다.
풀이 방법 2: withIndex를 활용한 직접 순회
다음은 withIndex를 활용한 방식입니다.
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val maxNums = mutableListOf<Int>()
repeat(9) {
val b = br.readLine().toInt()
maxNums.add(b)
}
val (max, maxLine) = findMax(maxNums)
bw.write("$max\n")
bw.write("$maxLine\n")
bw.flush()
bw.close()
}
fun findMax(list: List<Int>): Pair<Int, Int> {
var max = Int.MIN_VALUE
var maxLine = -1
for ((index, value) in list.withIndex()) {
if (value > max) {
max = value
maxLine = index + 1 // 1-based index
}
}
return Pair(max, maxLine)
}
코드 설명
- withIndex 문법:
- for ((index, value) in list.withIndex())는 리스트를 순회하면서 각 요소의 인덱스와 값을 동시에 제공합니다.
- 구조 분해 선언((index, value))을 사용해 IndexedValue 객체에서 인덱스와 값을 한 번에 꺼낼 수 있습니다.
- 최댓값과 인덱스 추적:
- max 변수는 현재까지의 최댓값을 저장하며, maxLine은 해당 값의 인덱스를 1부터 시작하도록 저장합니다.
- if (value > max) 조건을 통해 현재 값이 max보다 크면 이를 갱신합니다.
- Pair 반환:
- 최댓값과 인덱스를 묶어 Pair로 반환해 간결하게 처리합니다.
- 최댓값과 인덱스를 묶어 Pair로 반환해 간결하게 처리합니다.
두 방법 비교
항목풀이 방법 1풀이 방법 2
가독성 | 매우 간단하고 직관적임 | 약간 복잡함 |
사용된 문법 | 내장 함수(max, indexOf) 사용 | withIndex와 구조 분해 선언 활용 |
학습 목적 | 코틀린 내장 함수의 활용법 학습 | 순회 방식과 withIndex 이해 가능 |
withIndex 문법의 이점
1. 인덱스와 값을 동시에 처리
withIndex는 별도의 인덱스 변수를 관리할 필요 없이, 리스트 요소와 해당 인덱스를 동시에 사용할 수 있도록 도와줍니다.
예:
val list = listOf(10, 20, 30)
for ((index, value) in list.withIndex()) {
println("Index: $index, Value: $value")
}
출력:
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
2. 구조 분해 선언
코드를 더 읽기 쉽게 만들며, 가독성을 높입니다. 복잡한 데이터를 처리하는 데 유용합니다.
백준: https://www.acmicpc.net/problem/2562
참고: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/with-index.html
withIndex
Returns a lazy Iterable that wraps each element of the original array into an IndexedValue containing the index of that element and the element itself. Since Kotlin1.0 Returns a lazy Iterable that wraps each element of the original collection into an Index
kotlinlang.org
'Computer Science > Algorithm' 카테고리의 다른 글
[Algorithm/Kotlin] 에라토스테네스의 체(Sieve of Eratosthenes) 쉽게 이해하기 (0) | 2025.01.20 |
---|---|
[Algorithm/Kotlin] 백준 10816번 숫자 카드 2: 시간 복잡도를 계산해 시간초과 해결하기 (0) | 2025.01.16 |
[Algorithm/Kotlin] 백준 2164번 카드2: Queue를 활용한 풀이법 (0) | 2025.01.06 |
[Algorithm/Kotlin] 백준 2839번 설탕 배달 (0) | 2025.01.06 |
[Algorithm/Kotlin] 백준 7568번 덩치: StringBuilder를 활용한 풀이법 (1) | 2025.01.02 |