// Originally generated by the template in CodeDAO
package kotlinadventofcode.`2015`

import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import com.github.h0tk3y.betterParse.parser.Parser
import kotlinadventofcode.Day

class `2015-13` : Day {

    data class PersonId(private val id: String)
    data class Effect(val target: PersonId, val change: Int, val source: PersonId)

    /**
     * Alice would gain 54 happiness units by sitting next to Bob.
     */
    fun parse(input: String): List<Effect> {
        val grammar = object: Grammar<List<Effect>>() {
            val would by literalToken(" would ")
            val gain by literalToken("gain")
            val lose by literalToken("lose")
            val personIdText by regexToken("""[a-zA-Z]+""")
            val happinessText by regexToken("\\d+")
            val finalFiller by literalToken(" happiness units by sitting next to ")
            val space by literalToken(" ")
            val period by literalToken(".")
            val newline by literalToken("\n")

            val personId by personIdText use { PersonId(text) }
            val happinessSign by (gain map { 1 }) or (lose map { -1 })
            val unsignedHappiness by happinessText use { text.toInt() }
            val happiness by happinessSign and skip(space) and unsignedHappiness map { it.t1 * it.t2 }

            val line by personId and skip(would) and happiness and skip(finalFiller) and personId and skip(period) map { Effect(it.t1, it.t2, it.t3) }

            override val rootParser: Parser<List<Effect>> by separatedTerms(line, newline)
        }

        return grammar.parseToEnd(input)
    }

    private fun Iterable<Effect>.people(): Set<PersonId> {
        return this.flatMap { listOf(it.source, it.target) }.toSet()
    }

    private fun Iterable<Effect>.toMap(): Map<Pair<PersonId, PersonId>, Int> {
        val result: MutableMap<Pair<PersonId, PersonId>, Int> = mutableMapOf()
        this.forEach { result += (it.target to it.source) to it.change }
        return result
    }

    private fun List<PersonId>.grade(effectByPeople: Map<Pair<PersonId, PersonId>, Int>): Int {
        var result = 0
        for (i in this.indices) {
            val otherI = (i + 1) % this.size
            result += effectByPeople.getValue(this[i] to this[otherI])
            result += effectByPeople.getValue(this[otherI] to this[i])
        }

        return result
    }

    private fun createPermutations(people: Set<PersonId>): Set<List<PersonId>> {
        if (people.size == 1) return setOf(people.toList())

        val person = people.first()
        val permutations = createPermutations(people - person)

        return permutations
            .flatMap {
                val result: MutableList<List<PersonId>> = mutableListOf()
                for (i in it.indices) {
                    val permutation = it.toMutableList()
                    permutation.add(i, person)
                    result += permutation
                }
                result
            }
            .toSet()
    }

    /**
     * After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
     */
    override fun runPartOneNoUI(input: String): String {
        val effects = parse(input)

        // There are only 8 folks so we can just have all the permutations in memory.
        val permutations: Set<List<PersonId>> = createPermutations(effects.people())

        val effectMap = effects.toMap()
        return permutations.maxOf { it.grade(effectMap) }.toString()
    }

    /**
     * After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
     */
    override fun runPartTwoNoUI(input: String): String {
        val effects = parse(input).toMutableList()
        val me = PersonId("💩")
        effects.people().forEach {
            effects += Effect(me, 0, it)
            effects += Effect(it, 0, me)
        }

        val permutations = createPermutations(effects.people() + me)
        val effectMap = effects.toMap()
        return permutations.maxOf { it.grade(effectMap) }.toString()
    }

