Compare commits

...

5 commits
main ... lua

Author SHA1 Message Date
3976b051d0
Add lua template file 2023-12-16 22:00:54 -07:00
b41bf1ec13
Add solution to day 8 2023-12-11 22:12:31 -07:00
24ff3b369c
Add solution to day 11 2023-12-11 22:10:03 -07:00
4346cc7fc0
Update gitignore for lua 2023-12-11 22:09:26 -07:00
9248d35b50
Switch to Lua 2023-12-06 21:29:46 -07:00
19 changed files with 213 additions and 904 deletions

6
.gitignore vendored
View file

@ -1,4 +1,2 @@
.gradle
.idea
build
src/**/*.txt
src/*.txt
*.swp

View file

@ -1,25 +1,10 @@
# aoc-2023
Welcome to the Advent of Code[^aoc] Kotlin project created by [wbrawner][github] using the [Advent of Code Kotlin Template][template] delivered by JetBrains.
In this repository, wbrawner is about to provide solutions for the puzzles using [Kotlin][kotlin] language.
If you're stuck with Kotlin-specific questions or anything related to this template, check out the following resources:
- [Kotlin docs][docs]
- [Kotlin Slack][slack]
- Template [issue tracker][issues]
# Advent of Code 2023
Here are my solutions to the Advent of Code[^aoc] 2023 challenges. I did the first few days in Kotlin, then switched over to Lua for the rest.
[^aoc]:
[Advent of Code][aoc] An annual event of Christmas-oriented programming challenges started December 2015.
Every year since then, beginning on the first day of December, a programming puzzle is published every day for twenty-five days.
You can solve the puzzle and provide an answer using the language of your choice.
[aoc]: https://adventofcode.com
[docs]: https://kotlinlang.org/docs/home.html
[github]: https://github.com/wbrawner
[issues]: https://github.com/kotlin-hands-on/advent-of-code-kotlin-template/issues
[kotlin]: https://kotlinlang.org
[slack]: https://surveys.jetbrains.com/s3/kotlin-slack-sign-up
[template]: https://github.com/kotlin-hands-on/advent-of-code-kotlin-template
[aoc]: https://adventofcode.com

View file

@ -1,50 +0,0 @@
plugins {
kotlin("jvm") version "1.9.21"
}
sourceSets {
main {
kotlin.srcDir("src")
}
}
tasks {
wrapper {
gradleVersion = "8.5"
}
// Adapted from https://github.com/kotlin-hands-on/advent-of-code-kotlin-template/pull/17
task("generateNextDay") {
doLast {
val prevDayNum = fileTree("$projectDir/src").matching {
include("Day*.kt")
}.maxOf {
val (prevDayNum) = Regex("Day(\\d\\d)").find(it.name)!!.destructured
prevDayNum.toInt()
}
val newDayNum = String.format("%02d", prevDayNum + 1)
File("$projectDir/src", "Day$newDayNum.kt").writeText(
"""fun main() {
fun part1(input: List<String>): Int {
return input.size
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${newDayNum}_test")
check(part1(testInput) == 0)
val input = readInput("Day${newDayNum}")
part1(input).println()
part2(input).println()
}
"""
)
File("$projectDir/src", "Day$newDayNum.txt").createNewFile()
File("$projectDir/src", "Day${newDayNum}_test.txt").createNewFile()
}
}
}

Binary file not shown.

View file

@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
gradlew vendored
View file

@ -1,249 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored
View file

@ -1,92 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -1,7 +0,0 @@
rootProject.name = "aoc-2023"
dependencyResolutionManagement {
repositories {
mavenCentral()
}
}

View file

@ -1,77 +0,0 @@
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
var firstDigit: Char? = null
var lastDigit: Char? = null
it.forEach { c ->
if (!c.isDigit()) return@forEach
if (firstDigit == null) {
firstDigit = c
}
lastDigit = c
}
"$firstDigit$lastDigit".toInt()
}
}
val numbers = listOf(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
)
fun part2(input: List<String>): Int {
return input.sumOf { line ->
var firstIndex: Int = Integer.MAX_VALUE
var firstNumberIndex: Int? = null
var lastIndex: Int = -1
var lastNumberIndex: Int? = null
numbers.forEachIndexed { numberIndex, number ->
val firstLineIndex = line.indexOf(number)
val lastLineIndex = line.lastIndexOf(number)
if (firstLineIndex > -1 && firstIndex > firstLineIndex) {
firstIndex = firstLineIndex
firstNumberIndex = numberIndex
}
if (lastLineIndex > -1 && lastIndex < lastLineIndex) {
lastIndex = lastLineIndex
lastNumberIndex = numberIndex
}
}
"${firstNumberIndex!!.numberValue}${lastNumberIndex!!.numberValue}".toInt()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part2(testInput) == 281)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
val Int.numberValue: Int
get() {
val value = (this + 1) % 9
return if (value == 0) {
9
} else {
value
}
}

View file

@ -1,72 +0,0 @@
fun main() {
fun part1(input: List<String>): Int {
val maxCubes = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14
)
return input.map { Game.parse(it) }
.sumOf { game ->
val validGame = game.subsets.all { subset ->
subset.none { (color, count) ->
(count > maxCubes[color]!!)
}
}
if (validGame) {
game.id
} else {
0
}
}
}
fun part2(input: List<String>): Int {
return input.map { Game.parse(it) }
.sumOf { game ->
val minNecessary = mutableMapOf(
"blue" to 0,
"green" to 0,
"red" to 0
)
game.subsets.forEach { subset ->
subset.forEach { (color, count) ->
if (count > minNecessary[color]!!) {
minNecessary[color] = count
}
}
}
var power = 1
minNecessary.values.forEach { power *= it }
power
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 8)
check(part2(testInput) == 2286)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
data class Game(val id: Int, val subsets: Set<Map<String, Int>>) {
companion object {
fun parse(s: String): Game {
val colonPosition = s.indexOf(':')
val id = s.substring(5, colonPosition).toInt()
val subsets = s.substring(colonPosition + 2)
.split(';')
.map { set ->
set.split(',')
.associate {
val parts = it.trim().split(' ')
parts[1] to parts[0].toInt()
}
}
.toSet()
return Game(id, subsets)
}
}
}

View file

@ -1,80 +0,0 @@
import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
val numRegex = Regex("\\d+")
val symbolRegex = Regex("[^.\\d]")
input.forEachIndexed { index, line ->
numRegex.findAll(line).forEach { numberResult ->
numberResult.groups.forEach groups@{ group ->
if (group == null) return@groups
val searchRange = max(0, group.range.first - 1)..min(group.range.last + 1, line.lastIndex)
val searchRegions = listOf(
input[max(0, index - 1)],
input[index],
input[min(input.lastIndex, index + 1)],
)
if (searchRegions.any {
it.substring(searchRange).contains(symbolRegex)
}) {
sum += group.value.toInt()
}
}
}
}
return sum
}
fun part2(input: List<String>): Int {
val numRegex = Regex("\\d+")
val symbolRegex = Regex("[^.\\d]")
val asterisks = mutableMapOf<Pair<Int, Int>, Set<Int>>()
input.forEachIndexed { index, line ->
numRegex.findAll(line).forEach { numberResult ->
numberResult.groups.forEach groups@{ group ->
if (group == null) return@groups
val searchRange = max(0, group.range.first - 1)..min(group.range.last + 1, line.lastIndex)
val searchRegions = listOf(
input[max(0, index - 1)],
input[index],
input[min(input.lastIndex, index + 1)],
)
if (searchRegions.any {
it.substring(searchRange).contains(symbolRegex)
}) {
searchRegions.forEachIndexed { regionIndex, region ->
val gearIndex = region.substring(searchRange).indexOf('*')
if (gearIndex > -1) {
val coordinates = (index + regionIndex - 1) to gearIndex + searchRange.first
val gearNumbers = asterisks[coordinates]?.toMutableSet()?: mutableSetOf()
gearNumbers.add(group.value.toInt())
asterisks[coordinates] = gearNumbers
}
}
}
}
}
}
var sum = 0
asterisks.values.forEach {
if (it.size != 2) {
return@forEach
}
sum += it.fold(1) { left, right -> left * right}
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 4361)
val input = readInput("Day03")
part1(input).println()
check(part2(testInput) == 467835)
part2(input).println()
}

View file

@ -1,55 +0,0 @@
import kotlin.math.pow
fun main() {
fun part1(input: List<String>): Int {
var matchValue = 0
input.forEach { card ->
val winningNumbers = card.winningNumbers
val matches = card.myNumbers.sumOf { number ->
(if (winningNumbers.contains(number)) 1 else 0).toInt()
}
matchValue += when {
matches > 1 -> 2.0.pow(matches - 1).toInt()
else -> matches
}
}
return matchValue
}
fun part2(input: List<String>): Int {
val cardCounts = MutableList(input.size) { 1 }
val matches = MutableList(input.size) { 0 }
input.forEachIndexed { index, card ->
val winningNumbers = card.winningNumbers
val matchCount = card.myNumbers.sumOf { number ->
(if (winningNumbers.contains(number)) 1 else 0).toInt()
}
matches[index] = matchCount * cardCounts[index]
for (i in index + 1..index + matchCount) {
cardCounts[i] = cardCounts[i] + (1 * cardCounts[index])
}
}
return cardCounts.subList(0, input.size).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 13)
val input = readInput("Day04")
part1(input).println()
check(part2(testInput) == 30)
part2(input).println()
}
val String.winningNumbers: Set<Int>
get() = substringAfter(':')
.substringBefore('|')
.split(' ')
.mapNotNull { it.toIntOrNull() }
.toSet()
val String.myNumbers: List<Int>
get() = substringAfter('|')
.split(' ')
.mapNotNull { it.toIntOrNull() }

View file

@ -1,112 +0,0 @@
fun main() {
fun part1(input: List<String>): Long {
return SupplyMapper(input).lowestLocation()
}
fun part2(input: List<String>): Long {
return SupplyMapper(input).lowestLocationPart2()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == 35L)
val input = readInput("Day05")
part1(input).println()
check(part2(testInput) == 46L)
part2(input).println()
}
class SupplyMapper(input: List<String>) {
private val seeds: List<Long>
private val seedRanges: List<LongRange>
private val rangeMaps: List<Set<RangeMap>>
init {
val inputIterator = input.iterator()
seeds = inputIterator.next()
.substringAfter(' ')
.split(' ')
.map { it.toLong() }
val seedRanges = mutableListOf<LongRange>()
for (i in seeds.indices.step(2)) {
val start = seeds[i]
val end = start + seeds[i + 1]
seedRanges.add(start..<end)
}
this.seedRanges = seedRanges
inputIterator.next()
val rangeMaps = mutableListOf<Set<RangeMap>>()
while (inputIterator.hasNext()) {
rangeMaps.add(inputIterator.rangeMaps())
}
this.rangeMaps = rangeMaps
}
fun lowestLocation(): Long = seeds.minOf(::mapSeedToLocation)
fun lowestLocationPart2(): Long {
repeat(Int.MAX_VALUE) { number ->
val location = number.toLong()
val seed = mapLocationToSeed(location)
if (seedRanges.any { it.contains(seed) }) {
return@lowestLocationPart2 location
}
}
return 0L
}
private fun mapSeedToLocation(seed: Long): Long {
return rangeMaps.fold(seed) { num, rangeMapSet -> rangeMapSet.map(num) }
}
private fun mapLocationToSeed(location: Long): Long {
return rangeMaps.reversed().fold(location) { num, rangeMapSet -> rangeMapSet.reverseMap(num) }
}
}
private fun Iterator<String>.rangeMaps(): Set<RangeMap> {
val ranges = mutableSetOf<RangeMap>()
next()
var line = next()
while (line.isNotBlank() && line.first().isDigit()) {
ranges.add(RangeMap.parse(line))
if (!hasNext()) break
line = next()
}
return ranges
}
data class RangeMap(val sourceRange: LongRange, val destRange: LongRange) {
constructor(sourceStart: Long, destStart: Long, rangeSize: Long) :
this(sourceStart..<sourceStart + rangeSize, destStart..<destStart + rangeSize)
fun map(source: Long): Long? {
return if (!sourceRange.contains(source)) {
null
} else {
destRange.first + sourceRange.offset(source)
}
}
fun reverseMap(source: Long): Long? {
return if (!destRange.contains(source)) {
null
} else {
sourceRange.first + destRange.offset(source)
}
}
companion object {
fun parse(s: String): RangeMap {
val (destStart, srcStart, rangeSize) = s.split(' ').map { it.toLong() }
return RangeMap(sourceStart = srcStart, destStart = destStart, rangeSize = rangeSize)
}
}
}
fun LongRange.offset(at: Long) = at - first
fun Set<RangeMap>.map(source: Long) = firstNotNullOfOrNull { it.map(source) } ?: source
fun Set<RangeMap>.reverseMap(source: Long) = firstNotNullOfOrNull { it.reverseMap(source) } ?: source

View file

@ -1,60 +0,0 @@
fun main() {
fun part1(input: List<String>): Long = input.parseRaces()
.waysToWin()
.reduce { left, right -> left * right}
fun part2(input: List<String>): Long = input.parseRace().waysToWin()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 288L)
val input = readInput("Day06")
part1(input).println()
check(part2(testInput) == 71503L)
part2(input).println()
}
data class Race(val time: Long, val distance: Long)
fun List<String>.parseRaces(): List<Race> {
val times = get(0).numbers()
val distances = get(1).numbers()
return times.zip(distances).map { Race(it.first, it.second) }.toList()
}
fun List<String>.parseRace(): Race {
val time = get(0).number()
val distance = get(1).number()
return Race(time, distance)
}
fun List<Race>.waysToWin(): List<Long> = map { race ->
race.waysToWin()
}
fun Race.waysToWin(): Long {
var min = 0L
for (pressTime in 1..<time) {
val moveTime = time - pressTime
val distanceMoved = moveTime * pressTime
if (distanceMoved > distance) {
min = pressTime
break
}
}
var max = 0L
for (pressTime in time downTo 1) {
val moveTime = time - pressTime
val distanceMoved = moveTime * pressTime
if (distanceMoved > distance) {
max = pressTime
break
}
}
return max - min + 1
}
fun String.numbers() = Regex("\\d+").findAll(this).map { it.value.toLong() }
fun String.number() = Regex("\\d+").findAll(this).joinToString("") { it.value }.toLong()

View file

@ -1,21 +0,0 @@
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.io.path.Path
import kotlin.io.path.readLines
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = Path("src/$name.txt").readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
/**
* The cleaner shorthand for printing output.
*/
fun Any?.println() = println(this)

16
src/_template.lua Normal file
View file

@ -0,0 +1,16 @@
require "util"
function part1(input)
return #input
end
function part2(input)
return #input
end
local test_input = read_test_input()
assert_equals(part1(test_input), 0)
local input = read_input()
print(part1(input))
assert_equals(part2(test_input), 0)
print(part2(input))

92
src/day08.lua Normal file
View file

@ -0,0 +1,92 @@
---@diagnostic disable: lowercase-global
require "util"
function parse_node(line)
local matches = {}
for match in line:gmatch("%w+") do
matches[#matches + 1] = match
end
return matches[1], { L = matches[2], R = matches[3] }
end
function values(src)
local dest = {}
for _,v in pairs(src) do
dest[#dest + 1] = v
end
return dest
end
function part1(input)
local steps = input[1]
local nodes = {}
for i = 3, #input do
local node, children = parse_node(input[i])
nodes[node] = children
end
local current_node = "AAA"
local step_index = 1
local step_count = 0
while current_node ~= "ZZZ" do
local nextStep = steps:sub(step_index, step_index)
current_node = nodes[current_node][nextStep]
step_count = step_count + 1
step_index = step_index + 1
if step_index > #steps then
step_index = 1
end
end
return step_count
end
function find_lcm(first, second)
local max = math.max(first, second)
local fcm = first * second
local cm = max
io.write(string.format("finding lcm of %s and %s... ", first, second))
while cm <= fcm do
if (cm % first == 0 and cm % second == 0) then
print(cm)
return cm
end
cm = cm + max
end
end
function part2(input)
local steps = input[1]
local nodes = {}
local current_nodes = {}
for i = 3, #input do
local node, children = parse_node(input[i])
nodes[node] = children
if string.sub(node, #node, #node) == "A" then
current_nodes[node] = 0
end
end
for node, _ in pairs(current_nodes) do
local step_index = 1
local current_node = node
while current_node:sub(#current_node, #current_node) ~= "Z" do
local nextStep = steps:sub(step_index, step_index)
current_node = nodes[current_node][nextStep]
current_nodes[node] = current_nodes[node] + 1
step_index = step_index + 1
if step_index > #steps then
step_index = 1
end
end
end
local node_steps = values(current_nodes)
local lcm = find_lcm(node_steps[1], node_steps[2])
for i = 3, #node_steps do
lcm=find_lcm(lcm, node_steps[i])
end
return lcm
end
local test_input = readInput("day08_test.txt")
local input = readInput("day08.txt")
print(part1(input))
assert_equals(part2(test_input), 6)
print(part2(input))

70
src/day11.lua Normal file
View file

@ -0,0 +1,70 @@
require "util"
function parse_galaxies(input)
local galaxies = {}
local empty_rows = {}
local empty_cols = {}
for y, line in ipairs(input) do
empty_rows[y] = true
for x = 1, #line do
if empty_cols[x] == nil then
empty_cols[x] = true
end
if line:sub(x, x) == "#" then
empty_rows[y] = false
empty_cols[x] = false
galaxies[#galaxies + 1] = { x = x, y = y }
end
end
end
return galaxies, empty_rows, empty_cols
end
function calculate_offsets(data, offset_increment)
local offsets = {}
local data_index = 1
local offset = 0
for i, empty in ipairs(data) do
if empty then
offset = offset + offset_increment - 1
end
offsets[i] = offset
end
return offsets
end
function expand_universe(galaxies, empty_rows, empty_cols, expansion_amount)
local row_offsets = calculate_offsets(empty_rows, expansion_amount)
local col_offsets = calculate_offsets(empty_cols, expansion_amount)
for i, galaxy in ipairs(galaxies) do
galaxies[i] = {
x = galaxy.x + col_offsets[galaxy.x],
y = galaxy.y + row_offsets[galaxy.y],
}
end
end
function distance(a, b)
return math.abs(a.x - b.x) + math.abs(a.y - b.y)
end
function part1(input, expansion_amount)
local galaxies, empty_rows, empty_cols = parse_galaxies(input)
expand_universe(galaxies, empty_rows, empty_cols, expansion_amount)
local distances = 0
for i, galaxy in ipairs(galaxies) do
for j = i + 1, #galaxies do
local other_galaxy = galaxies[j]
distances = distances + distance(galaxy, other_galaxy)
end
end
return distances
end
local test_input = read_test_input()
assert_equals(part1(test_input, 2), 374)
assert_equals(part1(test_input, 10), 1030)
assert_equals(part1(test_input, 100), 8410)
local input = read_input()
print(part1(input, 2))
print(part1(input, 1000000))

30
src/util.lua Normal file
View file

@ -0,0 +1,30 @@
function get_day_name()
return arg[0]:sub(1,5)
end
function read_input()
local day = get_day_name()
return read_file(day .. ".txt")
end
function read_test_input()
local day = get_day_name()
return read_file(day .. "_test.txt")
end
function read_file(file)
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
function assert_equals(actual, expected, message)
if actual ~= expected then
print(string.format("assert failed: %s", message or ""))
print(string.format("\texpected: %s", expected))
print(string.format("\tactual: %s", actual))
os.exit(1)
end
end