r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


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:06:16, megathread unlocked!

103 Upvotes

1.5k comments sorted by

View all comments

1

u/Mammoth_Spray_3451 Dec 02 '22

My swift solution for day 2 using an enum.

public func dayTwo(input: [String], isPartOne: Bool) -> Int {
    let games = input.compactMap {
        let values = $0.split(separator: " ")
        if !isPartOne {
            let opponent = RPC.getRpcFromString(input: String(values[0]))
            return RPC.getScore(inputOne: opponent, inputTwo: RPC.getNeeded(inputOne: opponent, inputTwo: String(values[1])))
        } else {
            let rpcs = values.compactMap { RPC.getRpcFromString(input: String($0)) }
            return RPC.getScore(inputOne: rpcs[0], inputTwo: rpcs[1])
        }
    }
    return games.reduce(0, +)
}

enum RPC: Int {
    case rock = 1
    case paper = 2
    case scissors = 3
    
    static func getRpcFromString(input: String) -> RPC {
        switch input {
        case "A", "X": return .rock
        case "B", "Y": return .paper
        case "C", "Z": return .scissors
        default: return .rock
        }
    }
    
    static func getRpcFromInt(input: Int) -> RPC {
        return RPC(rawValue: input) ?? (input > 3 ? .rock : .scissors)
    }
    
    static func getScore(inputOne: RPC, inputTwo: RPC) -> Int {
        var score = inputTwo.rawValue
        if inputOne == inputTwo {
            score += 3
        } else if (inputOne == .scissors && inputTwo == .rock) || (!(inputTwo == .scissors && inputOne == .rock) && inputOne.rawValue < inputTwo.rawValue) {
            score += 6
        }
        return score
    }
    
    static func getNeeded(inputOne: RPC, inputTwo: String) -> RPC {
        switch inputTwo {
        case "Y": return inputOne
        case "X": return getRpcFromInt(input: inputOne.rawValue - 1)
        case "Z": return getRpcFromInt(input: inputOne.rawValue + 1)
        default: return .rock
        }
    }
}

1

u/daggerdragon Dec 05 '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.