permutation.cpp 713 B

12345678910111213141516171819202122232425262728293031
  1. #include "permutation.h"
  2. #include <algorithm> // swap
  3. #include <cstdlib> // rand
  4. #include <cassert>
  5. // TODO faut-il pi[0] = 0 et pourquoi ???
  6. permutation::permutation(int size) : size(size) {
  7. assert(size > 0);
  8. sigma = new int[size];
  9. for(int i = 0; i < size; i++)
  10. sigma[i] = i;
  11. }
  12. void permutation::transpose(int i, int j) {
  13. assert(0 <= i && i < size);
  14. assert(0 <= j && j < size);
  15. std::swap(sigma[i], sigma[j]);
  16. }
  17. void permutation::random() {
  18. // Knuth shuffle
  19. // TODO algo plus efficace ?
  20. // there is a bias due to the use of rand()%_
  21. for(int i = 0; i < size; i++)
  22. transpose(i, rand()%(i+1));
  23. }
  24. int permutation::operator[](int i) {
  25. assert(0 <= i && i < size);
  26. return sigma[i];
  27. }