N-queens problem: Difference between revisions

(→‎Using Iterators: Update code)
Line 14,882:
===Using Iterators===
Solution to the puzzle using an iterator that yields the 92 solutions for 8 queens.
 
<syntaxhighlight lang="rust">use std::collections::LinkedList;
}</syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">use std::collections::LinkedList;
use std::iter::IntoIterator;
 
Line 14,958 ⟶ 14,960:
str
}
}
}</syntaxhighlight>
</syntaxhighlight>
 
===Using Itertools and Diagonals filtering===
 
<syntaxhighlight lang="rust">
extern crate itertools;
 
use itertools::Itertools;
 
fn main() {
const N: usize = 8;
 
let permutations = (0..N).permutations(N);
let solution_count = permutations
.filter(|p| {
let mut diag1 = [false; 2 * N - 1];
let mut diag2 = [false; 2 * N - 1];
for (i, &row) in p.iter().enumerate() {
if diag1[row + i] || diag2[N - 1 + row - i] {
return false; // Two queens threaten each other
}
diag1[row + i] = true;
diag2[N - 1 + row - i] = true;
}
true // No two queens threaten each other
})
.count();
 
println!("{}", solution_count);
}
</syntaxhighlight>
 
=={{header|SAS}}==
121

edits