| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System;
- using System.IO;
- namespace D09._2
- {
- class Program
- {
- static bool TryGetToken(string input, ref int index, out long length)
- {
- length = 0;
- int idx = index;
- if (IsCompressionToken(input, out int strlen, out int repetition, ref idx) == false)
- return false;
- long sublength = 0;
- for (var i = idx; i < idx + strlen; i++)
- {
- if (TryGetToken(input, ref i, out long len))
- sublength += len;
- else sublength++;
- }
- idx += strlen;
- index = idx - 1;
- length = sublength * repetition;
- return true;
- }
- private static bool IsCompressionToken(string input, out int strlen, out int repetition, ref int idx)
- {
- strlen = 0;
- repetition = 0;
- if (input[idx++] != '(') return false;
- int nindex = idx;
- while (input[idx] >= '0' && input[idx] <= '9') idx++;
- strlen = int.Parse(input.Substring(nindex, idx - nindex));
- if (input[idx++] != 'x') return false;
- nindex = idx;
- while (input[idx] >= '0' && input[idx] <= '9') idx++;
- repetition = int.Parse(input.Substring(nindex, idx - nindex));
- if (input[idx++] != ')') return false;
- return true;
- }
- static void Main(string[] args)
- {
- if (args.Length < 1) throw new ArgumentException();
- if (File.Exists(args[0]) == false) throw new FileNotFoundException();
- long totalLength = 0;
- var text = File.ReadAllText(args[0]);
- for (var i = 0; i < text.Length; ++i)
- {
- if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t') continue;
- if (TryGetToken(text, ref i, out long length))
- totalLength += length;
- else totalLength++;
- }
- Console.WriteLine(totalLength);
- }
- }
- }
|