Skip to content

rolroralra/algorithm_kotlin

Repository files navigation

Template Code

import string.Main

fun main() {
//  System.setIn(Main::class.java.getResourceAsStream("input.txt"))
    val br = System.`in`.bufferedReader(Charsets.UTF_8)
    val t = br.readLine().toInt()

    for (testCase in 1 .. t) {
        val n = br.readLine().toInt()

        val inputs = br.readLine().split(" ").map { it.toInt()}

        val result = solution(inputs[0])
        println("#$testCase $result")
    }
}

fun solution(input: Int): Int {
    // TODO: implementation

    return 0
}

Kotlin Memory Usage (MemoryMXBean)

fun printMemoryUsage() {
    val memoryMXBean = ManagementFactory.getMemoryMXBean()
    val heapMemoryUsage = memoryMXBean.heapMemoryUsage
    val nonHeapMemoryUsage = memoryMXBean.nonHeapMemoryUsage

    println("Heap Memory Usage: ${heapMemoryUsage.used / (1024 * 1024)} MB")
    println("Non-Heap Memory Usage: ${nonHeapMemoryUsage.used / (1024 * 1024)} MB")
}

Lower Bound, Upper Bound

code example

Heap (Priority Queue)

code example

Cartesian Product

code example

Code Example
fun <T> Collection<Iterable<T>>.cartesianProduct(): List<List<T>> =
    if (isEmpty()) emptyList()
    else drop(1)
        .fold(first().map(::listOf)) { acc, iterable ->
            acc.flatMap { list ->
                iterable.map(list::plus)
            }
        }

fun <T> Collection<Iterable<T>>.cartesianProduct2(): List<List<T>> {
    if (isEmpty()) {
        return emptyList()
    }

    var result = mutableListOf(mutableListOf<T>())

    forEach { iterable ->
        result = iterable.flatMap { element ->
            result.map { previous ->
                previous.plus(element).toMutableList()
            }
        }.toMutableList()
    }

    return result
}

LCS (Longest Common Subsequence)

code example

Segment Tree

code example

About

Algorithm Problems by Kotlin

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages