Jump to content

Best shuffle: Difference between revisions

C++ snippet
(Kotlin output)
(C++ snippet)
Line 667:
return 0;
}</lang>
 
=={{header|C++}}==
C++11 version from Java.
<lang cpp>#include <iostream>
#include <random>
#include <time.h>
 
using namespace std;
 
template <class S>
class BestShuffle {
public:
S operator()(const S& s1) {
S s2 = s1;
shuffle(s2);
for (unsigned i = 0; i < s2.length(); i++)
if (s2[i] == s1[i])
for (unsigned j = 0; j < s2.length(); j++)
if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {
auto tmp = s2[i];
s2[i] = s2[j];
s2[j] = tmp;
break;
}
return s1 + '\n' + s2 + " (" + to_string(count(s2, s1)) + ')';
}
 
private:
static void shuffle(S& s) {
for (int i = s.length() - 1 ; i >= 1; i--) {
auto r = rand() % i +1;
auto tmp = s[i];
s[i] = s[r];
s[r] = tmp;
}
}
 
static int count(const S& s1, const S& s2) {
auto count = 0;
for (unsigned i = 0; i < s1.length(); i++)
if (s1[i] == s2[i])
count++;
return count;
}
};
 
int main() {
srand(time(NULL));// initialize random seed
 
string words[] = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"};
BestShuffle<string> bs;
for (string w : words) cout << bs(w) << endl;
return 0;
}</lang>
{{out}}
<pre>abracadabra
raabadabcar (0)
seesaw
wssaee (0)
grrrrrr
rgrrrrr (5)
pop
opp (1)
up
pu (0)
a
a (1)</pre>
 
=={{header|C sharp|C#}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.