    override val defaultInput = """Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 81 happiness units by sitting next to Carol.
Alice would lose 42 happiness units by sitting next to David.
Alice would gain 89 happiness units by sitting next to Eric.
Alice would lose 89 happiness units by sitting next to Frank.
Alice would gain 97 happiness units by sitting next to George.
Alice would lose 94 happiness units by sitting next to Mallory.
Bob would gain 3 happiness units by sitting next to Alice.
Bob would lose 70 happiness units by sitting next to Carol.
Bob would lose 31 happiness units by sitting next to David.
Bob would gain 72 happiness units by sitting next to Eric.
Bob would lose 25 happiness units by sitting next to Frank.
Bob would lose 95 happiness units by sitting next to George.
Bob would gain 11 happiness units by sitting next to Mallory.
Carol would lose 83 happiness units by sitting next to Alice.
Carol would gain 8 happiness units by sitting next to Bob.
Carol would gain 35 happiness units by sitting next to David.
Carol would gain 10 happiness units by sitting next to Eric.
Carol would gain 61 happiness units by sitting next to Frank.
Carol would gain 10 happiness units by sitting next to George.
Carol would gain 29 happiness units by sitting next to Mallory.
David would gain 67 happiness units by sitting next to Alice.
David would gain 25 happiness units by sitting next to Bob.
David would gain 48 happiness units by sitting next to Carol.
David would lose 65 happiness units by sitting next to Eric.
David would gain 8 happiness units by sitting next to Frank.
David would gain 84 happiness units by sitting next to George.
David would gain 9 happiness units by sitting next to Mallory.
Eric would lose 51 happiness units by sitting next to Alice.
Eric would lose 39 happiness units by sitting next to Bob.
Eric would gain 84 happiness units by sitting next to Carol.
Eric would lose 98 happiness units by sitting next to David.
Eric would lose 20 happiness units by sitting next to Frank.
Eric would lose 6 happiness units by sitting next to George.
Eric would gain 60 happiness units by sitting next to Mallory.
Frank would gain 51 happiness units by sitting next to Alice.
Frank would gain 79 happiness units by sitting next to Bob.
Frank would gain 88 happiness units by sitting next to Carol.
Frank would gain 33 happiness units by sitting next to David.
Frank would gain 43 happiness units by sitting next to Eric.
Frank would gain 77 happiness units by sitting next to George.
Frank would lose 3 happiness units by sitting next to Mallory.
George would lose 14 happiness units by sitting next to Alice.
George would lose 12 happiness units by sitting next to Bob.
George would lose 52 happiness units by sitting next to Carol.
George would gain 14 happiness units by sitting next to David.
George would lose 62 happiness units by sitting next to Eric.
George would lose 18 happiness units by sitting next to Frank.
George would lose 17 happiness units by sitting next to Mallory.
Mallory would lose 36 happiness units by sitting next to Alice.
Mallory would gain 76 happiness units by sitting next to Bob.
Mallory would lose 34 happiness units by sitting next to Carol.
Mallory would gain 37 happiness units by sitting next to David.
Mallory would gain 40 happiness units by sitting next to Eric.
Mallory would gain 18 happiness units by sitting next to Frank.
Mallory would gain 7 happiness units by sitting next to George."""
}
// Originally generated by the template in CodeDAO
package kotlinadventofcode.`2015`

import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import com.github.h0tk3y.betterParse.parser.Parser
import kotlinadventofcode.Day

class `2015-13` : Day {

    data class PersonId(private val id: String)
    data class Effect(val target: PersonId, val change: Int, val source: PersonId)

    /**
     * Alice would gain 54 happiness units by sitting next to Bob.
     */
    fun parse(input: String): List<Effect> {
        val grammar = object: Grammar<List<Effect>>() {
            val would by literalToken(" would ")
            val gain by literalToken("gain")
            val lose by literalToken("lose")
            val personIdText by regexToken("""[a-zA-Z]+""")
            val happinessText by regexToken("\\d+")
            val finalFiller by literalToken(" happiness units by sitting next to ")
            val space by literalToken(" ")
            val period by literalToken(".")
            val newline by literalToken("\n")

            val personId by personIdText use { PersonId(text) }
            val happinessSign by (gain map { 1 }) or (lose map { -1 })
            val unsignedHappiness by happinessText use { text.toInt() }
            val happiness by happinessSign and skip(space) and unsignedHappiness map { it.t1 * it.t2 }

            val line by personId and skip(would) and happiness and skip(finalFiller) and personId and skip(period) map { Effect(it.t1, it.t2, it.t3) }

            override val rootParser: Parser<List<Effect>> by separatedTerms(line, newline)
        }

        return grammar.parseToEnd(input)
    }

    private fun Iterable<Effect>.people(): Set<PersonId> {
        return this.flatMap { listOf(it.source, it.target) }.toSet()
    }

    private fun Iterable<Effect>.toMap(): Map<Pair<PersonId, PersonId>, Int> {
        val result: MutableMap<Pair<PersonId, PersonId>, Int> = mutableMapOf()
        this.forEach { result += (it.target to it.source) to it.change }
        return result
    }

    private fun List<PersonId>.grade(effectByPeople: Map<Pair<PersonId, PersonId>, Int>): Int {
        var result = 0
        for (i in this.indices) {
            val otherI = (i + 1) % this.size
            result += effectByPeople.getValue(this[i] to this[otherI])
            result += effectByPeople.getValue(this[otherI] to this[i])
        }

        return result
    }

