Skip to content

Instantly share code, notes, and snippets.

@fmo91
Last active December 5, 2024 12:41
Show Gist options
  • Save fmo91/756a44d4583fa374b016f43fad7eb626 to your computer and use it in GitHub Desktop.
Save fmo91/756a44d4583fa374b016f43fad7eb626 to your computer and use it in GitHub Desktop.
AdventOfCode2024 in Kotlin
import kotlin.math.abs
fun solve(input: String): Int {
val firstList: MutableList<Int> = mutableListOf()
val secondList: MutableList<Int> = mutableListOf()
var result = 0
for (line in input.lines()) {
val components = line.split(" ").filter { it != "" }.map { it.toInt() }
firstList.add(components[0])
secondList.add(components[1])
}
firstList.sort()
secondList.sort()
for (index in 0 ..< firstList.count()) {
result += abs(firstList[index] - secondList[index])
}
return result
}
@fmo91
Copy link
Author

fmo91 commented Dec 5, 2024

Day 2 Part 2

import kotlin.math.abs

fun solve(input: String): Int {
    return input.lines()
        .count { it.isSafe }
}

solve(input = challengeInput())

enum class LevelsTrend {
    DESCENDING,
    ASCENDING,
    EQUAL
}

fun Int.isSafe(previousLevel: Int, trend: LevelsTrend? = null): Boolean {
    val differenceIsCorrect = abs(this - previousLevel) in 1 .. 3
    if (trend == null) {
        return differenceIsCorrect
    }
    val trendIsCorrect = when(trend) {
        LevelsTrend.DESCENDING -> this < previousLevel
        LevelsTrend.ASCENDING -> this > previousLevel
        LevelsTrend.EQUAL -> false
    }
    return differenceIsCorrect && trendIsCorrect
}

fun getTrend(lastLevel: Int, currentLevel: Int) = when {
    currentLevel > lastLevel -> LevelsTrend.ASCENDING
    currentLevel < lastLevel -> LevelsTrend.DESCENDING
    else -> LevelsTrend.EQUAL
}

val String.isSafe: Boolean
    get() {
        val levels = this.split(" ").map { it.toInt() }

        if (isSafe(levels)) {
            return true
        } else {
            for (index in 0 ..< levels.count()) {
                val levelsCopy = levels.toMutableList()
                levelsCopy.removeAt(index)
                if (isSafe(levelsCopy)) {
                    return true
                }
            }
        }

        return false
    }

fun isSafe(levels: List<Int>): Boolean {
    var lastLevel: Int? = null
    var trend: LevelsTrend? = null
    for (level in levels) {
        if (lastLevel != null && trend != null) {
            if (!level.isSafe(previousLevel = lastLevel!!, trend = trend)) {
                return false
            }
            trend = getTrend(lastLevel = lastLevel!!, currentLevel = level)
        } else if (lastLevel != null) {
            trend = getTrend(lastLevel = lastLevel!!, currentLevel = level)
            if (!level.isSafe(previousLevel = lastLevel!!, trend = trend)) {
                return false
            }
        }
        lastLevel = level
    }

    return true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment