Skip to content

Commit

Permalink
feat: d20p1 example
Browse files Browse the repository at this point in the history
  • Loading branch information
jortrr committed Aug 11, 2024
1 parent e3c9c62 commit b218a8d
Show file tree
Hide file tree
Showing 3 changed files with 289 additions and 3 deletions.
12 changes: 12 additions & 0 deletions .aocf/cache/aoc2023_20.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"year": 2023,
"day": 20,
"level": "first",
"title": "Pulse Propagation",
"stars": null,
"solution": {},
"input": "%jb -> ps\n%cm -> ps, tm\n%sl -> ml, cp\n%qr -> ml\n%hf -> kh, jg\n%jg -> kk\n%jt -> pq\n%qv -> kv\n%rj -> mm, kh\n%kf -> xt\n%kx -> vk, mk\n%dq -> qn\n&ps -> xc, mq, jt, zs, sr, nt, pq\n%jk -> hh, ps\n%rr -> mk, nh\n%hs -> kh, mb\n%mg -> mk, kf\n%xt -> dq, mk\n&xc -> zh\n%mq -> nt\n%nh -> bm\n&ml -> bp, gd, qv, kq\n%md -> hs\n%vk -> mk, vl\n%mm -> kh\n&th -> zh\n&zh -> rx\n%kc -> ps, jk\n%kk -> dm\n%jn -> ll, ml\n&pd -> zh\n&kh -> jg, qx, md, th, hf, dm, kk\n%pp -> kh, md\n%zf -> ml, bd\n%qx -> pp\n&mk -> kf, qn, nh, pd, dq, mg, bm\n%qn -> rr\n%mb -> qb, kh\n%nt -> jt\n%vl -> zk, mk\n%gd -> ml, rm\n%hh -> ps, jb\n%tm -> ps, mq\n%kv -> jn, ml\n%zs -> kc\n%ll -> ml, kq\n%cp -> qv, ml\n%rm -> sl, ml\n%bd -> qr, ml\n%dm -> qx\n%qb -> rj, kh\n%pq -> zs\n%bm -> kx\n%sr -> cm, ps\n%zk -> mk\nbroadcaster -> sr, gd, mg, hf\n%kq -> zf\n&bp -> zh\n",
"brief": {
"first": "With your help, the Elves manage to find the right parts and fix all of the machines. Now, they just need to send the command to boot up the machines and get the sand flowing again.\n\nThe machines are far apart and wired together with long *cables*. The cables don't connect to the machines directly, but rather to communication *modules* attached to the machines that perform various initialization tasks and also act as communication relays.\n\nModules communicate using *pulses*. Each pulse is either a *high pulse* or a *low pulse*. When a module sends a pulse, it sends that type of pulse to each module in its list of *destination modules*.\n\nThere are several different types of modules:\n\n*Flip-flop* modules (prefix `%`) are either *on* or *off*; they are initially *off*. If a flip-flop module receives a high pulse, it is ignored and nothing happens. However, if a flip-flop module receives a low pulse, it *flips between on and off*. If it was off, it turns on and sends a high pulse. If it was on, it turns off and sends a low pulse.\n\n*Conjunction* modules (prefix `&`) *remember* the type of the most recent pulse received from *each* of their connected input modules; they initially default to remembering a *low pulse* for each input. When a pulse is received, the conjunction module first updates its memory for that input. Then, if it remembers *high pulses* for all inputs, it sends a *low pulse*; otherwise, it sends a *high pulse*.\n\nThere is a single *broadcast module* (named `broadcaster`). When it receives a pulse, it sends the same pulse to all of its destination modules.\n\nHere at Desert Machine Headquarters, there is a module with a single button on it called, aptly, the *button module*. When you push the button, a single *low pulse* is sent directly to the `broadcaster` module.\n\nAfter pushing the button, you must wait until all pulses have been delivered and fully handled before pushing it again. Never push the button if modules are still processing pulses.\n\nPulses are always processed *in the order they are sent*. So, if a pulse is sent to modules `a`, `b`, and `c`, and then module `a` processes its pulse and sends more pulses, the pulses sent to modules `b` and `c` would have to be handled first.\n\nThe module configuration (your puzzle input) lists each module. The name of the module is preceded by a symbol identifying its type, if any. The name is then followed by an arrow and a list of its destination modules. For example:\n\n```\nbroadcaster -> a, b, c\n%a -> b\n%b -> c\n%c -> inv\n&inv -> a\n\n```\n\nIn this module configuration, the broadcaster has three destination modules named `a`, `b`, and `c`. Each of these modules is a flip-flop module (as indicated by the `%` prefix). `a` outputs to `b` which outputs to `c` which outputs to another module named `inv`. `inv` is a conjunction module (as indicated by the `&` prefix) which, because it has only one input, acts like an inverter (it sends the opposite of the pulse type it receives); it outputs to `a`.\n\nBy pushing the button once, the following pulses are sent:\n\n```\nbutton -low-> broadcaster\nbroadcaster -low-> a\nbroadcaster -low-> b\nbroadcaster -low-> c\na -high-> b\nb -high-> c\nc -high-> inv\ninv -low-> a\na -low-> b\nb -low-> c\nc -low-> inv\ninv -high-> a\n\n```\n\nAfter this sequence, the flip-flop modules all end up *off*, so pushing the button again repeats the same sequence.\n\nHere's a more interesting example:\n\n```\nbroadcaster -> a\n%a -> inv, con\n&inv -> b\n%b -> con\n&con -> output\n\n```\n\nThis module configuration includes the `broadcaster`, two flip-flops (named `a` and `b`), a single-input conjunction module (`inv`), a multi-input conjunction module (`con`), and an untyped module named `output` (for testing purposes). The multi-input conjunction module `con` watches the two flip-flop modules and, if they're both on, sends a *low pulse* to the `output` module.\n\nHere's what happens if you push the button once:\n\n```\nbutton -low-> broadcaster\nbroadcaster -low-> a\na -high-> inv\na -high-> con\ninv -low-> b\ncon -high-> output\nb -high-> con\ncon -low-> output\n\n```\n\nBoth flip-flops turn on and a low pulse is sent to `output`! However, now that both flip-flops are on and `con` remembers a high pulse from each of its two inputs, pushing the button a second time does something different:\n\n```\nbutton -low-> broadcaster\nbroadcaster -low-> a\na -low-> inv\na -low-> con\ninv -high-> b\ncon -high-> output\n\n```\n\nFlip-flop `a` turns off! Now, `con` remembers a low pulse from module `a`, and so it sends only a high pulse to `output`.\n\nPush the button a third time:\n\n```\nbutton -low-> broadcaster\nbroadcaster -low-> a\na -high-> inv\na -high-> con\ninv -low-> b\ncon -low-> output\nb -low-> con\ncon -high-> output\n\n```\n\nThis time, flip-flop `a` turns on, then flip-flop `b` turns off. However, before `b` can turn off, the pulse sent to `con` is handled first, so it *briefly remembers all high pulses* for its inputs and sends a low pulse to `output`. After that, flip-flop `b` turns off, which causes `con` to update its state and send a high pulse to `output`.\n\nFinally, with `a` on and `b` off, push the button a fourth time:\n\n```\nbutton -low-> broadcaster\nbroadcaster -low-> a\na -low-> inv\na -low-> con\ninv -high-> b\ncon -high-> output\n\n```\n\nThis completes the cycle: `a` turns off, causing `con` to remember only low pulses and restoring all modules to their original states.\n\nTo get the cables warmed up, the Elves have pushed the button `1000` times. How many pulses got sent as a result (including the pulses sent by the button itself)?\n\nIn the first example, the same thing happens every time the button is pushed: `8` low pulses and `4` high pulses are sent. So, after pushing the button `1000` times, `8000` low pulses and `4000` high pulses are sent. Multiplying these together gives `*32000000*`.\n\nIn the second example, after pushing the button `1000` times, `4250` low pulses and `2750` high pulses are sent. Multiplying these together gives `*11687500*`.\n\nConsult your module configuration; determine the number of low pulses and high pulses that would be sent after pushing the button `1000` times, waiting for all pulses to be fully handled after each push of the button. *What do you get if you multiply the total number of low pulses sent by the total number of high pulses sent?*\n\nTo begin, [get your puzzle input](20/input).\n\nAnswer:"
}
}
5 changes: 4 additions & 1 deletion src/aoc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fs::read_to_string;
use std::{collections::VecDeque, fs::read_to_string};

