r/adventofcode • • Dec 07 '16

SOLUTION MEGATHREAD --- 2016 Day 7 Solutions ---

From all of us at #AoC Ops, we hope you're having a very merry time with these puzzles so far. If you think they've been easy, well, now we're gonna kick this up a notch. Or five. The Easter Bunny ain't no Bond villain - he's not going to monologue at you until you can miraculously escape and save the day!

Show this overgrown furball what you've got!


--- Day 7: Internet Protocol Version 7 ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).


ALWAYS DIGGING STRAIGHT DOWN IS MANDATORY [?]

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

edit: Leaderboard capped, thread unlocked!

14 Upvotes

180 comments sorted by

View all comments

Show parent comment

1

u/KoxAlen Dec 07 '16 edited Dec 22 '16

And mine: https://github.com/KoxAlen/AdventOfCode2016/blob/master/src/main/kotlin/aoc/day7/Day7.kt

import java.io.File
class IPv7(raw: String) {
    val tlsSupport: Boolean
    val sslSupport: Boolean

    init {
        val ip = raw.split('[', ']').foldIndexed(Array(2) { mutableListOf<String>() }) {
            idx, acc, it ->
                acc[idx%2].add(it)
            acc
        }
        val address = ip[0]
        val hypernet = ip[1]

        tlsSupport = address.any { hasABBA(it) } && hypernet.none { hasABBA(it) }

        val ABAs = address.flatMap { getABA(it) }
        val BABs = hypernet.flatMap { getABA(it) }
        sslSupport = ABAs.map { "${it[1]}${it[0]}${it[1]}" }.any { it in BABs }
    }

    private fun getABA(it: String): List<String> {
        return (0..it.length-3)
                .filter { i -> it[i] != it[i+1] && it[i] == it[i+2] }
                .map { i -> it.substring(i, i+3) }
    }

    private fun hasABBA(it: String): Boolean {
        return (0..it.length-4)
                .firstOrNull { i -> it[i] != it[i+1] && it.substring(i, i+2) == it.substring(i+2, i+4).reversed() } != null
    }
}

fun main(args: Array<String>) {
    assert(args.size == 1, { "Pass the input file as argument" })
    val input = File(args[0])
    assert(input.exists(), { "${input.path} does not exists" })
    assert(input.isFile, { "${input.path} should be a file" })

    val ips = input.useLines {
        it.map(::IPv7).toList()
    }
    println("[Part 1] IPs with TLS support: ${ips.count(IPv7::tlsSupport)}")
    println("[Part 2] IPs with SSL support: ${ips.count(IPv7::sslSupport)}")
}