Program.cs 2.0 KB

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