adventofcode/2020/Day03.cs

62 lines
1.3 KiB
C#
Raw Normal View History

2020-12-03 15:46:44 +00:00
using System;
using static System.Console;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
namespace AdventOfCode {
public class Day03 {
static int CountTreeIntersections(string[] lines, int dx, int dy) {
2020-12-03 15:58:14 +00:00
int count = 0, x = dx, y = dy;
while (y < lines.Length) {
2020-12-03 15:46:44 +00:00
string line = lines[y];
char tile = line[x % line.Length];
if (tile == '#') {
count++;
}
2020-12-03 15:58:14 +00:00
x += dx;
y += dy;
2020-12-03 15:46:44 +00:00
}
return count;
}
static int Part1() {
string[] input = File.ReadAllLines(Util.RootDir + "day03.txt");
return CountTreeIntersections(input, 3, 1);
}
static long Part2() {
string[] input = File.ReadAllLines(Util.RootDir + "day03.txt");
2020-12-03 15:58:14 +00:00
var deltas = new List<(int, int)> { (1, 1), (3, 1), (5, 1), (7, 1), (1, 2) };
long result = 1;
foreach ((int dx, int dy) in deltas) {
result *= CountTreeIntersections(input, dx, dy);
}
2020-12-03 15:46:44 +00:00
return result;
}
[Fact]
public static void Test() {
string[] example =
@"..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#".Split('\n');
Assert.Equal(7, CountTreeIntersections(example, 3, 1));
Assert.Equal(218, Part1());
Assert.Equal(3847183340, Part2());
}
}
}