| 1 | #ifndef _PermutationInversionCounter_h_ |
| 2 | #define _PermutationInversionCounter_h_ |
| 3 | /* PermutationInversionCounter.h |
| 4 | * |
| 5 | * Copyright (C) 2025 David Weenink |
| 6 | * |
| 7 | * This code is free software; you can redistribute it and/or modify |
| 8 | * it under the terms of the GNU General Public License as published by |
| 9 | * the Free Software Foundation; either version 2 of the License, or (at |
| 10 | * your option) any later version. |
| 11 | * |
| 12 | * This code is distributed in the hope that it will be useful, but |
| 13 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 15 | * General Public License for more details. |
| 16 | * |
| 17 | * You should have received a copy of the GNU General Public License |
| 18 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 19 | */ |
| 20 | |
| 21 | #include "Permutation.h" |
| 22 | #include "PermutationInversionCounter_def.h" |
| 23 | |
| 24 | /* |
| 25 | Given a vector v with n elements, we define an inversion as i < j && v [i] > v [j]. |
| 26 | We use a trick to store the inversion between two elements (i,j) with only **one** number code by using the following |
| 27 | lower triangular (n-1) x (n-1) matrix, with i being the **column** index and j being the **row** index! |
| 28 | |
| 29 | 1 2 3 4 5 ... n-1 |
| 30 | +--------------- ...-- |
| 31 | 1(2) | 1 |
| 32 | 2(3) | 2 3 |
| 33 | 3(4) | 4 5 6 |
| 34 | 4(5) | 7 8 9 10 |
| 35 | 5(6) | 11 12 13 14 15 |
| 36 | ... |
| 37 | n-1(n)| n(n-1)/2 |
| 38 | |
| 39 | E.g. the inversion between element 1 and element 2 is coded with the number 1, |
| 40 | the inversion between element 2 and 5 is code with the number 8. |
| 41 | From inversion (i<j) to the code: |
| 42 | code = (j-2)*(j-1)/2 + i |
| 43 | From the code to the inversion (i,j) |
| 44 | j = Melder_iroundUp (0.5 + sqrt (0.25 + 2 * code)); |
| 45 | i = code - (j-2) * (j - 1) / 2; |
| 46 | |
| 47 | */ |
| 48 | |
| 49 | inline void getInversionFromCode (integer code, integer& ilow, integer& ihigh) { |
| 50 | ihigh = Melder_iroundUp (0.5 + sqrt (0.25 + 2 * code)); |
| 51 | ilow = code - (ihigh - 2) * (ihigh - 1) / 2; |
| 52 | Melder_assert (ilow < ihigh); |
| 53 | } |
| 54 | |
| 55 | inline integer getCodeFromInversion (integer ilow, integer ihigh) { |
| 56 | Melder_assert (ilow < ihigh); |
| 57 | return (ihigh - 2) * (ihigh - 1) / 2 + ilow; |
| 58 | } |
| 59 | |
| 60 | void PermutationInversionCounter_init (integer size); |
| 61 | |
| 62 | autoPermutationInversionCounter PermutationInversionCounter_create (integer size); |
| 63 | |
| 64 | #endif // _PermutationInversionCounter_h_ |