Best shuffle: Difference between revisions
Content added Content deleted
(C++ snippet) |
(enhancements for C++) |
||
Line 673: | Line 673: | ||
#include <random> |
#include <random> |
||
#include <time.h> |
#include <time.h> |
||
⚫ | |||
template <class S> |
template <class S> |
||
Line 680: | Line 678: | ||
public: |
public: |
||
S operator()(const S& s1) { |
S operator()(const S& s1) { |
||
S s2 = s1; |
S s2 = shuffle(s1); |
||
⚫ | |||
for (unsigned i = 0; i < s2.length(); i++) |
for (unsigned i = 0; i < s2.length(); i++) |
||
if (s2[i] == s1[i]) |
if (s2[i] == s1[i]) |
||
Line 691: | Line 688: | ||
break; |
break; |
||
} |
} |
||
return s1 + '\n' + s2 + " (" + to_string(count(s2, s1)) + ')'; |
return s1 + '\n' + s2 + " (" + std::to_string(count(s2, s1)) + ')'; |
||
} |
} |
||
private: |
private: |
||
static |
static S shuffle(const S& in) { |
||
⚫ | |||
for (int i = s.length() - 1 ; i >= 1; i--) { |
for (int i = s.length() - 1 ; i >= 1; i--) { |
||
auto r = rand() % i +1; |
auto r = rand() % i + 1; |
||
auto tmp = s[i]; |
auto tmp = s[i]; |
||
s[i] = s[r]; |
s[i] = s[r]; |
||
s[r] = tmp; |
s[r] = tmp; |
||
} |
} |
||
return s; |
|||
} |
} |
||
Line 716: | Line 715: | ||
srand(time(NULL));// initialize random seed |
srand(time(NULL));// initialize random seed |
||
⚫ | |||
string words[] = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}; |
string words[] = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}; |
||
BestShuffle< |
BestShuffle<basic_string<char>> bs; |
||
for ( |
for (auto w : words) cout << bs(w) << endl; |
||
return 0; |
return 0; |
||
}</lang> |
}</lang> |