use std::rc::Rc;
use std::collections::HashMap;
use std::fmt;
#[derive(Clone)]
enum BddNode {
Terminal(bool),
Internal { variable: String, child_false: Rc<BddNode>, child_true: Rc<BddNode> },
}
impl PartialEq for BddNode {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(BddNode::Terminal(a), BddNode::Terminal(b)) => a == b,
(BddNode::Internal { variable: v1, child_false: cf1, child_true: ct1 },
BddNode::Internal { variable: v2, child_false: cf2, child_true: ct2 }) =>
v1 == v2 && cf1 == cf2 && ct1 == ct2,
_ => false,
}
}
}
fn bdd_true() -> Rc<BddNode> { Rc::new(BddNode::Terminal(true)) }
fn bdd_false() -> Rc<BddNode> { Rc::new(BddNode::Terminal(false)) }
fn create(variable: &str, child_false: Rc<BddNode>, child_true: Rc<BddNode>) -> Rc<BddNode> {
if *child_false == *child_true {
return child_false;
}
Rc::new(BddNode::Internal {
variable: variable.to_string(),
child_false,
child_true,
})
}
fn evaluate(node: &BddNode, assignment: &HashMap<&str, bool>) -> bool {
match node {
BddNode::Terminal(v) => *v,
BddNode::Internal { variable, child_false, child_true } => {
let var_value = assignment.get(variable.as_str()).copied().unwrap_or(false);
if var_value {
evaluate(child_true, assignment)
} else {
evaluate(child_false, assignment)
}
}
}
}
fn count_nodes(node: &BddNode) -> usize {
match node {
BddNode::Terminal(_) => 1,
BddNode::Internal { child_false, child_true, .. } =>
1 + count_nodes(child_false) + count_nodes(child_true),
}
}
fn apply(f: &Rc<BddNode>, g: &Rc<BddNode>, op: &dyn Fn(bool, bool) -> bool, op_name: &'static str, cache: &mut HashMap<(usize, usize, &'static str), Rc<BddNode>>) -> Rc<BddNode> {
if let (BddNode::Terminal(fv), BddNode::Terminal(gv)) = (f.as_ref(), g.as_ref()) {
return if op(*fv, *gv) { bdd_true() } else { bdd_false() };
}
let key = (Rc::as_ptr(f) as usize, Rc::as_ptr(g) as usize, op_name);
if let Some(cached) = cache.get(&key) {
return cached.clone();
}
let f_var: Option<&str> = if let BddNode::Internal { variable, .. } = f.as_ref() { Some(variable.as_str()) } else { None };
let g_var: Option<&str> = if let BddNode::Internal { variable, .. } = g.as_ref() { Some(variable.as_str()) } else { None };
let f_children: Option<(Rc<BddNode>, Rc<BddNode>)> = if let BddNode::Internal { child_false, child_true, .. } = f.as_ref() {
Some((child_false.clone(), child_true.clone()))
} else { None };
let g_children: Option<(Rc<BddNode>, Rc<BddNode>)> = if let BddNode::Internal { child_false, child_true, .. } = g.as_ref() {
Some((child_false.clone(), child_true.clone()))
} else { None };
let (top, f_lo, f_hi, g_lo, g_hi) = if let (Some(fv), Some(gv)) = (f_var, g_var) {
if fv < gv {
let (fcf, fct) = f_children.unwrap();
(fv.to_string(), fcf, fct, g.clone(), g.clone())
} else if gv < fv {
let (gcf, gct) = g_children.unwrap();
(gv.to_string(), f.clone(), f.clone(), gcf, gct)
} else {
let (fcf, fct) = f_children.unwrap();
let (gcf, gct) = g_children.unwrap();
(fv.to_string(), fcf, fct, gcf, gct)
}
} else if let Some(fv) = f_var {
let (fcf, fct) = f_children.unwrap();
(fv.to_string(), fcf, fct, g.clone(), g.clone())
} else if let Some(gv) = g_var {
let (gcf, gct) = g_children.unwrap();
(gv.to_string(), f.clone(), f.clone(), gcf, gct)
} else {
return bdd_false();
};
let res_lo = apply(&f_lo, &g_lo, op, op_name, cache);
let res_hi = apply(&f_hi, &g_hi, op, op_name, cache);
let result = create(&top, res_lo, res_hi);
cache.insert(key, result.clone());
result
}
fn and_(f: &Rc<BddNode>, g: &Rc<BddNode>, cache: &mut HashMap<(usize, usize, &'static str), Rc<BddNode>>) -> Rc<BddNode> {
apply(f, g, &|a, b| a && b, "AND", cache)
}
fn or_(f: &Rc<BddNode>, g: &Rc<BddNode>, cache: &mut HashMap<(usize, usize, &'static str), Rc<BddNode>>) -> Rc<BddNode> {
apply(f, g, &|a, b| a || b, "OR", cache)
}
fn not_(f: &Rc<BddNode>, not_cache: &mut HashMap<usize, Rc<BddNode>>) -> Rc<BddNode> {
if let BddNode::Terminal(v) = f.as_ref() {
return if *v { bdd_false() } else { bdd_true() };
}
let key = Rc::as_ptr(f) as usize;
if let Some(cached) = not_cache.get(&key) {
return cached.clone();
}
if let BddNode::Internal { variable, child_false, child_true } = f.as_ref() {
let result = create(variable, not_(child_false, not_cache), not_(child_true, not_cache));
not_cache.insert(key, result.clone());
result
} else {
bdd_false()
}
}
use myia_nb::py_bool;
// Cache neuf (cellule autonome)
let mut cache: HashMap<(usize, usize, &'static str), Rc<BddNode>> = HashMap::new();
let mut not_cache: HashMap<usize, Rc<BddNode>> = HashMap::new();
let bdd_x = create("x", bdd_false(), bdd_true());
// Test 1 : x AND NOT x = FALSE
let bdd_not_x = not_(&bdd_x, &mut not_cache);
let bdd_x_and_not_x = and_(&bdd_x, &bdd_not_x, &mut cache);
let res1 = evaluate(bdd_x_and_not_x.as_ref(), &HashMap::new());
let attendu1 = false;
let ok1 = res1 == attendu1;
println!("=== Test 1 : x AND NOT x ===");
println!("Résultat : {}", py_bool(res1));
println!("Verdict (attendu {}) : {}", py_bool(attendu1), if ok1 { "CONFORME" } else { "ECART" });
println!("Noeuds : {}", count_nodes(bdd_x_and_not_x.as_ref()));
println!();
// Test 2 : x OR NOT x = TRUE
let bdd_x_or_not_x = or_(&bdd_x, &bdd_not_x, &mut cache);
let res2 = evaluate(bdd_x_or_not_x.as_ref(), &HashMap::new());
let attendu2 = true;
let ok2 = res2 == attendu2;
println!("=== Test 2 : x OR NOT x ===");
println!("Résultat : {}", py_bool(res2));
println!("Verdict (attendu {}) : {}", py_bool(attendu2), if ok2 { "CONFORME" } else { "ECART" });
println!("Noeuds : {}", count_nodes(bdd_x_or_not_x.as_ref()));
println!();
// Test 3 : (x AND y) OR (x AND z) = x AND (y OR z) (distributivité)
let bdd_y = create("y", bdd_false(), bdd_true());
let bdd_z = create("z", bdd_false(), bdd_true());
let xy = and_(&bdd_x, &bdd_y, &mut cache);
let xz = and_(&bdd_x, &bdd_z, &mut cache);
let bdd_left = or_(&xy, &xz, &mut cache);
let yz = or_(&bdd_y, &bdd_z, &mut cache);
let bdd_right = and_(&bdd_x, &yz, &mut cache);
println!("=== Test 3 : Distributivité ===");
println!("Noeuds (gauche) : {}", count_nodes(bdd_left.as_ref()));
println!("Noeuds (droite) : {}", count_nodes(bdd_right.as_ref()));
let mut assign = HashMap::new();
assign.insert("x", true);
assign.insert("y", true);
assign.insert("z", false);
let lg = evaluate(bdd_left.as_ref(), &assign);
let rg = evaluate(bdd_right.as_ref(), &assign);
println!("Équivalent (x=T,y=T,z=F) : {} == {}", py_bool(lg), py_bool(rg));
// Vérif équivalence sur les 8 assignations.
let mut all_equiv = true;
for a in [false, true] {
for b in [false, true] {
for c in [false, true] {
let mut asg = HashMap::new();
asg.insert("x", a);
asg.insert("y", b);
asg.insert("z", c);
if evaluate(bdd_left.as_ref(), &asg) != evaluate(bdd_right.as_ref(), &asg) {
all_equiv = false;
}
}
}
}
println!("Équivalence sur les 8 assignations : {}", py_bool(all_equiv));