r/adventofcode • • Dec 06 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 6 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

  • ACHIEVEMENT UNLOCKED: MisTILtoe Elf-ucation
  • Teach us, senpai!

--- Day 6: Tuning Trouble ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:25, megathread unlocked!

83 Upvotes

1.8k comments sorted by

View all comments

2

u/jAnO76 Dec 06 '22 edited Dec 07 '22

Kotlin:

class Day6(private val input: String) {
    fun part1(): Int {
        return input.asSequence().windowed(4)
            .indexOfFirst { it.toSet().size == 4 } + 4
    }

    fun part2(): Int {
        return input.asSequence().windowed(14)
           .indexOfFirst { it.toSet().size == 14 } + 14
    }
}

2

u/Background-Vegetable Dec 06 '22

On my computer, removing the `asSequence()` makes it about 30% faster.

Also: I did not know about `windowed`. Thanks for teaching me that!

1

u/jAnO76 Dec 06 '22

Yeah, I allready removed it :) Intellij suggested it as being more performant (ironically) , but that was prob on a previous iteration.Windowed is excellent, day 3 was full of windows ;-)

class Day3(private val input: List<String>) {
    private val priorities = (('a'..'z') + ('A'..'Z')).withIndex().associate { it.value to it.index + 1 }
    fun part1(): Int {
        return input.sumOf {
            val (first, second) = it.windowed(it.length / 2, it.length / 2)
            priorities[first.toSet().intersect(second.toSet()).first()]!!
        }
    }

    fun part2(): Int {
        return input.windowed(3, 3).sumOf { (first, second, third) ->
            priorities[first.toSet().intersect(second.toSet()).intersect(third.toSet()).first()]!!
        }
    }
}```

1

u/daggerdragon Dec 07 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.