Program.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D7._1
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. if (args.Length < 1) return;
  12. if (File.Exists(args[0]) == false) return;
  13. var file = File.OpenText(args[0]);
  14. var builder = new Dictionary<char, Node>();
  15. do
  16. {
  17. var line = file.ReadLine();
  18. if (line == null) break;
  19. AddDependency(builder, line);
  20. } while (true);
  21. string path = GetPath(builder);
  22. Console.WriteLine(path);
  23. }
  24. private static string GetPath(Dictionary<char, Node> builder)
  25. {
  26. List<Node> possibleValues = builder.Select(s => s.Value).ToList();
  27. string path = "";
  28. while (possibleValues.Count() > 0)
  29. {
  30. var first = possibleValues
  31. .OrderBy(c => c.Name)
  32. .FirstOrDefault(c => c.Dependencies.Count == 0);
  33. path += first.Name;
  34. RemoveDependency(possibleValues, first);
  35. }
  36. return path;
  37. }
  38. private static void RemoveDependency(List<Node> possibleValues, Node first)
  39. {
  40. possibleValues.Remove(first);
  41. foreach (var next in possibleValues)
  42. next.Dependencies.Remove(first);
  43. }
  44. private static void AddDependency(Dictionary<char, Node> builder, string line)
  45. {
  46. var left = line.Substring(5, 1)[0];
  47. var right = line.Substring(36, 1)[0];
  48. if (builder.ContainsKey(left) == false)
  49. builder.Add(left, new Node
  50. {
  51. Name = left,
  52. Dependencies = new List<Node>()
  53. });
  54. if (builder.ContainsKey(right) == false)
  55. builder.Add(right, new Node
  56. {
  57. Name = right,
  58. Dependencies = new List<Node>()
  59. });
  60. var nleft = builder[left];
  61. var nright = builder[right];
  62. nright.Dependencies.Add(nleft);
  63. }
  64. public class Node
  65. {
  66. public char Name { get; set; }
  67. public List<Node> Dependencies { get; set; }
  68. public override int GetHashCode()
  69. {
  70. return Name.GetHashCode();
  71. }
  72. public override bool Equals(object obj)
  73. {
  74. var o = obj as Node;
  75. return Name.Equals(o.Name);
  76. }
  77. }
  78. }
  79. }