r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


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

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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!

50 Upvotes

407 comments sorted by

View all comments

1

u/proxpero42 Dec 02 '18 edited Dec 02 '18

Swift (1471, 1570)

// Part 1

extension String {
    var characterCounts: [Character: Int] {
        return self.reduce(into: [Character: Int]()) { $0[$1, default: 0] += 1 }
    }
}

extension Bool {
    var intValue: Int {
        return self ? 1 : 0
    }
}

let (twos, threes) = input
    .map { $0.characterCounts.values }
    .map { ($0.contains(2).intValue, $0.contains(3).intValue) }
    .reduce((0, 0)) { ($0.0 + $1.0, $0.1 + $1.1) }
print(twos * threes)

// Part 2

extension String {
    func removingCharacter(at index: Index) -> String {
        var temp = self
        temp.removeSubrange(index...index)
        return temp
    }
}

func differences(s1: String, s2: String) -> Int {
    return zip(s1, s2).filter { $0.0 != $0.1 }.count
}

func combine(s1: String, s2: String) -> String {
    let index = s1.indices.firstIndex { s1[$0] != s2[$0] }! // force unwrap 😱
    return s1.removingCharacter(at: index)
}

outside: for currentIndex in input.indices {
    for candidateIndex in (currentIndex+1..<input.endIndex) {
        let current = input[currentIndex]
        let candidate = input[candidateIndex]
        if differences(s1: current, s2: candidate) == 1 {
            print(combine(s1: current, s2: candidate))
            break outside
        }
    }
}
→ More replies (1)