Algorithm

코틀린으로 코딩테스트 준비하기

YOONJELLY 2024. 2. 1. 13:58

입출력

입력

fun main() = with(System.`in`.bufferedReader()) {
	// 정수 하나 읽기
	val num = readLine().toInt()
	
	// 공백 기준으로 읽기
	val nums = readLine().split(" ").map { it.toInt() }

	// 문자열을 char 배열로 받기
	val char = readLine().toCharArray
}

출력

fun main() = with(System.`out`.bufferedReader()) {
	// 기본
	print("hello")
	
	// bufferedWriter
	val sout = BufferedWriter(OutputStreamWriter(System.out))
	sout.appendLine()
	sout.flush()
	sout.close()

	// 더 짧은 bufferedWriter
	val bw = System.out.bufferedWriter()

	// xpavmfflt
	val s = "abc"
	println("$s.length is ${s.length}")
}

 

자료구조

배열

val arr = intArrayOf(1, 2, 3)

확장 함수로 배열 생성

val arr = IntArray(4) { it }
print(arr.contentToString()) // 결과 : [0, 1, 2, 3]

val arr = IntArray(4) { it * 2 }
print(arr.contentToString()) // 결과 : [0, 2, 4, 6]

다차원 배열

val booleanArray = Array(n) {
	BooleanArray(m) { false }
}
booleanArray[1][2] = true

리스트

  • 코틀린의 리스트는 불변객체이므로 변경이 필요한 경우에는 가변 리스트를 이용하거나 변수로 지정하고 변경하는 방식으로 이용한다.
val list = listOf(1, 2, 3)

스택

  • 자바처럼 라이브러리를 가져와서 사용할 수도 있지만, 내장되어있는 가변 리스트를 스택으로 사용할 수 있다.
val numbers = mutableListOf(1, 2, 3, 4)
val stack = MutableList<Int>(4) { it }

// stack.push(5)
numbers.add(5)

// stack.pop()
numbers.removeLast()

// stack.peek()
numbers.last()

// 비어있는지 확인
numbers.isEmpty()

// 내용물이 있는지 확인
numbers.isNotEmpty()

// 크기
numbers.size()

  • 스택과 비슷하게 별도의 클래스가 존재하지 않으므로 LinkedList를 가져와서 이용한다. (배열 기반으로 작동하는 ArrayList를 사용하는 것은 비효율적이다.)
val que = LinkedList<Int>()
que.offer(3)
que.poll()
pue.peek()

데크

  • 큐에서처럼 LinkedList를 사용하려고 보면 속도가 잘 나지 않는 경우가 있다. ArrayDequeue를 가져와서 사용하는 것이 좋다.
import kotlin.collections.ArrayDeque

val deque = ArrayDeque<Int>()

deque.addLast(1) // exception 반환
deque.offerFirst(2) // exception 반환 x

deque.removeFirst() // exception 반환
deque.pollLast() // exception 반환 x

deque.peekFirst()
deque.peekLast()

 

클래스

  • 자동으로 getter, setter, equals(), hashCode(), toString()을 생성해준다.
data class Cheese(val x:Int, val y:Int, val time:Int)