SimiLie
Loading...
Searching...
No Matches
permutation_parity.hpp
1// SPDX-FileCopyrightText: 2024 Baptiste Legouix
2// SPDX-License-Identifier: MIT
3
4#pragma once
5
6#include <ddc/ddc.hpp>
7
8namespace sil {
9
10namespace misc {
11
12/*
13 Given a permutation of unique digits 0...N,
14 returns its parity: +1 for even parity; -1 for odd.
15 If lst contains duplicates, returns 0. If it contains no
16 duplicate but is not a permutation of 0...N, this is undetermined.
17 */
18template <std::size_t N>
19inline constexpr int permutation_parity(std::array<std::size_t, N> lst)
20{
21 int parity = 1;
22 for (std::size_t i = 0; i < lst.size() - 1; ++i) {
23 if (lst[i] != i) {
24 parity *= -1;
25 std::size_t mn
26 = std::distance(lst.begin(), std::min_element(lst.begin() + i, lst.end()));
27 std::swap(lst[i], lst[mn]);
28 }
29 }
30 if (std::adjacent_find(lst.begin(), lst.end()) != lst.end()) {
31 return 0;
32 }
33 if (lst[lst.size() - 1] == lst[0]) {
34 return 0;
35 }
36
37 return parity;
38}
39
40} // namespace misc
41
42} // namespace sil
constexpr int permutation_parity(std::array< std::size_t, N > lst)
The top-level namespace of SimiLie.
Definition csr.hpp:14