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.

92 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 Day06 {
  9. static int CountAnswers1(string[] input) {
  10. int total = 0;
  11. var groupAnswers = new HashSet<char>();
  12. foreach (string line in input) {
  13. if (line == "") {
  14. total += groupAnswers.Count();
  15. groupAnswers.Clear();
  16. continue;
  17. }
  18. foreach (char c in line) {
  19. groupAnswers.Add(c);
  20. }
  21. }
  22. total += groupAnswers.Count();
  23. return total;
  24. }
  25. static int CountAnswers2(string[] input) {
  26. int total = 0;
  27. var groupAnswers = new HashSet<char>();
  28. int groupSize = 0;
  29. foreach (string line in input) {
  30. if (line == "") {
  31. total += groupAnswers.Count();
  32. groupAnswers.Clear();
  33. groupSize = 0;
  34. continue;
  35. }
  36. groupSize++;
  37. if (groupSize == 1) {
  38. foreach (char c in line) {
  39. groupAnswers.Add(c);
  40. }
  41. } else {
  42. foreach (char c in groupAnswers) {
  43. if (!line.Contains(c)) {
  44. groupAnswers.Remove(c);
  45. }
  46. }
  47. }
  48. }
  49. total += groupAnswers.Count();
  50. return total;
  51. }
  52. static int Part1() {
  53. string[] input = File.ReadAllLines(Util.RootDir + "day06.txt");
  54. return CountAnswers1(input);
  55. }
  56. static int Part2() {
  57. string[] input = File.ReadAllLines(Util.RootDir + "day06.txt");
  58. return CountAnswers2(input);
  59. }
  60. [Fact]
  61. public static void Test() {
  62. string[] example =
  63. @"abc
  64. a
  65. b
  66. c
  67. ab
  68. ac
  69. a
  70. a
  71. a
  72. a
  73. b".Split('\n');
  74. Assert.Equal(11, CountAnswers1(example));
  75. Assert.Equal(6, CountAnswers2(example));
  76. Assert.Equal(6947, Part1());
  77. Assert.Equal(3398, Part2());
  78. }
  79. }
  80. }