You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

  1. using System;
  2. using static System.Console;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using Xunit;
  7. namespace AdventOfCode {
  8. public class Day02 {
  9. static bool IsPasswordValid1(string spec) {
  10. string[] tokens = spec.Split(' ');
  11. string[] numbers = tokens[0].Split('-');
  12. int min = int.Parse(numbers[0]);
  13. int max = int.Parse(numbers[1]);
  14. char required = tokens[1][0];
  15. string password = tokens[2];
  16. int count = 0;
  17. for (int i = 0; i < password.Length; i++) {
  18. if (password[i] == required) {
  19. count++;
  20. }
  21. }
  22. return min <= count && count <= max;
  23. }
  24. static bool IsPasswordValid2(string spec) {
  25. string[] tokens = spec.Split(' ');
  26. string[] numbers = tokens[0].Split('-');
  27. int lowIndex = int.Parse(numbers[0]) - 1;
  28. int highIndex = int.Parse(numbers[1]) - 1;
  29. char required = tokens[1][0];
  30. string password = tokens[2];
  31. return
  32. (password[lowIndex] == required && password[highIndex] != required) ||
  33. (password[lowIndex] != required && password[highIndex] == required);
  34. }
  35. static int Part1() {
  36. return File.ReadAllLines(Util.RootDir + "day02.txt").Count(IsPasswordValid1);
  37. }
  38. static int Part2() {
  39. return File.ReadAllLines(Util.RootDir + "day02.txt").Count(IsPasswordValid2);
  40. }
  41. [Fact]
  42. public static void Test() {
  43. Assert.True(IsPasswordValid1("1-3 a: abcde"));
  44. Assert.False(IsPasswordValid1("1-3 b: cdefg"));
  45. Assert.True(IsPasswordValid1("2-9 c: ccccccccc"));
  46. Assert.Equal(603, Part1());
  47. Assert.True(IsPasswordValid2("1-3 a: abcde"));
  48. Assert.False(IsPasswordValid2("1-3 b: cdefg"));
  49. Assert.False(IsPasswordValid2("2-9 c: ccccccccc"));
  50. Assert.Equal(404, Part2());
  51. }
  52. }
  53. }