Euphoria
knuthshuffle.h
Go to the documentation of this file.
1 #pragma once
2 
3 
4 
5 #include "base/random.h"
6 #include "base/cint.h"
7 
8 namespace eu::core
9 {
10  // Knuth shuffle aka Fisher–Yates shuffle
11  // src: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
12  // add one that respects the current item so it won't be the first one https://gamedev.stackexchange.com/a/29747/90313
13 
14  // todo(Gustav): add tests some how...?
15 
16  template <typename T>
17  void
18  shuffle(std::vector<T>* v, Random* r)
19  {
20  for(int index = c_sizet_to_int(v->size()) - 1; index > 0; index -= 1)
21  {
22  const auto j = get_random_in_range(r, index + 1); // 0 ≤ j ≤ index
23  if(j != index)
24  {
25  std::swap((*v)[j], (*v)[index]);
26  }
27  }
28  }
29 
30 }
void shuffle(std::vector< T > *v, Random *r)
Definition: knuthshuffle.h:18
int c_sizet_to_int(size_t t)
Definition: cint.cc:11
T get_random_in_range(Random *rand, const Range< T > &range)
Definition: random.h:50
WEL512 Random Number Generator.
Definition: random.h:21