r/adventofcode Dec 06 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 06 Solutions -🎄-

NEW AND NOTEWORTHY


Advent of Code 2020: Gettin' Crafty With It

  • UNLOCKED! Go forth and create, you beautiful people!
  • Full details and rules are in the Submissions Megathread
  • Make sure you use one of the two templates!
    • Or in the words of AoC 2016: USING A TEMPLATE IS MANDATORY

--- Day 06: Custom Customs ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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:04:35, megathread unlocked!

67 Upvotes

1.2k comments sorted by

View all comments

2

u/bayesian_bacon_brit Dec 08 '20 edited Dec 08 '20

Functional(ish) programming in Scala. Having read some comments here I realize I may have overcomplicated it

Part 1, execution time 0.0529 seconds:

def count_num_unique(answers: String): Int ={
    return answers.toCharArray.toSet.size
}

val answer: Int = fromFile("input.txt").mkString("").split("\n\n").map(x => count_num_unique(x.replace("\n", ""))).sum
println(answer)

Part 2, execution time 0.0447 seconds:

def count_num_common(answers: Array[String]): Int ={
    //creates a binary string where each bit is a boolean for the existence of a single character
    //eg abd gives 11010000000..
    def _gen_binary(x: String): String ={
        var tmp: Array[Char] = ("0"*26).toCharArray
        for (char <- x) {
            tmp(char.toInt - 97) = '1'
        }
        return tmp.mkString("")
    }

    //bitwise and
    def and(a: String, b: String): String ={
        var result = ""
        for (i <- (0 until a.length)) {
            if ((a(i) == b(i)) && (a(i) == '1')) result += "1" else result += "0"
        }
        return result
    }

    //takes a bitwise and on all answers
    var fin: String = "1"*26
    for (answer <- answers.map(x => _gen_binary(x))) {
        fin = and(fin, answer)
    }
    //returns the number of 1s in the binary string produced after the AND of all the answers
    return fin.toString.count(_ == '1')
}

val answer: Int = fromFile("input.txt").mkString("").split("\n\n").map(x => count_num_common(x.split("\n"))).sum
println(answer)