Last active
February 1, 2023 00:36
-
-
Save FormerlyZeroCool/ad5dd1bd615c828715341cd7bd91cd82 to your computer and use it in GitHub Desktop.
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
#include <string> | |
#include <array> | |
#include <iostream> | |
void naive_solution(std::string &left, std::string &right) | |
{ | |
for(int i = 0; i < right.length(); i++) | |
{ | |
//to check if the given character in the right matches any character in the left | |
for(int j = 0; j < left.length(); j++) | |
{ | |
if(right[i] == left[j]) | |
{ | |
std::cout<<"naive_solution The matching char is: "<<(right[i])<<"\n"; | |
return; | |
} | |
} | |
} | |
} | |
bool binary_search(char element, std::string search_string) | |
{ | |
int start = 0, end = search_string.length() - 1; | |
int middle = (start + end) / 2; | |
while(start != middle) | |
{ | |
if(search_string[middle] > element) | |
end = middle - 1; | |
else if(search_string[middle] < element) | |
start = middle; | |
else | |
break; | |
middle = (start + end) / 2; | |
} | |
return element == search_string[middle]; | |
} | |
void binary_search_solution(std::string &left, std::string &right) | |
{ | |
//first sort left array | |
std::sort(left.begin(), left.end()); | |
for(int i = 0; i < right.length(); i++) | |
{ | |
//to check if the given character in the right matches any character in the left | |
//search for element in sorted left array | |
if(binary_search(right[i], left)) | |
{ | |
std::cout<<"bin search The matching char is: "<<(right[i])<<"\n"; | |
return; | |
} | |
} | |
} | |
int hash(char c) | |
{ | |
return c - 64; | |
} | |
void hash_set_solution(std::string &left, std::string &right) | |
{ | |
std::array<bool, 64> hash_set = {0}; | |
for(int i = 0; i < left.length(); i++) | |
{ | |
const char element = left[i]; | |
const int hash_code = hash(element); | |
hash_set[hash_code] = true; | |
} | |
char solution = 0; | |
for(int i = 0; i < right.length(); i++) | |
{ | |
//to check if the given character in the right matches any character in the left | |
if(hash_set[hash(right[i])]) | |
{ | |
std::cout<<"hash set The matching char is: "<<(right[i])<<"\n"; | |
return; | |
} | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
if(argc < 2) | |
{ | |
std::cout<<"Please provide an input command line parameter"; | |
} | |
std::string input = argv[1]; | |
std::string left = input.substr(0, input.length() / 2); | |
std::string right = input.substr(input.length() / 2, input.length()); | |
std::cout<<"left: "<<left<<" right: "<<right<<"\n"; | |
naive_solution(left, right); | |
hash_set_solution(left, right); | |
binary_search_solution(left, right); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment