├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── kotlin │ ├── days │ │ ├── Day.kt │ │ └── Day1.kt │ └── util │ │ ├── InputReader.kt │ │ └── Runner.kt └── resources │ └── input_day_1.txt └── test ├── kotlin ├── days │ └── Day1Test.kt └── util │ ├── InputReaderTest.kt │ └── RunnerTest.kt └── resources └── input_day_1.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ 2 | .idea/ 3 | out/ 4 | *.iml 5 | 6 | # Gradle 7 | .gradle 8 | build/ 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aoc-kotlin-starter 2 | 3 | :sparkles: [Screenshots](#screenshots) :sparkles: 4 | 5 | Starter template for solving [Advent of Code](https://adventofcode.com) in [Kotlin](https://kotlinlang.org/) 6 | 7 | ### Features 8 | 9 | * Gradle setup so you can run a specific day or all days on the command line (see **Running** below) 10 | * Timings for each part of each day 11 | * Input for each day automatically exposed in String and List form 12 | * Junit and Hamcrest test libraries included (see **Testing** below) 13 | * Starter .gitignore 14 | 15 | ### Running 16 | 17 | Project is already setup with gradle. To run the app: 18 | 19 | * Navigate to top-level directory on the command line 20 | * Run `./gradlew run` to run all days 21 | * Run `./gradlew run --args $DAY` where `$DAY` is an integer to run a specific day 22 | 23 | ### Testing 24 | 25 | Project includes Junit and Hamcrest and a stub unit test to get you going. To run all tests: 26 | 27 | * Navigate to top-level directory on the command line 28 | * Run `./gradlew test` 29 | * Add `--info`, `--debug` or `--stacktrace` flags for more output 30 | 31 | ##### Test input 32 | 33 | By default, instantiations of `Day` classes in tests will use the input files in `src/test/resources`, _not_ those in `src/main/resources`. 34 | This hopefully gives you flexibility - you could either just copy the real input into `src/test/resources` if you want to test 35 | the actual answers, or you could add a file of test data based on the examples given on the Advent of Code description for the day. 36 | The stub `Day1Test` class shows a test of the functionality of `Day1` where the test input differs from the actual input. 37 | 38 | ### Architecture 39 | 40 | * Inputs go into `src/main/resources` and follow the naming convention `input_day_X.txt` 41 | * Solutions go into `src/main/kotlin/days` and extend the `Day` abstract class, calling its constructor with their day number 42 | * Solutions follow the naming convention `DayX` 43 | * It is assumed all solutions will have two parts but share the same input 44 | * Input is exposed in the solution classes in two forms - `inputList` and `inputString` 45 | * Day 1 solution class and input file are stubbed as a guide on how to extend the project, 46 | and how you can use the `inputList` and `inputString` mentioned above 47 | * To get started simply replace `src/main/input_day_1.txt` with the real input and the solutions in `Day1` with your own 48 | * A Day 1 test class also exists, mostly to show a few hamcrest matchers, and how test input files can differ from actual ones (see **Test input** section above). 49 | To get started with testing you can edit this class, and the input file at `src/test/resources/input_day_1.txt` 50 | 51 | ### Screenshots 52 | 53 | Screenshots show fake data (not a real advent of code year!) 54 | 55 | ##### Running all days 56 | 57 | ![Running all days](/../screenshots/assets/run-all.png) 58 | 59 | ##### Running a single day 60 | 61 | ![Running a single day](/../screenshots/assets/run-one.png) 62 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | application 3 | kotlin("jvm") version "2.1.0" 4 | } 5 | 6 | application { 7 | mainClass.set("util.Runner") 8 | } 9 | 10 | version = "1.0-SNAPSHOT" 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation(kotlin("stdlib-jdk8")) 18 | implementation("org.reflections", "reflections", "0.10.2") 19 | implementation("org.slf4j:slf4j-nop:2.0.16") 20 | 21 | testImplementation("org.junit.jupiter", "junit-jupiter-api", "5.11.3") 22 | testImplementation("org.junit.jupiter", "junit-jupiter-engine", "5.11.3") 23 | testImplementation("org.hamcrest", "hamcrest", "3.0") 24 | testImplementation ("com.github.stefanbirkner:system-lambda:1.2.1") 25 | } 26 | 27 | tasks.test { 28 | useJUnitPlatform() 29 | } 30 | 31 | kotlin { 32 | jvmToolchain(21) 33 | } 34 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hughjdavey/aoc-kotlin-starter/e7e0e583330b3a7414f736b601b3be36f896ac1c/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'aoc-kotlin-starter' 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/days/Day.kt: -------------------------------------------------------------------------------- 1 | package days 2 | 3 | import util.InputReader 4 | 5 | abstract class Day(dayNumber: Int) { 6 | 7 | // lazy delegate ensures the property gets computed only on first access 8 | protected val inputList: List by lazy { InputReader.getInputAsList(dayNumber) } 9 | protected val inputString: String by lazy { InputReader.getInputAsString(dayNumber) } 10 | 11 | abstract fun partOne(): Any 12 | 13 | abstract fun partTwo(): Any 14 | } 15 | -------------------------------------------------------------------------------- /src/main/kotlin/days/Day1.kt: -------------------------------------------------------------------------------- 1 | package days 2 | 3 | class Day1 : Day(1) { 4 | 5 | override fun partOne(): Any { 6 | return inputList.take(2) 7 | .map { it.uppercase() } 8 | .joinToString(" ") 9 | } 10 | 11 | override fun partTwo(): Any { 12 | return inputString.split("\n") 13 | .filterNot { it.isEmpty() } 14 | .map { it.uppercase() } 15 | .last() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/util/InputReader.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import java.io.File 4 | 5 | object InputReader { 6 | 7 | fun getInputAsString(day: Int): String { 8 | return fromResources(day).readText() 9 | } 10 | 11 | fun getInputAsList(day: Int): List { 12 | return fromResources(day).readLines() 13 | } 14 | 15 | private fun fromResources(day: Int): File { 16 | return File(javaClass.classLoader.getResource("input_day_$day.txt").toURI()) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/kotlin/util/Runner.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import days.Day 4 | import org.reflections.Reflections 5 | import kotlin.math.max 6 | import kotlin.time.ExperimentalTime 7 | import kotlin.time.TimedValue 8 | import kotlin.time.measureTimedValue 9 | 10 | @ExperimentalTime 11 | object Runner { 12 | 13 | private val reflections = Reflections("days") 14 | 15 | @JvmStatic 16 | fun main(args: Array) { 17 | if (args.isNotEmpty()) { 18 | val day = try { 19 | args[0].toInt() 20 | } 21 | catch (e: NumberFormatException) { 22 | printError("Day argument must be an integer") 23 | return 24 | } 25 | 26 | val dayClass = getAllDayClasses()?.find { dayNumber(it.simpleName) == day } 27 | if (dayClass != null) { 28 | printDay(dayClass) 29 | } 30 | else { 31 | printError("Day $day not found") 32 | } 33 | } 34 | else { 35 | val allDayClasses = getAllDayClasses() 36 | if (allDayClasses != null) { 37 | allDayClasses.sortedBy { dayNumber(it.simpleName) }.forEach { printDay(it) } 38 | } 39 | else { 40 | printError("Couldn't find day classes - make sure you're in the right directory and try building again") 41 | } 42 | } 43 | } 44 | 45 | private fun getAllDayClasses(): MutableSet>? { 46 | return reflections.getSubTypesOf(Day::class.java) 47 | } 48 | 49 | private fun printDay(dayClass: Class) { 50 | println("\n=== DAY ${dayNumber(dayClass.simpleName)} ===") 51 | val day = dayClass.constructors[0].newInstance() as Day 52 | 53 | val partOne = measureTimedValue { day.partOne() } 54 | val partTwo = measureTimedValue { day.partTwo() } 55 | printParts(partOne, partTwo) 56 | } 57 | 58 | private fun printParts(partOne: TimedValue, partTwo: TimedValue) { 59 | val padding = max(partOne.value.toString().length, partTwo.value.toString().length) + 14 // 14 is 8 (length of 'Part 1: ') + 6 more 60 | println("Part 1: ${partOne.value}".padEnd(padding, ' ') + "(${partOne.duration})") 61 | println("Part 2: ${partTwo.value}".padEnd(padding, ' ') + "(${partTwo.duration})") 62 | } 63 | 64 | private fun printError(message: String) { 65 | System.err.println("\n=== ERROR ===\n$message") 66 | } 67 | 68 | private fun dayNumber(dayClassName: String) = dayClassName.replace("Day", "").toInt() 69 | } 70 | -------------------------------------------------------------------------------- /src/main/resources/input_day_1.txt: -------------------------------------------------------------------------------- 1 | kotlin 2 | is 3 | awesome 4 | -------------------------------------------------------------------------------- /src/test/kotlin/days/Day1Test.kt: -------------------------------------------------------------------------------- 1 | package days 2 | 3 | import org.hamcrest.MatcherAssert.assertThat 4 | import org.hamcrest.core.Is.`is` 5 | import org.hamcrest.core.IsInstanceOf.instanceOf 6 | import org.hamcrest.core.IsNull.notNullValue 7 | import org.junit.jupiter.api.Test 8 | 9 | class Day1Test { 10 | 11 | private val dayOne = Day1() 12 | 13 | @Test 14 | fun testPartOne() { 15 | assertThat(dayOne.partOne(), `is`("THIS IS")) 16 | } 17 | 18 | @Test 19 | fun testPartTwo() { 20 | val partTwo = dayOne.partTwo() 21 | assertThat(partTwo, notNullValue()) 22 | assertThat(partTwo, instanceOf(String::class.java)) 23 | assertThat(partTwo, `is`("FILE")) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/kotlin/util/InputReaderTest.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import org.hamcrest.MatcherAssert.assertThat 4 | import org.hamcrest.collection.IsIterableContainingInOrder.contains 5 | import org.hamcrest.core.Is.`is` 6 | import org.junit.jupiter.api.Test 7 | 8 | class InputReaderTest { 9 | 10 | @Test 11 | fun testReadInputAsString() { 12 | val testInputAsString = InputReader.getInputAsString(1) 13 | assertThat(testInputAsString, `is`("this\nis\na\ntest input\nfile\n")) 14 | } 15 | 16 | @Test 17 | fun testReadInputAsList() { 18 | val testInputAsList = InputReader.getInputAsList(1) 19 | assertThat(testInputAsList, contains("this", "is", "a", "test input", "file")) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/kotlin/util/RunnerTest.kt: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemErr 4 | import com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemOut 5 | import org.hamcrest.MatcherAssert.assertThat 6 | import org.hamcrest.Matchers.`is` 7 | import org.hamcrest.Matchers.matchesPattern 8 | import org.junit.jupiter.api.Test 9 | import kotlin.time.ExperimentalTime 10 | 11 | @OptIn(ExperimentalTime::class) 12 | class RunnerTest { 13 | 14 | @Test 15 | fun testPrintDay() { 16 | val day1 = tapSystemOut { Runner.main(arrayOf("1")) } 17 | assertThat(day1, matchesPattern( 18 | """ 19 | 20 | === DAY 1 === 21 | Part 1: THIS IS \(.*\) 22 | Part 2: FILE \(.*\) 23 | 24 | """.trimIndent() 25 | )) 26 | } 27 | 28 | @Test 29 | fun testPrintErrors() { 30 | val dayNotAString = tapSystemErr { Runner.main(arrayOf("one")) } 31 | assertThat(dayNotAString, `is`("\n=== ERROR ===\nDay argument must be an integer\n")) 32 | 33 | val dayNotExists = tapSystemErr { Runner.main(arrayOf("99")) } 34 | assertThat(dayNotExists, `is`("\n=== ERROR ===\nDay 99 not found\n")) 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/resources/input_day_1.txt: -------------------------------------------------------------------------------- 1 | this 2 | is 3 | a 4 | test input 5 | file 6 | --------------------------------------------------------------------------------