heh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#![allow(confusable_idents, uncommon_codepoints, mixed_script_confusables)]
#![feature(
    inline_const,
    slice_flatten,
    iter_collect_into,
    let_chains,
    anonymous_lifetime_in_impl_trait,
    unchecked_math,
    array_windows,
    slice_take,
    test,
    slice_as_chunks,
    array_chunks,
    slice_split_once,
    byte_slice_trim_ascii
)]
extern crate test;
pub mod util;

use std::mem::MaybeUninit;

use arrayvec::ArrayVec;
pub use util::prelude::*;

#[derive(Eq, Debug, PartialEq)]
enum ModuleT {
    Flip(bool),
    Cj(ArrayVec<(u16, bool), 11>),
    Untyped,
}

#[derive(Debug)]
struct Module {
    ty: ModuleT,
    output: Box<[u16]>,
}

impl Module {
    pub fn pass<'b>(
        &mut self,
        myname: u16,
        from: u16,
        x: bool,
        stack: &'b mut VecDeque<(u16, u16, bool)>,
    ) {
        match self.ty {
            ModuleT::Flip(ref mut state) => {
                if x {
                    return;
                }
                *state = !*state;
                for &o in &*self.output {
                    stack.push_back((myname, o, *state));
                }
            }
            ModuleT::Cj(ref mut mem) => {
                mem.iter_mut().find(|(x, _)| x == &from).unwrap().1 = x;
                let s = !mem.iter().all(|&(_, x)| x);
                for &o in &*self.output {
                    stack.push_back((myname, o, s));
                }
            }
            ModuleT::Untyped => {
                for &x in &*self.output {
                    stack.push_back((myname, x, false));
                }
            }
        }
    }
}

fn split<'a>(
    i: impl Iterator<Item = &'a [u8]>,
) -> impl Iterator<Item = (&'a [u8], impl Iterator<Item = &'a [u8]>)> {
    i.map(|mut x| {
        let n = x.iter().position(|&x| x == b' ').unwrap();
        let a = &x[..n];
        x.skip(n + 4);
        (a, x.split(|&x| x == b',').map(<[u8]>::trim_ascii))
    })
}

impl<'a, T> std::ops::IndexMut<u16> for Hold<T> {
    fn index_mut(&mut self, index: u16) -> &mut Self::Output {
        unsafe { self.names.get_unchecked_mut(index.nat()).assume_init_mut() }
    }
}

impl<'a, T> std::ops::Index<u16> for Hold<T> {
    type Output = T;
    fn index(&self, index: u16) -> &Self::Output {
        unsafe { self.names.get_unchecked(index.nat()).assume_init_ref() }
    }
}

struct Hold<T> {
    names: [MaybeUninit<T>; 26 * 26],
}

impl<'a, T> std::ops::IndexMut<&[u8]> for Hold<T> {
    fn index_mut(&mut self, index: &[u8]) -> &mut Self::Output {
        unsafe {
            self.names
                .get_unchecked_mut(hash(index).nat())
                .assume_init_mut()
        }
    }
}

impl<'a, T> std::ops::Index<&[u8]> for Hold<T> {
    type Output = T;

    fn index(&self, index: &[u8]) -> &Self::Output {
        unsafe {
            self.names
                .get_unchecked(hash(index).nat())
                .assume_init_ref()
        }
    }
}

fn hash(x: &[u8]) -> u16 {
    println!("{}", x.p());
    if let &[a, b] = x {
        (a - b'a').widen() * 26 + (b - b'a').widen()
    } else {
        0
    }
}

impl<T> Hold<T> {
    #[inline]
    fn new() -> Self {
        Self {
            names: [const { MaybeUninit::uninit() }; 26 * 26],
        }
    }

    fn set(&mut self, index: u16, to: T) {
        unsafe { self.names.get_unchecked_mut(index.nat()).write(to) };
    }
}

fn parse<'a>(i: impl Iterator<Item = (&'a [u8], impl Iterator<Item = &'a [u8]>)>) -> Hold<Module> {
    let mut modules = Hold::new();
    let mut backwards = [const { vec![] }; 26 * 26];
    let mut rest = vec![];
    i.map(|(mut from, to)| {
        let to: Box<[u16]> = to.map(hash).collect();
        let t = match C! { from[0] } {
            b'%' => {
                from.skip(1);
                Some(ModuleT::Flip(false))
            }
            b'&' => {
                from.skip(1);
                None
            }
            _ => Some(ModuleT::Untyped),
        };
        let f = hash(from);
        for &elem in &*to {
            let x = C! { &mut backwards[elem.nat()]};
            if !x.contains(&f) {
                x.push(f);
            };
        }

        if let Some(ty) = t {
            modules.set(f, Module { ty, output: to });
        } else {
            rest.push((f, to));
        }
    })
    .Θ();
    for (name, output) in rest {
        modules.set(
            name,
            Module {
                ty: ModuleT::Cj(
                    C! { &backwards[name.nat()] }
                        .iter()
                        .map(|&x| (x, false))
                        .collect(),
                ),
                output,
            },
        );
    }
    modules
}

fn p1(i: &str) -> usize {
    let mut modules = parse(split(i.行()));
    fn push(modules: &mut Hold<Module>) -> (usize, usize) {
        let (mut lo, mut hi) = (0, 0);
        let mut stack = VecDeque::new();
        stack.push_back((0, 0, false));
        while let Some((m, to, x)) = stack.pop_front() {
            if x {
                hi += 1
            } else {
                lo += 1;
            }
            if to != hash(b"rx") {
                modules[to].pass(to, m, x, &mut stack)
            };
        }
        (lo, hi)
    }

    let (lo, hi) = (0..1000).fold((0, 0), |(lo, hi), _| {
        let (lo2, hi2) = push(&mut modules);
        (lo + lo2, hi + hi2)
    });
    lo * hi
}

fn p(x: [u8; 2]) -> [u8; 2] {
    println!("{}", x.p());
    x
}

fn p2(i: &str) -> u64 {
    let mut broadcast = [0; 4];
    let mut flip = [(u16::MAX, u16::MAX); 26 * 26];
    let mut i = i.as_bytes();
    while i.len() > 1 {
        println!("it");
        match i.by().ψ() {
            b'%' => {
                let from = hash(&i.rd::<2>().ψ());
                i.skip(4);
                let first = hash(&i.rd::<2>().ψ());
                let second = if i.get(0).is_some_and(|&x| x != b'\n') {
                    i.skip(2);
                    let second = hash(&i.rd::<2>().ψ());
                    second
                } else {
                    u16::MAX
                };
                _ = i.read(&mut [0]);
                C! { flip[from.nat()] = (first, second) };
            }
            b'b' => {
                println!("bro");
                i.skip(14);
                let a = hash(&i.rd::<2>().ψ());
                i.skip(2);
                let b = hash(&i.rd::<2>().ψ());
                i.skip(2);
                let c = hash(&i.rd::<2>().ψ());
                i.skip(2);
                let d = hash(&i.rd::<2>().ψ());
                broadcast = [a, b, c, d];
            }
            _ => {
                i.take_line();
            }
        };
    }

    fn quadrant(start: u16, flops: &[(u16, u16); 26 * 26]) -> u64 {
        let mut period = (1 << 11) | 1;
        let mut outputs = C! { flops[start.nat()] };
        let mut i = 1;
        loop {
            let first = C! { flops[outputs.0.nat()] };
            outputs = if first.0 == u16::MAX {
                if outputs.1 == u16::MAX {
                    return period;
                }
                C! { flops[outputs.1.nat()] }
            } else {
                first
            };
            if outputs.1 != u16::MAX {
                bits!(period + i);
            }
            i += 1;
        }
    }
    [
        quadrant(broadcast[0], &flip),
        quadrant(broadcast[1], &flip),
        quadrant(broadcast[2], &flip),
        quadrant(broadcast[3], &flip),
    ]
    .iter()
    .product()
}

pub fn run(i: &str) -> impl Display {
    p2(i)
}

fn main() {
    let i = include_str!("inp.txt").trim();
    println!("{}", run(i));
}

#[bench]
fn bench(b: &mut test::Bencher) {
    let i = boxd(include_str!("inp.txt").trim());
    b.iter(|| run(i));
}