adventofcode/2020/Day02.cs

63 lines
1.8 KiB
C#

using System;
using static System.Console;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xunit;
namespace AdventOfCode {
public class Day02 {
static bool IsPasswordValid1(string spec) {
string[] tokens = spec.Split(' ');
string[] numbers = tokens[0].Split('-');
int min = int.Parse(numbers[0]);
int max = int.Parse(numbers[1]);
char required = tokens[1][0];
string password = tokens[2];
int count = 0;
for (int i = 0; i < password.Length; i++) {
if (password[i] == required) {
count++;
}
}
return min <= count && count <= max;
}
static bool IsPasswordValid2(string spec) {
string[] tokens = spec.Split(' ');
string[] numbers = tokens[0].Split('-');
int lowIndex = int.Parse(numbers[0]) - 1;
int highIndex = int.Parse(numbers[1]) - 1;
char required = tokens[1][0];
string password = tokens[2];
return
(password[lowIndex] == required && password[highIndex] != required) ||
(password[lowIndex] != required && password[highIndex] == required);
}
static int Part1() {
return File.ReadAllLines(Util.RootDir + "day02.txt").Count(IsPasswordValid1);
}
static int Part2() {
return File.ReadAllLines(Util.RootDir + "day02.txt").Count(IsPasswordValid2);
}
[Fact]
public static void Test() {
Assert.True(IsPasswordValid1("1-3 a: abcde"));
Assert.False(IsPasswordValid1("1-3 b: cdefg"));
Assert.True(IsPasswordValid1("2-9 c: ccccccccc"));
Assert.Equal(603, Part1());
Assert.True(IsPasswordValid2("1-3 a: abcde"));
Assert.False(IsPasswordValid2("1-3 b: cdefg"));
Assert.False(IsPasswordValid2("2-9 c: ccccccccc"));
Assert.Equal(404, Part2());
}
}
}