Program.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.IO;
  3. namespace D09._1
  4. {
  5. class Program
  6. {
  7. static bool TryGetToken(string input, ref int index, out int length, out int repetition)
  8. {
  9. length = 0;
  10. repetition = 0;
  11. int idx = index;
  12. if (input[idx++] != '(') return false;
  13. int nindex = idx;
  14. while (input[idx] >= '0' && input[idx] <= '9') idx++;
  15. length = int.Parse(input.Substring(nindex, idx - nindex));
  16. if (input[idx++] != 'x') return false;
  17. nindex = idx;
  18. while (input[idx] >= '0' && input[idx] <= '9') idx++;
  19. repetition = int.Parse(input.Substring(nindex, idx - nindex));
  20. if (input[idx++] != ')') return false;
  21. idx += length;
  22. index = idx - 1;
  23. length *= repetition;
  24. return true;
  25. }
  26. static void Main(string[] args)
  27. {
  28. if (args.Length < 1) throw new ArgumentException();
  29. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  30. int totalLength = 0;
  31. var text = File.ReadAllText(args[0]);
  32. for (var i = 0; i < text.Length; ++i)
  33. {
  34. if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t') continue;
  35. if (TryGetToken(text, ref i, out int length, out int repetition))
  36. totalLength += length;
  37. else totalLength++;
  38. }
  39. Console.WriteLine(totalLength);
  40. }
  41. }
  42. }