DEV Community

benboorstein
benboorstein

Posted on

Advent of Code 2022 Day 2 Part 1 - Solution Only

// EXAMPLE input (encrypted strategy guide) converted to a multiline string
const strategyGuide =
`A Y
B X
C Z`

// opponent is first column and this is opponent winning
const oppWinning = {
    A: 'Z',
    B: 'X',
    C: 'Y'    
}

// I am second column and this is me winning
const meWinning = {
    A: 'Y',
    B: 'Z',
    C: 'X'
}

// points granted for use of tool
const toolPoints = {
    X: 1,
    Y: 2,
    Z: 3
}

const getMyTotalScore = (input) => {
    const inputAsArr = input.split('\n').map(str => str.split(' ')) // the reason 'input' is converted to an array of arrays instead of an object of key-value pairs is because the ACTUAL input (i.e., not the EXAMPLE input we're working with here) would, if set up as an object, have duplicate keys, and of course duplicate keys are not allowed in JavaScript objects (iterating through the keys of a JavaScript object that has duplicate keys doesn't work)

    let myTotalScore = 0

    for (let i = 0; i < inputAsArr.length; i++) {
        myTotalScore += toolPoints[inputAsArr[i][1]]

        if (inputAsArr[i][1] === meWinning[inputAsArr[i][0]]) {
            myTotalScore += 6
        } else if (inputAsArr[i][1] === oppWinning[inputAsArr[i][0]]) {
            myTotalScore
        } else {
            myTotalScore += 3
        }
    }

    return myTotalScore
}

console.log(getMyTotalScore(strategyGuide)) // 15
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs