|
| 1 | +package adventofcode; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.LinkedHashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +/** |
| 8 | + * Why Did you create this class? what does it do? |
| 9 | + */ |
| 10 | +@SuppressWarnings("Duplicates") public class Spinlock_17 { |
| 11 | + public static void main(String[] args) { |
| 12 | + System.out.println(solve2(301)); |
| 13 | + } |
| 14 | + |
| 15 | + private static int solve(int n) { |
| 16 | + if (n <= 0) |
| 17 | + return 0; |
| 18 | + Map<Node, Integer> map = new HashMap<>(); |
| 19 | + Node current = new Node(0, null); |
| 20 | + Node root = current; |
| 21 | + map.put(current, 0); |
| 22 | + Node ipNode; |
| 23 | + for (int i = 1; i <= 2017; i++) { |
| 24 | + int ip = (n + map.get(current)) % map.size(); |
| 25 | + ipNode = findByIndex(root, ip); |
| 26 | + ipNode.next = new Node(i, ipNode.next); |
| 27 | + map.put(ipNode.next, ip + 1); |
| 28 | + current = ipNode.next; |
| 29 | + } |
| 30 | + return current.next.value; |
| 31 | + } |
| 32 | + |
| 33 | + private static int solve2(int n) { |
| 34 | + if (n <= 0) |
| 35 | + return 0; |
| 36 | + int k = 0; |
| 37 | + int currentIndex = 0; |
| 38 | + for (int i = 1; i <= 50_000_000; i++) { |
| 39 | + currentIndex = (n + currentIndex) % i + 1; |
| 40 | + if (currentIndex - 1 == 0) { |
| 41 | + k = i; |
| 42 | + } |
| 43 | + } |
| 44 | + return k; |
| 45 | + } |
| 46 | + |
| 47 | + private static void printNode(Node root) { |
| 48 | + while (root != null) { |
| 49 | + System.out.print(root.value + " "); |
| 50 | + root = root.next; |
| 51 | + } |
| 52 | + System.out.println(); |
| 53 | + } |
| 54 | + |
| 55 | + private static Node findByIndex(Node root, int ip) { |
| 56 | + int i = 0; |
| 57 | + while (i < ip) { |
| 58 | + root = root.next; |
| 59 | + i++; |
| 60 | + } |
| 61 | + return root; |
| 62 | + } |
| 63 | + |
| 64 | + private static class Node { |
| 65 | + int value; |
| 66 | + Node next; |
| 67 | + |
| 68 | + public Node(int value, Node next) { |
| 69 | + this.value = value; |
| 70 | + this.next = next; |
| 71 | + } |
| 72 | + |
| 73 | + @Override public boolean equals(Object o) { |
| 74 | + if (this == o) |
| 75 | + return true; |
| 76 | + if (o == null || getClass() != o.getClass()) |
| 77 | + return false; |
| 78 | + |
| 79 | + Node node = (Node) o; |
| 80 | + |
| 81 | + if (value != node.value) |
| 82 | + return false; |
| 83 | + return next != null ? next.equals(node.next) : node.next == null; |
| 84 | + } |
| 85 | + |
| 86 | + @Override public int hashCode() { |
| 87 | + return value; |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments