Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active November 22, 2023 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/d418847eb5c8fece458fe05a5dede7e8 to your computer and use it in GitHub Desktop.
Save juanfal/d418847eb5c8fece458fe05a5dede7e8 to your computer and use it in GitHub Desktop.
string are permutations of each other
// 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