| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using Day3;
- if (args.Length < 1)
- {
- Console.WriteLine("Requires 1 args: inputFileName");
- return -1;
- }
- var inputFile = args[0];
- var parser = new SchematicParser();
- var set = new Dictionary<Point2D, IList<Cell>>();
- var cellList = new List<Cell>();
- var tokens = parser.Parse(inputFile).ToList();
- foreach (var token in tokens)
- {
- if (token is SymbolToken sym)
- {
- var cell = new Cell(sym);
- cellList.Add(cell);
- foreach (var p in sym.Position.SurroundingAndSelf())
- {
- if (!set.ContainsKey(p))
- {
- set[p] = new List<Cell>();
- }
-
- set[p].Add(cell);
- }
- }
- }
- Console.WriteLine();
- for (var y = 0; y < parser.Height; y++)
- {
- for (var x = 0; x < parser.Width; x++)
- {
- var p = new Point2D(x, y);
- if (set.TryGetValue(p, out IList<Cell>? cells))
- {
- Console.Write(cells.Count);
- }
- else
- {
- Console.Write("-");
- }
- }
- Console.WriteLine("|");
- }
- var sum = 0;
- foreach (var token in tokens)
- {
- if (token is NumberToken num)
- {
- sum += IsTouchingSymbol(set, num);
- }
- }
- Console.WriteLine();
- Console.WriteLine($"Sum: {sum}");
- sum = cellList.Select(c => c.GearRatio()).Sum();
- Console.WriteLine();
- Console.WriteLine($"Gear ratio sum: {sum}");
- return 0;
- int IsTouchingSymbol(Dictionary<Point2D, IList<Cell>> set, NumberToken num)
- {
- var touching = false;
- var cellMap = new HashSet<Cell>();
- for (var w = 0; w < num.Length; w++)
- {
- var p = num.Position with { X = num.Position.X + w };
- if (set.TryGetValue(p, out IList<Cell>? cells))
- {
- touching = true;
- foreach (var cell in cells)
- {
- if (!cellMap.Contains(cell))
- {
- cell.Numbers.Add(num);
- cellMap.Add(cell);
- }
- }
- }
- }
- return touching ? num.Value : 0;
- }
|