We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
cool_shark, that is a beautiful solution. I had initially tried a similar (but exceedingly broken)thing using character arrays...
HOWEVER THIS BREAKS THE UNIT TESTS SO BEWARE!!! I'm just posting it here to help other people avoid my same mistake.
The reason it breaks is because of the size of the datasets. In this implementation, if an individual character occurs more than 128 times, the value stored at that character's position in the array will go from 127 to -128 and then go down from there, back to 0 and then back up again. You get a bunch of negative or otherwise incorrect values. A char is just not large enough to hold some of the counts that occur in the large data sets. Again, this is BROKEN, but I just wanted to share it FYI as a 'don't do it this way' sort of thing.
int number_needed(char * a, char * b) {
char countA[MAX] = {0};
char countB[MAX] = {0};
for(int i = 0; i < strlen(a); ++i) {
char charAtIndex = a[i];
countA[charAtIndex]++;
}
for(int i = 0; i < strlen(b); ++i) {
char charAtIndex = b[i];
countB[charAtIndex]++;
}
int g = 0;
for(int i = 0; i < MAX; ++i){
int diff = countA[i] - countB[i];
if (diff != 0)
g = g + abs(diff);
}
return g;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Strings: Making Anagrams
You are viewing a single comment's thread. Return to all comments →
cool_shark, that is a beautiful solution. I had initially tried a similar (but exceedingly broken)thing using character arrays...
HOWEVER THIS BREAKS THE UNIT TESTS SO BEWARE!!! I'm just posting it here to help other people avoid my same mistake.
The reason it breaks is because of the size of the datasets. In this implementation, if an individual character occurs more than 128 times, the value stored at that character's position in the array will go from 127 to -128 and then go down from there, back to 0 and then back up again. You get a bunch of negative or otherwise incorrect values. A char is just not large enough to hold some of the counts that occur in the large data sets. Again, this is BROKEN, but I just wanted to share it FYI as a 'don't do it this way' sort of thing.
int number_needed(char * a, char * b) { char countA[MAX] = {0}; char countB[MAX] = {0};
}