Skip to content

Commit

Permalink
2020: Day 3 completed
Browse files Browse the repository at this point in the history
  • Loading branch information
bmic86 committed Feb 19, 2023
1 parent fe9496a commit 7de82da
Show file tree
Hide file tree
Showing 4 changed files with 410 additions and 2 deletions.
4 changes: 2 additions & 2 deletions AdventOfCode/Common/Vector2Int.cs
Original file line number Diff line number Diff line change
@@ -1,9 1,9 @@
namespace AdventOfCode.Common
{
public record struct Vector2Int(int X, int Y)
public record struct Vector2Int(int X = 0, int Y = 0)
{
public static Vector2Int operator (Vector2Int a, Vector2Int b)
=> new (a.X b.X, a.Y b.Y);
=> new(a.X b.X, a.Y b.Y);

public static Vector2Int operator *(Vector2Int a, int mul)
=> new(a.X * mul, a.Y * mul);
Expand Down
82 changes: 82 additions & 0 deletions AdventOfCode/Year2020/Day03.cs
Original file line number Diff line number Diff line change
@@ -0,0 1,82 @@
using AdventOfCode.Common;
using AoCHelper;

namespace AdventOfCode.Year2020
{
public class Day03 : BaseDay
{
private readonly int _mapWidth;
private readonly int _mapHeight;
private readonly bool[,] _treeMap;

public Day03()
=> (_treeMap, _mapWidth, _mapHeight) = LoadTreeMap();

public override ValueTask<string> Solve_1()
{
Vector2Int move = new(3, 1);
int treesCount = CountTreesOnPath(move);
return new(treesCount.ToString());
}

public override ValueTask<string> Solve_2()
{
Vector2Int[] moves =
{
new(1, 1),
new(3, 1),
new(5, 1),
new(7, 1),
new(1, 2),
};

long result = moves.Aggregate(
(long)1,
(multiplier, move) => multiplier * CountTreesOnPath(move));

return new(result.ToString());
}

private bool IsTreeOnMap(Vector2Int position)
{
int x = position.X % _mapWidth;
return _treeMap[position.Y, x];
}

private int CountTreesOnPath(Vector2Int move)
{
int treesCount = 0;
for (Vector2Int pos = move; pos.Y < _mapHeight; pos = move)
{
if (IsTreeOnMap(pos))
{
treesCount ;
}
}

return treesCount;
}

private (bool[,] Map, int Width, int Height) LoadTreeMap()
{
string[] lines = File.ReadAllLines(InputFilePath);

int mapWidth = lines.First().Length;
int mapHeight = lines.Length;

bool[,] treeMap = new bool[mapHeight, mapWidth];
for (int y = 0; y < mapHeight; y)
{
for (int x = 0; x < mapWidth; x)
{
if (lines[y][x] == '#')
{
treeMap[y, x] = true;
}
}
}

return (treeMap, mapWidth, mapHeight);
}
}
}
Loading

0 comments on commit 7de82da

Please sign in to comment.