| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- namespace D7._1
- {
- class Program
- {
- static void Main(string[] args)
- {
- if (args.Length < 1) return;
- if (File.Exists(args[0]) == false) return;
- var file = File.OpenText(args[0]);
- var builder = new Dictionary<char, Node>();
- do
- {
- var line = file.ReadLine();
- if (line == null) break;
- AddDependency(builder, line);
- } while (true);
- string path = GetPath(builder);
- Console.WriteLine(path);
- }
- private static string GetPath(Dictionary<char, Node> builder)
- {
- List<Node> possibleValues = builder.Select(s => s.Value).ToList();
- string path = "";
- while (possibleValues.Count() > 0)
- {
- var first = possibleValues
- .OrderBy(c => c.Name)
- .FirstOrDefault(c => c.Dependencies.Count == 0);
- path += first.Name;
- RemoveDependency(possibleValues, first);
- }
- return path;
- }
- private static void RemoveDependency(List<Node> possibleValues, Node first)
- {
- possibleValues.Remove(first);
- foreach (var next in possibleValues)
- next.Dependencies.Remove(first);
- }
- private static void AddDependency(Dictionary<char, Node> builder, string line)
- {
- var left = line.Substring(5, 1)[0];
- var right = line.Substring(36, 1)[0];
- if (builder.ContainsKey(left) == false)
- builder.Add(left, new Node
- {
- Name = left,
- Dependencies = new List<Node>()
- });
- if (builder.ContainsKey(right) == false)
- builder.Add(right, new Node
- {
- Name = right,
- Dependencies = new List<Node>()
- });
- var nleft = builder[left];
- var nright = builder[right];
- nright.Dependencies.Add(nleft);
- }
- public class Node
- {
- public char Name { get; set; }
- public List<Node> Dependencies { get; set; }
- public override int GetHashCode()
- {
- return Name.GetHashCode();
- }
- public override bool Equals(object obj)
- {
- var o = obj as Node;
- return Name.Equals(o.Name);
- }
- }
- }
- }
|