#include <iostream>
#include <algorithm>
#include <cstring>
const char* wordsArr1[] = {"baseball", "mansion", "backpack" };
const char* wordsArr2[] = {"baseb", "mansi", "backp" };
/**given some word1, some word2, and minLength which is the value min(strlen(word1), strlen(word2))
this will return true iff the first 5 chars or more of word1 and word2 match, otherwise false.
It is safe to modify this to up to 7 char matching, any more overflows the uint64_t into sign
bit which is undefined.**/
bool matches(const char* word1, const char* word2, int minLength)
{
if(minLength < 5) //experiment with removing this, branching may be slower
return false;
uint64_t concatenatedChars1 = 0;
uint64_t concatenatedChars2 = 0;
// no loop due to loop unrolling, might provide speedups in case of cache misses
concatenatedChars1 |= (uint8_t)word1[0];
concatenatedChars2 |= (uint8_t)word2[0];
concatenatedChars1 <<= 8;
concatenatedChars2 <<= 8;
concatenatedChars1 |= (uint8_t)word1[1];
concatenatedChars2 |= (uint8_t)word2[1];
concatenatedChars1 <<= 8;
concatenatedChars2 <<= 8;
concatenatedChars1 |= (uint8_t)word1[2];
concatenatedChars2 |= (uint8_t)word2[2];
concatenatedChars1 <<= 8;
concatenatedChars2 <<= 8;
concatenatedChars1 |= (uint8_t)word1[3];
concatenatedChars2 |= (uint8_t)word2[3];
concatenatedChars1 <<= 8;
concatenatedChars2 <<= 8;
concatenatedChars1 |= (uint8_t)word1[4];
concatenatedChars2 |= (uint8_t)word2[4];
return concatenatedChars1 == concatenatedChars2;
}
int main() {
for(int i = 0; i < 3; i++)
{
const char* word1 = wordsArr1[i];
for(int j = 0; j < 3; j++)
{
const char* word2 = wordsArr2[j];
std::cout << matches(word1, word2, std::min(strlen(word1), strlen(word2))) << std::endl;
}
}
}