use serde_json::Value;

Expand All @@ -10,6 +10,9 @@ pub type Int = i64;
/// Default Grid type
pub type Grid<T> = Vec<Vec<T>>;

/// Default Queue type
pub type Queue<T> = VecDeque<T>;

pub fn get(year: i32, day: u32) -> String {
let aoc_json_cache_path = format!(".aocf/cache/aoc{}_{:02}.json", year, day);
let aoc_json_cache = aocf::Aoc::load_json_from(&aoc_json_cache_path);
Expand Down
275 changes: 273 additions & 2 deletions src/day20.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,274 @@
fn main() {
println!("Hello, World! from src/day20.rs!");
mod problem;

use nom::character::complete::space1;
use problem::*;

type Name = String;
type Modules = HashMap<Name, Module>;
type Memory = HashMap<Name, PulseKind>;

#[derive(Copy, Clone)]
enum State {
On,
Off,
}

impl Into<PulseKind> for State {
fn into(self) -> PulseKind {
match self {
State::On => PulseKind::High,
State::Off => PulseKind::Low,
}
}
}

impl State {
fn flip(&self) -> State {
use State::*;
match &self {
On => Off,
Off => On,
}
}
}

#[derive(Clone)]
enum ModuleKind {
FlipFlop(State),
Conjuction(Memory),
Output,
Broadcaster,
}

impl ModuleKind {
fn from_char(c: char) -> ModuleKind {
use ModuleKind::*;
match c {
'%' => FlipFlop(State::Off),
'&' => Conjuction(Memory::new()),
_ => unreachable!(),
}
}
}

#[derive(Clone)]
struct Module {
kind: ModuleKind,
name: Name,
destinations: Vec<Name>,
}

impl Parse for Module {
fn parse(input: Input) -> Self {
Module::parse_module(&input).unwrap().1
}
}

impl Module {
fn parse_module(input: &str) -> IResult<&str, Module> {
// Parsing "broadcaster" as a special case
let broadcaster_parser = map(tag("broadcaster"), |_| Module {
kind: ModuleKind::Broadcaster,
name: "broadcaster".to_string(),
destinations: Vec::new(),
});

// Parsing a symbolic module with a special character and a name
let symbolic_module_parser = map(
tuple((one_of("%&"), alpha1)),
|(symbol, name): (char, &str)| Module {
kind: ModuleKind::from_char(symbol),
name: name.to_string(),
destinations: Vec::new(),
},
);

let (rest, mut module) = alt((broadcaster_parser, symbolic_module_parser))(input)?;
let (rest, _) = tuple((space1, tag("->"), space1))(rest)?;
let (rest, destination) = separated_list1(tag(", "), alpha1)(rest)?;
module.destinations = destination.iter().map(|s| s.to_string()).collect();

Ok((rest, module))
}

fn generate_pulses(&self, kind: PulseKind) -> Vec<Pulse> {
self.destinations
.iter()
.map(|name| Pulse {
from: self.name.clone(),
to: name.clone(),
kind,
})
.collect()
}

fn handle_pulse(&mut self, pulse: Pulse, system: &mut System) {
use ModuleKind::*;
match &mut self.kind {
FlipFlop(state) => {
if pulse.kind == PulseKind::Low {
*state = state.flip();
let state = *state;
system.enqueue_pulses(self.generate_pulses(state.into()));
}
}
Conjuction(memory) => {
memory.insert(pulse.from, pulse.kind);
let new_pulse = if memory.values().all(|kind| *kind == PulseKind::High) {
PulseKind::Low
} else {
PulseKind::High
};
system.enqueue_pulses(self.generate_pulses(new_pulse));
}
Broadcaster => system.enqueue_pulses(self.generate_pulses(pulse.kind)),
_ => unreachable!(),
}
}
}

#[derive(Copy, Clone, PartialEq, Debug)]
enum PulseKind {
High,
Low,
}

struct Pulse {
from: Name,
to: Name,
kind: PulseKind,
}

impl Debug for Pulse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} -{:?}-> {}", self.from, self.kind, self.to)
}
}

