adventofcode2022/day2/solution.ts

139 lines
3.0 KiB
TypeScript
Raw Normal View History

2022-12-03 00:59:02 -05:00
import { readFileSync } from 'fs';
import { join } from 'path';
enum GameStatus {
Win = 1,
Lose,
Draw,
}
function didIWinRound(oppoMove: string, myMove: string): GameStatus {
if (oppoMove == 'A') {
if (myMove == 'X') {
return GameStatus.Draw
}
if (myMove == 'Y') {
return GameStatus.Win
}
if (myMove == 'Z') {
return GameStatus.Lose
}
}
if (oppoMove == 'B') {
if (myMove == 'X') {
return GameStatus.Lose
}
if (myMove == 'Y') {
return GameStatus.Draw
}
if (myMove == 'Z') {
return GameStatus.Win
}
}
if (oppoMove == 'C') {
if (myMove == 'X') {
return GameStatus.Win
}
if (myMove == 'Y') {
return GameStatus.Lose
}
if (myMove == 'Z') {
return GameStatus.Draw
}
}
return GameStatus.Lose;
}
function didIWinRoundPtTwo(opMove: string, myMove: string): {status:GameStatus, move:string} {
if (myMove == 'Z') { // Win
if (opMove == 'A') { // Rock
return {status:GameStatus.Win, move:"Y"}; // Paper
}
if (opMove == 'B') { // Paper
return {status:GameStatus.Win, move:"Z"}; // Sissors
}
if (opMove == 'C') { // Sissors
return {status:GameStatus.Win, move:"X"}; // Rock
}
}
if (myMove == 'Y') { // Draw
if (opMove == 'A') { // Rock
return {status:GameStatus.Draw, move:"X"}; // Rock
}
if (opMove == 'B') { // Paper
return {status:GameStatus.Draw, move:"Y"}; // Paper
}
if (opMove == 'C') { // Sissors
return {status:GameStatus.Draw, move:"Z"}; // Sissors
}
}
if (myMove == 'X') { // Lose
if (opMove == 'A') { // R
return {status:GameStatus.Lose, move:"Z"}; // S
}
if (opMove == 'B') { // P
return {status:GameStatus.Lose, move:"X"}; // R
}
if (opMove == 'C') { // S
return {status:GameStatus.Lose, move:"Y"}; // P
}
}
}
let pointsLookup = {};
pointsLookup["A"] = 1;
pointsLookup["X"] = 1;
pointsLookup["B"] = 2;
pointsLookup["Y"] = 2;
pointsLookup["C"] = 3;
pointsLookup["Z"] = 3;
const fileString = readFileSync(join(__dirname, "input"), 'utf-8');
const rounds = fileString.split("\n");
var totalScore: number = 0;
var totalScoreTwo: number = 0;
for (const round of rounds){
const moves = round.split(" ");
if (moves.length != 2) {
continue;
}
const opScore = pointsLookup[moves[0]];
const myScore = pointsLookup[moves[1]];
var roundScore: number = 0;
const win = didIWinRound(moves[0], moves[1]);
roundScore += myScore;
if (win == GameStatus.Win) {
roundScore += 6;
} else if (win == GameStatus.Draw) {
roundScore += 3;
}
totalScore += roundScore;
var roundScorePt2: number = 0;
const {status, move} = didIWinRoundPtTwo(moves[0], moves[1]);
const myScorePt2 = pointsLookup[move];
roundScorePt2 += myScorePt2;
if (status == GameStatus.Win) {
roundScorePt2 += 6;
} else if (status == GameStatus.Draw) {
roundScorePt2 += 3;
}
totalScoreTwo += roundScorePt2;
}
console.log(totalScore);
console.log(totalScoreTwo);