Program.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace D19._1
  5. {
  6. public class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. if (args.Length < 1) throw new ArgumentException();
  11. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  12. string input;
  13. List<(string, string)> replacements;
  14. ParseFile(args, out input, out replacements);
  15. var molecules = TestMolecules(input, replacements);
  16. Console.WriteLine($"The answer is : {molecules.Count}");
  17. }
  18. public static void ParseFile(string[] args, out string input, out List<(string, string)> replacements)
  19. {
  20. input = string.Empty;
  21. replacements = new List<(string, string)>();
  22. using (var file = File.OpenText(args[0]))
  23. {
  24. while (true)
  25. {
  26. var line = file.ReadLine();
  27. if (line == null) break;
  28. if (line == string.Empty) continue;
  29. var lr = line.Split(" => ");
  30. if (lr.Length == 2) replacements.Add((lr[0], lr[1]));
  31. else input = lr[0];
  32. }
  33. }
  34. }
  35. public static HashSet<string> TestMolecules(string input, List<(string, string)> replacements)
  36. {
  37. HashSet<string> molecules = new HashSet<string>();
  38. foreach ((string orig, string replace) in replacements)
  39. {
  40. int index = 0;
  41. while (true)
  42. {
  43. index = input.IndexOf(orig, index);
  44. if (index == -1) break;
  45. string molecule = input.Substring(0, index) + replace + input.Substring(index + orig.Length);
  46. molecules.Add(molecule);
  47. index++;
  48. }
  49. }
  50. return molecules;
  51. }
  52. }
  53. }