Advent of Code Day 5: Counting Fresh Ingredients
10 Dec 2025 #csharpOn Day 5 of Advent of Code, we’re helping the elves to find which ingredients are fresh or spoiled.
To find if an ingredient is fresh, I create a FreshIngredientRange with a method IsFresh(),
record FreshIngredientRange(int IngredientId1, int IngredientId2)
{
public bool IsFresh(int productId)
=> productId >= IngredientId1 && productId <= IngredientId2;
}
Then, to count all the fresh ingredients, I write a method that receives all product ranges and all candidate products. A single LINQ query will do the counting,
static int CountFreshIngredients(
IEnumerable<FreshIngredientRange> ranges,
IEnumerable<int> productIds)
=> productIds.Count(productId => ranges.Any(r => r.IsFresh(productId)));
Here’s my final solution,
var ranges = new FreshIngredientRange[]
{
new FreshIngredientRange(3, 5),
new FreshIngredientRange(10, 14),
new FreshIngredientRange(16, 20),
new FreshIngredientRange(12, 18)
};
var productIds = new int[] { 1, 5, 8, 11, 17, 32 };
var count = CountFreshIngredients(ranges, productIds);
Console.WriteLine(count);
Console.ReadKey();
static int CountFreshIngredients(IEnumerable<FreshIngredientRange> ranges, IEnumerable<int> productIds)
=> productIds.Count(productId => ranges.Any(r => r.IsFresh(productId)));
record FreshIngredientRange(int IngredientId1, int IngredientId2)
{
public bool IsFresh(int productId)
=> productId >= IngredientId1 && productId <= IngredientId2;
}
That’s an easy one with LINQ. Just one single line. Et voilà!
Advent of Code sharpens your coding skills. But coding is more than typing symbols fast. It’s also about teamwork, collaboration, and many skills I share in my book, Street-Smart Coding: 30 Ways to Get Better at Coding. That’s the roadmap I wish I’d known from day one.