public CircularList InsertNext(CircularList node) { if (next == this) // only one node in the circular list { // Easy to handle, after the two lines of executions, // there will be two nodes in the circular list node.next = this; next = node; } else { // Insert in the middle (node.next, next) = (next, node); } return(node); }
public CircularList(int value) { data = value; next = this; }
public void Traverse(CircularList node, Action <CircularList> action) { if (node == null) { node = this; } var startnode = node; do { action(node); node = node.next; } while (node != startnode); }
protected override string SolvePartTwo() { var max_cup = 1000000; var ind = new Dictionary <int, CircularList>(); var head = new CircularList(_cups[0]); ind[_cups[0]] = head; var curr = head; foreach (var cup in _cups) { if (cup == _cups[0]) { continue; } curr = curr.InsertNext(cup); ind[cup] = curr; } for (int i = 10; i <= max_cup; i++) { curr = curr.InsertNext(i); ind[i] = curr; } var currCup = head; for (int i = 0; i < 10000000; i++) { var c1 = currCup.DeleteNext(); var c2 = currCup.DeleteNext(); var c3 = currCup.DeleteNext(); var target = Subtract(currCup.Data, new[] { c1.Data, c2.Data, c3.Data }, max_cup); var targetNode = ind[target]; targetNode.InsertNext(c3); targetNode.InsertNext(c2); targetNode.InsertNext(c1); currCup = currCup.Next; } var firstStar = ind[1].Next; var secondStar = ind[1].Next.Next; long mul = (long)firstStar.Data * (long)secondStar.Data; return(mul.ToString()); }
protected override string SolvePartOne() { var max_cup = 9; var ind = new Dictionary <int, CircularList>(); var head = new CircularList(_cups[0]); ind[_cups[0]] = head; var curr = head; foreach (var cup in _cups) { if (cup == _cups[0]) { continue; } curr = curr.InsertNext(cup); ind[cup] = curr; } var currCupNum = head.Data; for (int i = 0; i < 100; i++) { var currentCup = ind[currCupNum]; var c1 = currentCup.DeleteNext(); var c2 = currentCup.DeleteNext(); var c3 = currentCup.DeleteNext(); var target = Subtract(currCupNum, new[] { c1.Data, c2.Data, c3.Data }); var targetNode = ind[target]; targetNode.InsertNext(c3); targetNode.InsertNext(c2); targetNode.InsertNext(c1); currCupNum = currentCup.Next.Data; } var start = ind[1].Next; var sb = new StringBuilder(); start.Traverse(start, node => sb.Append(node.Data)); return(sb.ToString().Replace("1", "")); }
public CircularList DeleteNext() { if (next == this) { Console.WriteLine( "\nThe node can not be deleted as there is only one node in the circular list"); return(null); } var node = next; next = next.next; return(node); }
public CircularList() { data = 0; next = this; }