diff --git a/scripts/aoc2015/day15/input.txt b/scripts/aoc2015/day15/input.txt new file mode 100644 index 0000000..66e1882 --- /dev/null +++ b/scripts/aoc2015/day15/input.txt @@ -0,0 +1,4 @@ +Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 +Sprinkles: capacity -3, durability 3, flavor 0, texture 0, calories 9 +Candy: capacity -1, durability 0, flavor 4, texture 0, calories 1 +Chocolate: capacity 0, durability 0, flavor -2, texture 2, calories 8 \ No newline at end of file diff --git a/scripts/aoc2015/day15/puzzle1.ts b/scripts/aoc2015/day15/puzzle1.ts new file mode 100644 index 0000000..e7d56a8 --- /dev/null +++ b/scripts/aoc2015/day15/puzzle1.ts @@ -0,0 +1,101 @@ +/* +--- Day 15: Science for Hungry People --- +Today, you set out on the task of perfecting your milk-dunking cookie recipe. +All you have to do is find the right balance of ingredients. + +Your recipe leaves room for exactly 100 teaspoons of ingredients. +You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon: + +capacity (how well it helps the cookie absorb milk) +durability (how well it keeps the cookie intact when full of milk) +flavor (how tasty it makes the cookie) +texture (how it improves the feel of the cookie) +calories (how many calories it adds to the cookie) +You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories. + +For instance, suppose you have these two ingredients: + +Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8 +Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3 +Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties: + +A capacity of 44*-1 + 56*2 = 68 +A durability of 44*-2 + 56*3 = 80 +A flavor of 44*6 + 56*-2 = 152 +A texture of 44*3 + 56*-1 = 76 +Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero. + +Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make? + +ALGORITHM + +- read all ingredients from file + - we will need a specific parseIngredient function for that + +- make variations of 100 ingredients from all ingredients + +- add score to each variation + - take score for each of: + capacity + durability + flavor + texture + if one of ingredients is bellow 0, total score is zero + if all ingredients are above 0, total score is multiplying of those properties + +- create a board of results +- add score of each variation to the board +- find one with best score +*/ + +// ALGORITHM II +// +// +// - read all ingredients from file +// - we will need a specific parseIngredient function for that +import { + computeScore, + generateCombinationWithRepetition, + Ingredient, + parseIngredientLine, +} from "./utils.ts"; + +async function processFile(filename: string): Promise { + const input = await Deno.readTextFileSync(filename); + const ingredients: Ingredient[] = []; + for (const line of input.split("\n")) { + const ingredient = parseIngredientLine(line); + if (ingredient) { + ingredients.push(ingredient); + } + } + console.log("ingredients", ingredients); + // - make an iterator, that will provide you with next combination with repetition of 100 ingredients from all ingredients + const generator = generateCombinationWithRepetition( + ingredients.map((i) => i.name), + 100, + ); + // - create a board of results + const board: number[] = []; + const ingredientsMap = ingredients.reduce( + (acc: Record, ingredient) => ({ + ...acc, + [ingredient.name]: ingredient, + }), + {}, + ); + // - start to iterate, in each iteration, compute score. + for (const combination of generator) { + const scoreForCombination = computeScore(combination, ingredientsMap); + // If score is above zero, add it to the board + if (scoreForCombination) { + board.push(scoreForCombination); + } + } + // - find one with best score + console.log("max score", Math.max(...board)); +} + +// expected score 62842880 +processFile("./simpleInput.txt"); +processFile("./input.txt"); diff --git a/scripts/aoc2015/day15/puzzle2.ts b/scripts/aoc2015/day15/puzzle2.ts new file mode 100644 index 0000000..07955a0 --- /dev/null +++ b/scripts/aoc2015/day15/puzzle2.ts @@ -0,0 +1,115 @@ +/* +--- Day 15: Science for Hungry People --- +Today, you set out on the task of perfecting your milk-dunking cookie recipe. +All you have to do is find the right balance of ingredients. + +Your recipe leaves room for exactly 100 teaspoons of ingredients. +You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon: + +capacity (how well it helps the cookie absorb milk) +durability (how well it keeps the cookie intact when full of milk) +flavor (how tasty it makes the cookie) +texture (how it improves the feel of the cookie) +calories (how many calories it adds to the cookie) +You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories. + +For instance, suppose you have these two ingredients: + +Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8 +Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3 +Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties: + +A capacity of 44*-1 + 56*2 = 68 +A durability of 44*-2 + 56*3 = 80 +A flavor of 44*6 + 56*-2 = 152 +A texture of 44*3 + 56*-1 = 76 +Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero. + +Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make? + +--- Part Two --- +Your cookie recipe becomes wildly popular! +Someone asks if you can make another recipe that has exactly 500 calories per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100 teaspoons, same ingredients, same scoring system). + +For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go down, though: only 57600000, the best you can do in such trying circumstances. + +Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500? + + + +ALGORITHM + +- read all ingredients from file + - we will need a specific parseIngredient function for that + +- make variations of 100 ingredients from all ingredients + +- add score to each variation + - take score for each of: + capacity + durability + flavor + texture + if one of ingredients is bellow 0, total score is zero + if all ingredients are above 0, total score is multiplying of those properties + +- create a board of results +- add score of each variation to the board +- find one with best score +*/ + +// ALGORITHM II +// +// +// - read all ingredients from file +// - we will need a specific parseIngredient function for that +import { + computeCalories, + computeScore, + generateCombinationWithRepetition, + Ingredient, + parseIngredientLine, +} from "./utils.ts"; + +async function processFile(filename: string): Promise { + const input = await Deno.readTextFileSync(filename); + const ingredients: Ingredient[] = []; + for (const line of input.split("\n")) { + const ingredient = parseIngredientLine(line); + if (ingredient) { + ingredients.push(ingredient); + } + } + console.log("ingredients", ingredients); + // - make an iterator, that will provide you with next combination with repetition of 100 ingredients from all ingredients + const generator = generateCombinationWithRepetition( + ingredients.map((i) => i.name), + 100, + ); + // - create a board of results + const board: number[] = []; + const ingredientsMap = ingredients.reduce( + (acc: Record, ingredient) => ({ + ...acc, + [ingredient.name]: ingredient, + }), + {}, + ); + // - start to iterate, in each iteration, compute score. + for (const combination of generator) { + const calories = computeCalories(combination, ingredientsMap); + if (calories === 500) { + const scoreForCombination = computeScore(combination, ingredientsMap); + // If score is above zero, add it to the board + if (scoreForCombination) { + board.push(scoreForCombination); + } + } + } + // - find one with best score + console.log("max score", Math.max(...board)); +} + +// expected score 57600000 +processFile("./simpleInput.txt"); +processFile("./input.txt"); diff --git a/scripts/aoc2015/day15/simpleInput.txt b/scripts/aoc2015/day15/simpleInput.txt new file mode 100644 index 0000000..1a7ff25 --- /dev/null +++ b/scripts/aoc2015/day15/simpleInput.txt @@ -0,0 +1,2 @@ +Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8 +Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3 diff --git a/scripts/aoc2015/day15/utils.test.ts b/scripts/aoc2015/day15/utils.test.ts new file mode 100644 index 0000000..95c3449 --- /dev/null +++ b/scripts/aoc2015/day15/utils.test.ts @@ -0,0 +1,253 @@ +import { describe, it } from "@std/testing/bdd"; +import { assertEquals, assertThrows } from "@std/assert"; +import { + computeCalories, + computeScore, + generateCombinationWithRepetition, + parseIngredientLine, +} from "./utils.ts"; + +describe("parseIngredientLine", function () { + it("should return null for invalid line", function () { + assertEquals(parseIngredientLine("abc"), null); + }); + it("should return ingredient for valid line", function () { + assertEquals( + parseIngredientLine( + "Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8", + ), + { + name: "Butterscotch", + capacity: -1, + durability: -2, + flavor: 6, + texture: 3, + calories: 8, + }, + ); + }); + + it("should return ingredient for more complex valid line", function () { + assertEquals( + parseIngredientLine( + "Butterscotch: capacity -19, durability -2, flavor 64, texture 3, calories 8", + ), + { + name: "Butterscotch", + capacity: -19, + durability: -2, + flavor: 64, + texture: 3, + calories: 8, + }, + ); + }); +}); + +describe("computeScore", function () { + const ingredients = { + Butterscotch: { + name: "Butterscotch", + capacity: -1, + durability: -2, + flavor: 6, + texture: 3, + calories: 8, + }, + Cinnamon: { + name: "Cinnamon", + capacity: 2, + durability: 3, + flavor: -2, + texture: -1, + calories: 3, + }, + }; + it("should throw error, when ingredient is not found", function () { + assertThrows(() => + computeScore({ + Butterscotch: 1, + }, {}) + ); + }); + it("should return 0, when an property for combination of ingredients is negative", function () { + assertEquals( + computeScore({ + Butterscotch: 1, + }, ingredients), + 0, + ); + }); + it("should return a value for combination of ingredients", function () { + assertEquals( + computeScore({ + Butterscotch: 44, + Cinnamon: 56, + }, ingredients), + 62842880, + ); + }); +}); + +describe("computeCalories", function () { + const ingredients = { + Butterscotch: { + name: "Butterscotch", + capacity: -1, + durability: -2, + flavor: 6, + texture: 3, + calories: 8, + }, + Cinnamon: { + name: "Cinnamon", + capacity: 2, + durability: 3, + flavor: -2, + texture: -1, + calories: 3, + }, + }; + it("should compute calories", function () { + assertEquals( + computeCalories({ + [ingredients.Butterscotch.name]: 2, + [ingredients.Cinnamon.name]: 2, + }, ingredients), + 22, + ); + }); +}); + +describe("generateCombinationWithRepetition", function () { + it("should provide 1 result for n = 0", function () { + const generator = generateCombinationWithRepetition( + ["blue", "brown", "black"], + 0, + ); + const result = generator.next(); + assertEquals(result.value, { + blue: 0, + brown: 0, + black: 0, + }); + }); + + it("should provide 1 result for names with length 1", function () { + const generator = generateCombinationWithRepetition( + ["blue"], + 100, + ); + const result = generator.next(); + assertEquals(result.value, { + blue: 100, + }); + }); + + it("should provide 3 results for names with length 2", function () { + const expectedResults = [{ + blue: 0, + red: 2, + }, { + blue: 1, + red: 1, + }, { + blue: 2, + red: 0, + }]; + assertEquals([...generateCombinationWithRepetition( + ["blue", "red"], + 2, + )], expectedResults); + }); + + it("should provide 6 results for names with length 3", function () { + const expectedResults = [{ + blue: 0, + red: 0, + green: 2, + }, { + blue: 0, + red: 1, + green: 1, + }, { + blue: 0, + red: 2, + green: 0, + }, { + blue: 1, + red: 0, + green: 1, + }, { + blue: 1, + red: 1, + green: 0, + }, { + blue: 2, + red: 0, + green: 0, + }]; + assertEquals([...generateCombinationWithRepetition( + ["blue", "red", "green"], + 2, + )], expectedResults); + }); + + it("should provide x results for names with length 4", function () { + const expectedResults = [{ + blue: 0, + red: 0, + green: 0, + black: 2, + }, { + blue: 0, + red: 0, + green: 1, + black: 1, + }, { + blue: 0, + red: 0, + green: 2, + black: 0, + }, { + blue: 0, + red: 1, + green: 0, + black: 1, + }, { + blue: 0, + red: 1, + green: 1, + black: 0, + }, { + blue: 0, + red: 2, + green: 0, + black: 0, + }, { + blue: 1, + red: 0, + green: 0, + black: 1, + }, { + blue: 1, + red: 0, + green: 1, + black: 0, + }, { + blue: 1, + red: 1, + green: 0, + black: 0, + }, { + blue: 2, + red: 0, + green: 0, + black: 0, + }]; + assertEquals([...generateCombinationWithRepetition( + ["blue", "red", "green", "black"], + 2, + )], expectedResults); + }); +}); diff --git a/scripts/aoc2015/day15/utils.ts b/scripts/aoc2015/day15/utils.ts new file mode 100644 index 0000000..26c5118 --- /dev/null +++ b/scripts/aoc2015/day15/utils.ts @@ -0,0 +1,142 @@ +export type Ingredient = { + name: string; + capacity: number; + durability: number; + flavor: number; + texture: number; + calories: number; +}; + +const ingredientRegex = + /(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)/; + +export function parseIngredientLine(line: string): Ingredient | null { + const match = line.match(ingredientRegex); + if (match) { + return { + name: match[1], + capacity: parseInt(match[2], 10), + durability: parseInt(match[3], 10), + flavor: parseInt(match[4], 10), + texture: parseInt(match[5], 10), + calories: parseInt(match[6], 10), + }; + } + return null; +} + +type RecipeProperties = { + capacity: number; + durability: number; + flavor: number; + texture: number; +}; + +export function computeScore( + combination: Record, + ingredients: Record, +): number { + const ingredientNames = Object.keys(combination); + ingredientNames.forEach((name) => { + if (!ingredients[name]) { + throw new Error("Missing ingredient " + name); + } + }); + const recipeProperties: RecipeProperties = { + capacity: 0, + durability: 0, + flavor: 0, + texture: 0, + }; + for ( + const property of [ + "capacity", + "durability", + "flavor", + "texture", + ] + ) { + let value = 0; + for (const [name, spoonsCount] of Object.entries(combination)) { + const ingredient = ingredients[name]; + value = value + spoonsCount * (ingredient[ + property as keyof RecipeProperties + ]); + } + if (value <= 0) { + return 0; + } + recipeProperties[property as keyof RecipeProperties] = value; + } + return recipeProperties.flavor * recipeProperties.texture * + recipeProperties.capacity * recipeProperties.durability; +} + +export function* generateCombinationWithRepetition( + names: string[], + n: number, // number of item types, you can choose from +): Generator<{ + [name: string]: number; +}> { + // if n = 0 + if (n === 0) { + // yield { name[0]: 0, name[1]: 0, name[2]: 0, ...} + yield names.reduce((acc: { + [name: string]: number; + }, name) => ({ + ...acc, + [name]: 0, + }), {}); + return; + } + // if names length === 1 + if (names.length === 1) { + // yield {[names[0]]: n} + yield { [names[0]]: n }; + return; + } + + // solve for count of names 2 + if (names.length === 2) { + // run loop for i = 0 to n + for (let i = 0; i <= n; i++) { + // yield {names[0] = i; names[1] = n - i} + yield { + [names[0]]: i, + [names[1]]: n - i, + }; + } + } + + // solve for count of names 3+ + if (names.length > 2) { + const firstName = names[0]; + const restNames = names.slice(1); + // take one name X and iterate loop for i = 0 to n + for (let i = 0; i <= n; i++) { + // for (const partialCombination of (generateCombinationWithRepetition( {combinations without X}, n - 1 - i))) + for ( + const partialCombination of generateCombinationWithRepetition( + restNames, + n - i, + ) + ) { + // yield {X: i, ...partialCombination} + yield { + [firstName]: i, + ...partialCombination, + }; + } + } + } +} + +export function computeCalories( + combination: Record, + ingredients: Record, +): number { + return Object.entries(combination).reduce( + (acc, [name, spoons]) => acc + spoons * ingredients[name].calories, + 0, + ); +}