Last active
December 14, 2022 19:52
-
-
Save JavadocMD/100e49509c15283390ee124b2638c1c1 to your computer and use it in GitHub Desktop.
A solution to Advent of Code 2022 Day 6 without sets, only loops (modeled as nested recursive functions).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright 2022 Tyler Coles (javadocmd.com) | |
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 | |
http://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. | |
*/ | |
import scala.annotation.tailrec | |
import scala.io.Source | |
object Day06Loops: | |
final def main(args: Array[String]): Unit = | |
val input = Source.fromResource("Day06.input.txt").mkString | |
val part1 = findMarker(input, length = 4) | |
println(part1) | |
val part2 = findMarker(input, length = 14) | |
println(part2) | |
@tailrec | |
def findMarker(signal: String, length: Int, position: Int = 0): Int = | |
@tailrec | |
def findDuplicate(check: Int, cursor: Int, stop: Int): Int = | |
// when check advances to stop, conclude no duplicate found | |
if check == stop then -1 | |
// when cursor advances to stop, advance check and reset cursor | |
else if cursor == stop then findDuplicate(check + 1, check + 2, stop) | |
// if the characters at check and cursor are equal, duplicate found | |
// return the index at which to continue the outer search | |
else if signal(check) == signal(cursor) then check + 1 | |
// otherwise, advance cursor | |
else findDuplicate(check, cursor + 1, stop) | |
if position + length > signal.length then -1 // stop if there aren't enough characters left to make the marker | |
else | |
// search for duplicates within `length` of our current position | |
findDuplicate(position, position + 1, position + length) match | |
case -1 => position + length // no duplicate means we've found the marker! success | |
case next => findMarker(signal, length, position = next) // otherwise keep looking | |
end findMarker |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Scala 3.2.1