/// A System of wired up Modules that can send pulses to eachother
struct System {
modules: Modules,
pulses: Queue<Pulse>,
low_pulses: Int,
high_pulses: Int,
}

impl Parse for System {
fn parse(input: Input) -> Self {
let lines: Vec<String> = InputLines::from(input).into();
let mut modules: Modules = lines
.into_iter()
.map(Module::parse)
.map(|m| (m.name.clone(), m))
.collect();
// Always add output module, since we do not parse these
let output = Module {
kind: ModuleKind::Output,
name: String::from("output"),
destinations: Vec::new(),
};
modules.insert(output.name.clone(), output);
System {
modules,
pulses: Queue::new(),
low_pulses: 0,
high_pulses: 0,
}
}
}

impl System {
fn enqueue_pulse(&mut self, from: &str, to: &str, kind: PulseKind) {
self.pulses.push_back(Pulse {
from: from.to_string(),
to: to.to_string(),
kind,
});
// Increment the correct pulse kind
match kind {
PulseKind::High => self.high_pulses += 1,
PulseKind::Low => self.low_pulses += 1,
}
}

fn enqueue_pulses(&mut self, pulses: Vec<Pulse>) {
pulses
.iter()
.for_each(|pulse| self.enqueue_pulse(&pulse.from, &pulse.to, pulse.kind))
}

/// Press the button and run the System, until all pulses have been handled
fn press_button(&mut self) {
self.enqueue_pulse("button", "broadcaster", PulseKind::Low);
self.run_until_all_pulses_handled();
}

/// Press the button and run the System, until all pulses have been handled, `times` times after each other
fn press_button_repeatedly(&mut self, times: Int) {
for _ in 0..times {
self.press_button();
}
}

fn run_until_all_pulses_handled(&mut self) {
while !self.pulses.is_empty() {
let pulse = self.pulses.pop_front().unwrap();
//dbg!(&pulse);

let mut destination = self.modules.get(&pulse.to).unwrap().clone();
destination.handle_pulse(pulse, self);

// Overwrite the old destination module with the possibly changed one
self.modules.insert(destination.name.clone(), destination);
}
}
}

struct DayTwenty {}

impl Problem for DayTwenty {
const YEAR: Year = 2023;
const DAY: Day = 20;
const PART_ONE_EXAMPLE_EXPECTED: Answer = 32000000;
const PART_ONE_EXPECTED: Answer = 0;
const PART_TWO_EXAMPLE_EXPECTED: Answer = 0;
const PART_TWO_EXPECTED: Answer = 0;

fn example_input() -> ExampleInput {
"
broadcaster -> a, b, c
%a -> b
%b -> c
%c -> inv
&inv -> a
"
}

fn solve_part_one(input: Input, _is_example: bool) -> Answer {
let mut system = System::parse(input);
system.press_button_repeatedly(1000);
system.high_pulses * system.low_pulses
}

fn solve_part_two(input: Input, _is_example: bool) -> Answer {
0
}
}

run!(DayTwenty);

/*
Expected:
button -low-> broadcaster
broadcaster -low-> a
broadcaster -low-> b
broadcaster -low-> c
a -high-> b
b -high-> c
c -high-> inv
inv -low-> a
a -low-> b
b -low-> c
c -low-> inv
inv -high-> a
*/

0 comments on commit b218a8d

Please sign in to comment.