Last active
November 22, 2023 09:26
-
-
Save juanfal/d418847eb5c8fece458fe05a5dede7e8 to your computer and use it in GitHub Desktop.
string are permutations of each other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// t11e10.scrabble.cpp | |
// juanfc 2023-11-22 | |
// https://gist.github.com/d418847eb5c8fece458fe05a5dede7e8 | |
#include <array> | |
#include <iostream> | |
using namespace std; | |
typedef array<int,256> TCharFreq; | |
bool permutations(string a, string b); | |
void test(string a, string b); | |
int main() | |
{ | |
test("abc", "cba"); | |
test("abc", "cb"); | |
test("", ""); | |
return 0; | |
} | |
void test(string a, string b) | |
{ | |
cout << '"' << a << "\" and \"" << b << '"'; | |
if (permutations(a, b)) | |
cout << " ARE permutations of each other" << endl; | |
else | |
cout << " are NOT permutations of each other" << endl; | |
} | |
TCharFreq getFreqs(string s); | |
bool permutations(string a, string b) | |
{ | |
if (a.length() == b.length()) { | |
TCharFreq af = getFreqs(a); | |
TCharFreq bf = getFreqs(b); | |
return af == bf; | |
} else | |
return false; | |
} | |
TCharFreq getFreqs(string s) | |
{ | |
TCharFreq r; | |
for (int i = 0; i < 256; ++i) | |
r[i] = 0; | |
for (int i = 0; i < s.length(); ++i) | |
++r[s[i]]; | |
return r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment