Skip to content

Instantly share code, notes, and snippets.

@jasondyoungberg
Created November 23, 2024 18:38
Show Gist options
  • Save jasondyoungberg/ed6763faa8195e285646a394a365cb18 to your computer and use it in GitHub Desktop.
Save jasondyoungberg/ed6763faa8195e285646a394a365cb18 to your computer and use it in GitHub Desktop.
tc add optimizer
use std::process::exit;
#[derive(Clone, Copy, Debug)]
struct Gate {
in1: usize,
in2: usize,
kind: GateKind
}
impl Gate {
fn all(n: usize) -> impl Iterator<Item = Self> {
(0..n).flat_map(move|a|(0..n).map(move|b|(a,b))).flat_map(|(a,b)|{
GateKind::all().map(move|k|Gate { in1: a, in2: b, kind: k })
})
}
fn eval(&self, data: &[u8]) -> u8 {
self.kind.eval(data[self.in1], data[self.in2])
}
}
#[derive(Clone, Copy, Debug)]
enum GateKind {
And,
Or,
Nand,
Nor,
}
impl GateKind {
fn all() -> impl Iterator<Item = Self> {
[GateKind::And, GateKind::Or, GateKind::Nand, GateKind::Nor].into_iter()
}
fn eval(&self, a: u8, b: u8) -> u8 {
match self {
GateKind::And => a&b,
GateKind::Or => a|b,
GateKind::Nand => !(a&b),
GateKind::Nor => !(a|b),
}
}
}
// a, b, carry in, a or b, a and b, carry out
const INITIAL: &[u8] = &[0b_00001111, 0b_00110011, 0b_01010101, 0b_00111111, 0b_00000011, 0b00010111];
const GOAL: u8 = 0b_01101001; // sum
fn main() {
for depth in 0.. {
dbg!(depth);
try_all(Vec::from(INITIAL), Vec::new(), depth);
}
}
fn try_all(data: Vec<u8>, gatelist: Vec<Gate>, max_depth: usize) {
for new_gate in Gate::all(data.len()) {
let new_item = new_gate.eval(&data);
if max_depth == 0 {
if new_item == GOAL {
dbg!(&data, &gatelist, &new_gate);
exit(0);
}
} else {
let mut new_data = data.clone();
new_data.push(new_item);
let mut new_gatelist = gatelist.clone();
new_gatelist.push(new_gate);
try_all(new_data, new_gatelist, max_depth-1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment