Skip to content

Commit

Permalink
Add Day 4 part 1 solution without Pow
Browse files Browse the repository at this point in the history
  • Loading branch information
eduherminio committed Dec 4, 2023
1 parent caf6f3d commit 2d4a568
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/AoC_2023/Day_04.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public Day_04()
_input = ParseInput().ToList();
}

public override ValueTask<string> Solve_1() => new($"{Solve_1_Original()}");
public override ValueTask<string> Solve_1() => new($"{Solve_1_NoPow()}");

public override ValueTask<string> Solve_2() => new($"{Solve_2_NoDictionary()}");

Expand All @@ -20,6 +20,31 @@ public int Solve_1_Original()
return _input.Sum(card => (int)Math.Pow(2, card.CardNumbers.Intersect(card.WinningNumbers).Count() - 1));
}

public int Solve_1_OptimizedIntersectOrder()
{
return _input.Sum(card => (int)Math.Pow(2, card.WinningNumbers.Intersect(card.CardNumbers).Count() - 1));
}

public int Solve_1_NoPow()
{
int result = 0;

foreach (var card in _input)
{
var winnerThatWeHave = card.WinningNumbers.Intersect(card.CardNumbers).Count();

int points = winnerThatWeHave == 0 ? 0 : 1;
for (int i = 1; i < winnerThatWeHave; ++i)
{
points *= 2;
}

result += points;
}

return result;
}

public int Solve_2_Original()
{
Dictionary<Card, int> cards = _input.ToDictionary(card => card, _ => 1);
Expand Down
20 changes: 20 additions & 0 deletions tests/AoC_2023.Benchmarks/Day_04_Benchmarks.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
/*
*
* | Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Allocated | Alloc Ratio |
* |------------------------------ |---------:|--------:|--------:|------:|--------:|--------:|----------:|------------:|
* | Part1_Original | 211.6 us | 4.18 us | 4.29 us | 1.00 | 0.00 | 49.0723 | 100.53 KB | 1.00 |
* | Part1_OptimizedIntersectOrder | 199.9 us | 3.98 us | 4.59 us | 0.95 | 0.03 | 79.1016 | 161.84 KB | 1.61 |
* | Part1 | 187.9 us | 3.75 us | 3.85 us | 0.89 | 0.02 | 79.1016 | 161.8 KB | 1.61 |
*
* | Method | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio |
* |------------------- |---------:|--------:|---------:|------:|--------:|----------:|------------:|
Expand All @@ -9,6 +15,20 @@

namespace AoC_2023.Benchmarks;

public class Day_04_Part1 : BaseDayBenchmark
{
private readonly Day_04 _problem = new();

[Benchmark(Baseline = true)]
public int Part1_Original() => _problem.Solve_1_Original();

[Benchmark]
public int Part1_OptimizedIntersectOrder() => _problem.Solve_1_OptimizedIntersectOrder();

[Benchmark]
public int Part1() => _problem.Solve_1_NoPow();
}

public class Day_04_Part2 : BaseDayBenchmark
{
private readonly Day_04 _problem = new();
Expand Down

0 comments on commit 2d4a568

Please sign in to comment.