Skip to content

Instantly share code, notes, and snippets.

@oberhamsi
Created December 2, 2022 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oberhamsi/cd14d18b539955d5c32017b4d70940e4 to your computer and use it in GitHub Desktop.
Save oberhamsi/cd14d18b539955d5c32017b4d70940e4 to your computer and use it in GitHub Desktop.
const ROCK = 'rock';
const PAPER = 'paper';
const SCISSORS = 'scissors';
const LOOSE = 'loose';
const DRAW = 'draw';
const WIN = 'win';
const sum = (array) => array.reduce((prev, curr) => prev + curr);
const scoreForShape = (round) => {
return {
[ROCK]: 1,
[PAPER]: 2,
[SCISSORS]: 3
}[round.me];
};
const scoreForResult = (round) => {
if (round.opponent === round.me) {
return 3;
}
const winnerShape = getShapeToWin(round.opponent);
return winnerShape === round.me ? 6 : 0;
};
// shape that wins against given shape
const getShapeToWin = (shape) => {
return {
[ROCK]: PAPER,
[PAPER]: SCISSORS,
[SCISSORS]: ROCK
}[shape];
};
// shape that looses against given shape
const getShapeToLoose = (shape) => {
return {
[PAPER]: ROCK,
[SCISSORS]: PAPER,
[ROCK]: SCISSORS
}[shape];
};
const decodeShapeSymbol = (symbol) => {
return {
A: ROCK,
B: PAPER,
C: SCISSORS,
X: ROCK,
Y: PAPER,
Z: SCISSORS
}[symbol];
}
const decodeGuideSymbol = (symbol) => {
return {
X: LOOSE,
Y: DRAW,
Z: WIN
}[symbol]
}
// given the opponents shape and our guide hint
// which shape should be picked
const getShapeForGuide = (opponent, guideHint) => {
if (guideHint === DRAW) {
return opponent;
} else if (guideHint === WIN) {
return getShapeToWin(opponent)
} else {
return getShapeToLoose(opponent);
}
};
// parse first part into {opponent, me} shapes
const parseHandsPerRound = (inputString) => {
const rounds = inputString.split('\n');
return rounds.map(p => {
const shapes = p.split(' ');
return {
opponent: decodeShapeSymbol(shapes[0]),
me: decodeShapeSymbol(shapes[1])
}
})
};
// parse second part into {opponent, me} shapes
const parseHandGuidePerRound = (inputString) => {
const rounds = inputString.split('\n');
return rounds.map(p => {
const shapes = p.split(' ');
const opponent = decodeShapeSymbol(shapes[0]);
const guideHint = decodeGuideSymbol(shapes[1]);
return {
opponent,
me: getShapeForGuide(opponent, guideHint)
}
})
};
const mainDayTwoA = (inputString) => {
const rounds = parseHandsPerRound(inputString);
const scores = rounds.map(round => {
return scoreForShape(round) + scoreForResult(round)
})
return sum(scores);
}
const mainDayTwoB = (inputString) => {
const rounds = parseHandGuidePerRound(inputString);
const scores = rounds.map(round => {
return scoreForShape(round) + scoreForResult(round)
})
return sum(scores);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment