// === Problemes de reference ===
// --- Coloration de l'Australie ---
const AUSTRALIA_VARS: [&str; 7] = ["WA", "NT", "SA", "Q", "NSW", "V", "T"];
fn australia_neighbors() -> Vec<(&'static str, Vec<&'static str>)> {
vec![
("WA", vec!["NT", "SA"]),
("NT", vec!["WA", "SA", "Q"]),
("SA", vec!["WA", "NT", "Q", "NSW", "V"]),
("Q", vec!["NT", "SA", "NSW"]),
("NSW", vec!["Q", "SA", "V"]),
("V", vec!["SA", "NSW"]),
("T", vec![]),
]
}
fn australia_domains() -> Vec<(String, Vec<String>)> {
AUSTRALIA_VARS
.iter()
.map(|v| {
(
v.to_string(),
vec!["Rouge".to_string(), "Vert".to_string(), "Bleu".to_string()],
)
})
.collect()
}
/// Contrainte : deux variables voisines doivent avoir des valeurs differentes.
fn different_values(_var1: &String, val1: &String, _var2: &String, val2: &String) -> bool {
val1 != val2
}
/// Cree une nouvelle instance du CSP de coloration de l'Australie.
fn make_australia_csp() -> Csp<String, String> {
Csp {
variables: AUSTRALIA_VARS.iter().map(|v| v.to_string()).collect(),
domains: australia_domains(),
neighbors: australia_neighbors()
.into_iter()
.map(|(k, ns)| (k.to_string(), ns.into_iter().map(|n| n.to_string()).collect()))
.collect(),
constraint_func: different_values,
n_assigns: 0,
n_backtracks: 0,
}
}
// --- N-Reines ---
/// Contrainte des N-Reines : pas de meme ligne, pas de diagonale.
fn queens_constraint(c1: &usize, r1: &usize, c2: &usize, r2: &usize) -> bool {
if r1 == r2 {
return false;
}
if c1.abs_diff(*c2) == r1.abs_diff(*r2) {
return false;
}
true
}
/// Cree un CSP pour le probleme des N-Reines.
fn make_nqueens_csp(n: usize) -> Csp<usize, usize> {
let variables: Vec<usize> = (0..n).collect();
let domains: Vec<(usize, Vec<usize>)> = variables
.iter()
.map(|col| (*col, (0..n).collect()))
.collect();
let neighbors: Vec<(usize, Vec<usize>)> = variables
.iter()
.map(|col| {
(
*col,
variables.iter().filter(|c| *c != col).map(|c| *c).collect(),
)
})
.collect();
Csp {
variables,
domains,
neighbors,
constraint_func: queens_constraint,
n_assigns: 0,
n_backtracks: 0,
}
}
// --- Visualisation N-Reines ---
/// Visualise la solution du probleme des N-Reines (SVG ecrit a la main).
#[allow(dead_code)]
fn svg_queens(solution: &[(usize, usize)], n: usize, title: &str) -> String {
let cell_size = 60.0_f64;
let margin = 40.0_f64;
let board = cell_size * n as f64;
let width = board + 2.0 * margin;
let height = board + 2.0 * margin + 30.0;
let font_size = std::cmp::max(8usize, 24usize.saturating_sub(n));
let mut svg = String::new();
svg.push_str(&format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\">",
width, height, width, height
));
svg.push_str(&format!(
"<rect x=\"0\" y=\"0\" width=\"{}\" height=\"{}\" fill=\"#ffffff\"/>",
width, height
));
svg.push_str(&format!(
"<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"bold\" fill=\"black\">{}</text>",
width / 2.0,
margin - 12.0,
title
));
// Damier : ligne 0 en haut, comme dans la source.
for row in 0..n {
for col in 0..n {
let color = if (row + col) % 2 == 0 { "#F0D9B5" } else { "#B58863" };
let x = margin + col as f64 * cell_size;
let y = margin + row as f64 * cell_size;
svg.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\" stroke=\"black\" stroke-width=\"1\"/>",
x, y, cell_size, cell_size, color
));
}
}
for (col, row) in solution {
let x = margin + (*col as f64 + 0.5) * cell_size;
let y = margin + (*row as f64 + 0.5) * cell_size;
svg.push_str(&format!(
"<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\" font-size=\"{}\" font-weight=\"bold\" fill=\"darkred\">Q</text>",
x, y, font_size
));
}
svg.push_str("</svg>");
svg
}
// Heuristique MRV (rappel de CSP-1)
/// Heuristique MRV : choisir la variable avec le moins de valeurs viables
/// (premier minimum dans l'ordre des variables).
fn select_mrv<V: Clone + PartialEq + Ord, D: Clone>(
csp: &Csp<V, D>,
assignment: &[(V, D)],
domains: &[(V, Vec<D>)],
) -> V {
let mut best: Option<(usize, V)> = None;
for var in &csp.variables {
if assignment.iter().any(|(k, _)| k == var) {
continue;
}
let len = domains
.iter()
.find(|(k, _)| k == var)
.map(|(_, d)| d.len())
.unwrap_or(0);
match &best {
None => best = Some((len, var.clone())),
Some((bl, _)) => {
if len < *bl {
best = Some((len, var.clone()));
}
}
}
}
best.map(|(_, v)| v)
.expect("MRV : aucune variable non assignee")
}
// --- Aides d'affichage : repr Python ---
/// Repr Python d'une liste de chaines : ['Rouge', 'Vert', 'Bleu']
#[allow(dead_code)]
fn py_list(items: &[String]) -> String {
format!(
"[{}]",
items
.iter()
.map(|s| format!("'{}'", s))
.collect::<Vec<String>>()
.join(", ")
)
}
/// Repr Python d'une liste d'entiers : [3, 4, 5]
#[allow(dead_code)]
fn py_list_int(items: &[usize]) -> String {
format!(
"[{}]",
items
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(", ")
)
}
/// Repr Python d'un dict : {'A': 'R', 'B': 'V'}
#[allow(dead_code)]
fn py_dict(pairs: &[(String, String)]) -> String {
format!(
"{{{}}}",
pairs
.iter()
.map(|(k, v)| format!("'{}': '{}'", k, v))
.collect::<Vec<String>>()
.join(", ")
)
}
/// Repr Python d'un booleen : True / False
#[allow(dead_code)]
fn py_bool(b: bool) -> String {
if b {
"True".to_string()
} else {
"False".to_string()
}
}
println!("Problemes de reference et utilitaires definis.");