Skip to content

Commit

Permalink
AOC Day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
adamjberg committed Dec 1, 2023
1 parent 5847905 commit a6c4f87
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 1 deletion.
80 changes: 80 additions & 0 deletions _posts/adam/advent-of-code/2022/2023-12-01-aoc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
layout: post
title: Advent of Code 2023 Day 1 - Trebuchet?! - Solution in JavaScript
author: adam
permalink: /adam/2022-12-01-advent-of-code
description: Solution for Advent of Code (AoC) Day 1 in JavaScript (JS)
image: assets/img/advent-of-code-2023-day-1-trebuchet?!-in-javascript
tags: dev js
---

I only made it through 3 days of posting solutions last year...let's see how this year goes.

I got wrecked by part two because I started with a regex solution that failed to pick up a match when the last text digit was part of another one. For example: "1eightwo". My first version picked up 18, but because the "t" was part of "eight" it never picked up "two".

```js
import fs from "fs";
import { log } from "console";

const lines = fs.readFileSync("./day1.txt", {encoding: "utf-8"}).split("\n");

function isDigit(char) {
return /^\d$/.test(char);
}

function part1() {
let sum = 0;

for (const line of lines) {
let firstNum, lastNum;
for (const c of line) {
if (isDigit(c)) {
if (!firstNum) {
firstNum = c;
}
lastNum = c;
}
}

const twoDigit = `${firstNum}${lastNum}`;
sum += Number(twoDigit);
}

log(sum);
}

function part2() {
let sum = 0;

for(const line of lines) {
let digits = [];

for (let i = 0; i < line.length; i++) {
const c = line[i];

if (isDigit(c)) {
digits.push(c);
}

const textDigits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
const lineSubstring = line.substring(i);
for (let d = 0; d < textDigits.length; d++) {
const textDigit = textDigits[d];
if (lineSubstring.startsWith(textDigit)) {
digits.push(d+1);
}
}
}

const lastIndex = digits.length - 1;
const twoDigits = `${digits[0]}${digits[lastIndex]}`;

sum += Number(twoDigits);
}

log(sum);
}

part1();
part2();
```
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion tools/previews/createPreview.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ if (title) {
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/\n/g, "-");
fs.writeFileSync(`${formattedTitle}.png`, png);
fs.writeFileSync(`../../assets/img/${formattedTitle}.png`, png);
}

0 comments on commit a6c4f87

Please sign in to comment.