James Williams
LinkedInMastodonGithub

Advent Of Code 2022 - Day 6 - Tuning Trouble

For day 6, you need to help the elves with their communication system. Their devices receive a series of characters, one at a time. The start of a usable data packet is indicated by some x characters that are unique.

If you are doing this problem in Kotlin, 95% of the work can be done for you using a pre-defined function in the collections library. I, however, didn't think of it until AFTER completing both stars.

Part I and II

I used much of the same logic for both parts as the only difference was the required number of unique characters. I iterated over the string from zero to string length minus the required size. On each iteration, I created a substring for the target size and tested it for uniqueness.

package adventofcode.y2022
import adventofcode.AdventOfCode
import adventofcode.DayOf2022
import java.util.*

class Day06 : DayOf2022(6) {
    var scan: Scanner

    init {
        //DEBUG = true
        scan = if(DEBUG)
            testScanner
        else scanner
    }

    lateinit var part2Line:String
    override fun part01(): Any? {
        val line = scan.nextLine()
        part2Line = line
        for (i in 0..line.length-4) {
            val x = line.substring(i..i+3).toCharArray().distinct()
            if (x.size == 4) {
                return i+4
            }
        }
        return super.part01()
    }

    override fun part02(): Any? {
        val line = part2Line
        for (i in 0..line.length-14) {
            val x = line.substring(i..i+13).toCharArray().distinct()
            if (x.size == 14) {
                return i+14
            }
        }

        return super.part02()
    }
}

fun main() = AdventOfCode.mainify(Day06())
 

If you are thinking that sounds a lot like windowed with the requirement for no partial windows. You are totally correct.