Skip to content

2023 - Day 6 - Wait For It

Posted on:December 6, 2023 at 11:45 AM

A Race of Timing and Distance

On Day 6, our Advent of Code journey took an exciting turn with a boat race challenge on Island Island. The task? Calculate the number of ways to beat the record in a race where timing is everything.

Our Solution

We employed TypeScript to develop efficient solutions for both parts of the challenge, focusing on the intricate relationship between time, speed, and distance. Additional care was given to focus on functional programming in TypeScript.

Part One: Calculating Winning Strategies

import calculateWinningWays from "./utils";

export default function partOne(inputArray: string[]): number {
  const [timeString, distanceString] = inputArray;

  const digits = /\d+/g;
  const times = timeString.match(digits)!.map(Number);
  const distances = distanceString.match(digits)!.map(Number);

  return times
    .map((time, index) => calculateWinningWays(time, distances[index]))
    .reduce((acc, curr) => (acc *= curr), 1);
}

In partOne, we analyzed each race to determine the number of possible ways to beat the record. Our solution involved calculating the potential distances based on different button-holding durations and comparing them against the record distances.

Part Two: One Long Race

import calculateWinningWays from "./utils";

const concatenateStrings = (acc: string, curr: string): string => {
  return acc + curr;
};

export default function partTwo(inputArray: string[]): number {
  const [timeString, distanceString] = inputArray;

  const digits = /\d+/g;
  const time = timeString.match(digits)!.reduce(concatenateStrings, "");
  const distance = distanceString.match(digits)!.reduce(concatenateStrings, "");

  return calculateWinningWays(Number(time), Number(distance));
}

partTwo presented us with a twist: interpreting the input as a single, much longer race. We adapted our approach to handle this extended format, ensuring that our calculation method remained robust and effective.

Utility Function: calculateWinningWays

export default function calculateWinningWays(time: number, distance: number): number {
	const ways = Array.from({ length: Math.floor(time / 2) + 1 }, (_, speed) => speed)
			.filter(speed => speed * (time - speed) > distance)
			.length * 2;

	return time % 2 === 0 ? ways - 1 : ways;
};

Our utility function, calculateWinningWays, played a pivotal role in both parts. It efficiently calculated the feasible number of ways to surpass the record by considering various speeds and their resulting distances.

Conclusion

Day 6 challenged us to think creatively about the relationship between time, speed, and distance. Our TypeScript solutions demonstrated the power of careful calculation and strategic planning in achieving victory in this unique race.

Stay tuned for more adventures and coding challenges as we navigate the Advent of Code!