    private fun createPermutations(people: Set<PersonId>): Set<List<PersonId>> {
        if (people.size == 1) return setOf(people.toList())

        val person = people.first()
        val permutations = createPermutations(people - person)

        return permutations
            .flatMap {
                val result: MutableList<List<PersonId>> = mutableListOf()
                for (i in it.indices) {
                    val permutation = it.toMutableList()
                    permutation.add(i, person)
                    result += permutation
                }
                result
            }
            .toSet()
    }

    /**
     * After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
     */
    override fun runPartOneNoUI(input: String): String {
        val effects = parse(input)

        // There are only 8 folks so we can just have all the permutations in memory.
        val permutations: Set<List<PersonId>> = createPermutations(effects.people())

        val effectMap = effects.toMap()
        return permutations.maxOf { it.grade(effectMap) }.toString()
    }

    /**
     * After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
     */
    override fun runPartTwoNoUI(input: String): String {
        val effects = parse(input).toMutableList()
        val me = PersonId("💩")
        effects.people().forEach {
            effects += Effect(me, 0, it)
            effects += Effect(it, 0, me)
        }

        val permutations = createPermutations(effects.people() + me)
        val effectMap = effects.toMap()
        return permutations.maxOf { it.grade(effectMap) }.toString()
    }

    override val defaultInput = """Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 81 happiness units by sitting next to Carol.
Alice would lose 42 happiness units by sitting next to David.
Alice would gain 89 happiness units by sitting next to Eric.
Alice would lose 89 happiness units by sitting next to Frank.
Alice would gain 97 happiness units by sitting next to George.
Alice would lose 94 happiness units by sitting next to Mallory.
Bob would gain 3 happiness units by sitting next to Alice.
Bob would lose 70 happiness units by sitting next to Carol.
Bob would lose 31 happiness units by sitting next to David.
Bob would gain 72 happiness units by sitting next to Eric.
Bob would lose 25 happiness units by sitting next to Frank.
Bob would lose 95 happiness units by sitting next to George.
Bob would gain 11 happiness units by sitting next to Mallory.
Carol would lose 83 happiness units by sitting next to Alice.
Carol would gain 8 happiness units by sitting next to Bob.
Carol would gain 35 happiness units by sitting next to David.
Carol would gain 10 happiness units by sitting next to Eric.
Carol would gain 61 happiness units by sitting next to Frank.
Carol would gain 10 happiness units by sitting next to George.
Carol would gain 29 happiness units by sitting next to Mallory.
David would gain 67 happiness units by sitting next to Alice.
David would gain 25 happiness units by sitting next to Bob.
David would gain 48 happiness units by sitting next to Carol.
David would lose 65 happiness units by sitting next to Eric.
David would gain 8 happiness units by sitting next to Frank.
David would gain 84 happiness units by sitting next to George.
David would gain 9 happiness units by sitting next to Mallory.
Eric would lose 51 happiness units by sitting next to Alice.
Eric would lose 39 happiness units by sitting next to Bob.
Eric would gain 84 happiness units by sitting next to Carol.
Eric would lose 98 happiness units by sitting next to David.
Eric would lose 20 happiness units by sitting next to Frank.
Eric would lose 6 happiness units by sitting next to George.
Eric would gain 60 happiness units by sitting next to Mallory.
Frank would gain 51 happiness units by sitting next to Alice.
Frank would gain 79 happiness units by sitting next to Bob.
Frank would gain 88 happiness units by sitting next to Carol.
Frank would gain 33 happiness units by sitting next to David.
Frank would gain 43 happiness units by sitting next to Eric.
Frank would gain 77 happiness units by sitting next to George.
Frank would lose 3 happiness units by sitting next to Mallory.
George would lose 14 happiness units by sitting next to Alice.
George would lose 12 happiness units by sitting next to Bob.
George would lose 52 happiness units by sitting next to Carol.
George would gain 14 happiness units by sitting next to David.
George would lose 62 happiness units by sitting next to Eric.
George would lose 18 happiness units by sitting next to Frank.
George would lose 17 happiness units by sitting next to Mallory.
Mallory would lose 36 happiness units by sitting next to Alice.
Mallory would gain 76 happiness units by sitting next to Bob.
Mallory would lose 34 happiness units by sitting next to Carol.
Mallory would gain 37 happiness units by sitting next to David.
Mallory would gain 40 happiness units by sitting next to Eric.
Mallory would gain 18 happiness units by sitting next to Frank.
Mallory would gain 7 happiness units by sitting next to George."""
}