Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- namespace App
- {
- class Program
- {
- static IEnumerable<string> ToLines(IEnumerable<object> list, int spaces = 0)
- {
- foreach (object obj in list)
- {
- string pre = string.Join(string.Empty, Enumerable.Repeat(" ", spaces));
- if (obj is int)
- yield return pre + obj;
- else
- {
- var kvp = (KeyValuePair<int, List<object>>)obj;
- yield return string.Format("{0}repeat {1}:", pre, kvp.Key);
- foreach (string line in ToLines(kvp.Value, spaces + 4))
- yield return line;
- }
- }
- }
- static bool Compare(object obj1, object obj2)
- {
- if (obj1 is int && !(obj2 is int)) return false;
- if (obj2 is int && !(obj1 is int)) return false;
- if (obj1 is int && obj2 is int)
- return (int) obj1 == (int) obj2;
- var kvp1 = (KeyValuePair<int, List<object>>)obj1;
- var kvp2 = (KeyValuePair<int, List<object>>)obj2;
- if (kvp1.Key != kvp2.Key) return false;
- if (kvp1.Value.Count != kvp2.Value.Count) return false;
- return !kvp1.Value.Where((t, i) => !Compare(t, kvp2.Value[i])).Any();
- }
- static IEnumerable<object> Process(IEnumerable<object> source, int depth)
- {
- var list = new List<object>(source);
- var result = new List<object>(list.Count);
- bool sublistsCreated = false;
- for (int startIdx = 0; startIdx < list.Count; ++startIdx)
- {
- var counts = Enumerable.Repeat(0, depth).ToList();
- for (int rangeLen = 1;
- rangeLen <= depth && startIdx + rangeLen <= list.Count;
- ++rangeLen)
- {
- int count = 0;
- bool eq;
- do
- {
- ++count;
- eq = true;
- for (int i = 0; i < rangeLen; ++i)
- {
- int idx0 = startIdx + i;
- int idx1 = startIdx + rangeLen*count + i;
- if (idx1 >= list.Count)
- {
- eq = false;
- break;
- }
- if (!Compare(list[idx0], list[idx1]))
- {
- eq = false;
- break;
- }
- }
- } while (eq);
- counts[rangeLen - 1] = count;
- }
- int max = counts.Max();
- int maxDepth = counts.IndexOf(max) + 1;
- if (max == 1)
- result.Add(list[startIdx]);
- else
- {
- var subList = new List<object>(maxDepth);
- for (int i = 0; i < maxDepth; ++i)
- subList.Add(list[startIdx + i]);
- subList = Process(subList, depth).ToList();
- result.Add(new KeyValuePair<int, List<object>>(max, subList));
- sublistsCreated = true;
- startIdx += maxDepth * max - 1;
- }
- }
- if (sublistsCreated)
- result = Process(result, depth).ToList();
- return result;
- }
- static void Main()
- {
- const string inputFileName = @"input.txt";
- const string outputFileName = @"output.txt";
- var source = (from line in File.ReadAllLines(inputFileName)
- select (object)int.Parse(line.Trim())).ToList();
- var result = Process(source, source.Count);
- File.WriteAllLines(outputFileName, ToLines(result));
- foreach (var line in ToLines(result))
- Console.WriteLine(line);
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment