Skip to content

Commit

Permalink
feat(2022-day-02): score rochambeau games
Browse files Browse the repository at this point in the history
  • Loading branch information
amclin committed Dec 2, 2022
1 parent 033077f commit d13ae6d
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
3 changes: 3 additions & 0 deletions 2022/day-02/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// eslint-disable-next-line no-unused-vars
const console = require('../helpers')
require('./solution')
53 changes: 53 additions & 0 deletions 2022/day-02/rochambeau.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

// Lookup tables for possible rock / paper / scissor values
const selfCodes = ['X', 'Y', 'Z']
const opponentCodes = ['A', 'B', 'C']

const scoreRound = (opponent, self) => {
const scoreShape = (self) => {
return selfCodes.indexOf(self) + 1
}

const scoreOutcome = (opponent, self) => {
const selfScore = selfCodes.indexOf(self)
const oppScore = opponentCodes.indexOf(opponent)
// Win
if (
(selfScore - 1 === oppScore) ||
(selfScore === -1 && oppScore === 2)
) {
return 6
}
// Lose
if (
(oppScore - 1 === selfScore) ||
(oppScore === -1 && selfScore === 2)
) {
return 0
}
// Draw
if (selfCodes.indexOf(self) === opponentCodes.indexOf(opponent)) {
return 3
}

throw new Error(`Could not calculate the results of the match: ${opponent}, ${self}`)
}

return scoreShape(self) + scoreOutcome(opponent, self)
}

/**
* Tallies the results of all rounds in a match
* @param {*} guide
* @returns
*/
const scoreMatch = (guide) => {
return guide.map((match) => {
return scoreRound(...match)
}).reduce((sum, value) => sum + value, 0)
}

module.exports = {
scoreMatch,
scoreRound
}
26 changes: 26 additions & 0 deletions 2022/day-02/rochambeau.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* eslint-env mocha */
const { expect } = require('chai')
const { scoreMatch, scoreRound } = require('./rochambeau')

describe.only('--- Day 2: Rock Paper Scissors ---', () => {
describe('Part 1', () => {
describe('scoreRound', () => {
it('calculates the score of a round based on what the opponent played and what you played', () => {
expect(scoreRound('A', 'Y')).to.equal(8)
expect(scoreRound('B', 'X')).to.equal(1)
expect(scoreRound('C', 'Z')).to.equal(6)
})
})
describe('scoreMatch', () => {
it('calculates the total score of a match', () => {
expect(
scoreMatch([
['A', 'Y'],
['B', 'X'],
['C', 'Z']
])
).to.equal(15)
})
})
})
})

0 comments on commit d13ae6d

Please sign in to comment.