Permutation_and_Index.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Permutation_and_Index.cpp
  2. *
  3. * Copyright (C) 2005-2011, 2015-2016 David Weenink
  4. *
  5. * This code is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * This code is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. * See the GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this work. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /*
  19. * djmw 20050725
  20. * djmw 20110503 Latest modification
  21. */
  22. #include "Permutation_and_Index.h"
  23. autoPermutation Index_to_Permutation_permuteRandomly (Index me, bool permuteWithinClasses) {
  24. try {
  25. integer numberOfClasses = my classes->size;
  26. autoPermutation thee = Permutation_create (my numberOfItems);
  27. autoPermutation classes = Permutation_create (numberOfClasses);
  28. Permutation_permuteRandomly_inplace (classes.get(), 0, 0);
  29. autoPermutation classesinv = Permutation_invert (classes.get());
  30. autoNUMmatrix<integer> indices (0, numberOfClasses, 1, 4);
  31. for (integer i = 1; i <= my numberOfItems; i ++) {
  32. indices [my classIndex [i]] [2] ++; /* col 2: number of elements in class */
  33. }
  34. /* Get some other indices ready */
  35. for (integer i = 1; i <= numberOfClasses; i ++) {
  36. integer klass = classes -> p [i];
  37. indices [i] [1] = klass;
  38. indices [i] [3] = indices [i - 1] [3] + indices [i - 1] [2]; /* col 3: index at start of class */
  39. }
  40. for (integer i = 1; i <= my numberOfItems; i ++) {
  41. integer klass = my classIndex [i];
  42. integer newindex = classesinv -> p [klass];
  43. indices [newindex] [4] ++; /* col 4: number of elements processed for class */
  44. integer newpos = indices [newindex] [3] + indices [newindex] [4];
  45. thy p [newpos] = i;
  46. }
  47. if (permuteWithinClasses) {
  48. for (integer i = 1; i <= numberOfClasses; i ++) {
  49. integer from = indices [i] [3] + 1;
  50. integer to = from + indices [i] [2] - 1;
  51. if (to > from) {
  52. Permutation_permuteRandomly_inplace (thee.get(), from, to);
  53. }
  54. }
  55. }
  56. return thee;
  57. } catch (MelderError) {
  58. Melder_throw (me, U": Permutation not created.");
  59. }
  60. }
  61. /* End of file Permutation_and_Index.cpp */