'Optimize the next permutations in n queens puzzle

I am solving the n queens problem.

I use an array of 1..=n to represent the position of the queen, and then keep finding the next permutation until I judge that this permutation is a solution.

/// Returns a bool value indicating whether the next permutation exists
pub fn next_permutation(arrange: &mut [usize]) -> bool {
    let last_ascending = match arrange.windows(2).rposition(|w| w[0] < w[1]) {
        Some(i) => i,
        None => {
            arrange.reverse();
            return false;
        }
    };

    let swap_with = arrange[last_ascending + 1..]
        .binary_search_by(|n| usize::cmp(&arrange[last_ascending], n).then(Ordering::Less))
        .unwrap_err();
    arrange.swap(last_ascending, last_ascending + swap_with);
    arrange[last_ascending + 1..].reverse();
    true
}

pub fn is_solution(arrange: &[usize]) -> bool {
    let iter = arrange.iter().enumerate();
    iter.clone().all(|(i, &j)| {
        iter.clone()
            .filter(|&(c, _)| c != i)
            .all(|(p, &q)| i as isize - j as isize != p as isize - q as isize && i as usize + j != p as usize + q)
    })
}

Now my problem is that the next_permutation function does not quite meet my needs.

For example [1, 2, 3, 4, 5], the next permutation is [1, 2, 3, 5, 4], this results in a lot of wasted judgment.

It can be found that [1, 2, _, _, _] does not meet the requirements , the next permutation to check should be say [1, 3, 2, 4, 5].

How do I optimize the next_permutation function to implement this process?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source