Skip to content

Commit

Permalink
make part1 solution more readable (hopefully)
Browse files Browse the repository at this point in the history
  • Loading branch information
zebalu committed Dec 20, 2023
1 parent f6b9f37 commit ec83094
Showing 1 changed file with 17 additions and 20 deletions.
37 changes: 17 additions & 20 deletions aoc2023/src/main/java/io/github/zebalu/aoc2023/days/Day20.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
package io.github.zebalu.aoc2023.days;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -71,6 +65,12 @@ private enum Pulse {
}

private record Counter(AtomicLong lowCounter, AtomicLong highCounter) {
void count(Pulse pulse) {
switch(pulse) {
case LOW -> lowCounter.incrementAndGet();
case HIGH -> highCounter.incrementAndGet();
}
}
}

private static class Node {
Expand Down Expand Up @@ -133,26 +133,23 @@ void reset() {
}

private record Machine(Map<String, Node> setup, Counter counter) {
private static final String STOP_NODE = "rx";
boolean push() {
Queue<Message> messageQueue = new LinkedList<>();
counter.lowCounter.incrementAndGet();
messageQueue.add(new Message("button", Node.BROADCASTER, Pulse.LOW));
while (!messageQueue.isEmpty()) {
Message curr = messageQueue.poll();
if (setup.containsKey(curr.target())) {
var nexts = setup.get(curr.target()).recieve(curr.from(), curr.pulse());
nexts.forEach(msg -> {
if (msg.pulse() == Pulse.LOW) {
counter.lowCounter.incrementAndGet();
} else {
counter.highCounter.incrementAndGet();
}
messageQueue.add(msg);
});
}
if (curr.target.equals("rx") && curr.pulse == Pulse.LOW) {
if (curr.target.equals(STOP_NODE) && curr.pulse == Pulse.LOW) {
return true;
}
setup.computeIfPresent(curr.target, (key, node)->{
node.recieve(curr.from(), curr.pulse()).forEach(msg -> {
counter.count(msg.pulse());
messageQueue.add(msg);
});
return node;
});
}
return false;
}
Expand Down

0 comments on commit ec83094

Please sign in to comment.