Is hidden in this giant string. So how do we find it?
The Problem:
Given as part of the application process to Fog Creek (found here), this problem is as follows…
Sort the characters in the following string:
by the number of times the character appears in the following text (descending):
Now take the sorted string, and drop all the characters after (and including) the _. The remaining word is the answer.
Okay. It’s a long string. A really long string.
The Breakdown:
We need to count how many occurrences of each character there is in the string. A hash will do. As it often does. So lets create a variable called big_string.
Then, we call split on it so we can iterate over big_string. It’ll look like big_string_array = big_string.split("")
So we have something to iterate over! So time to make a hash.
Notice that while we have a proper count of all character occurences, it’s not in order. Hash order is based on when values are put into the hash. That’s not in any order that’s meaningful to us. It’s easiest to say that hashes simply aren’t ordered.
So how do we sort this? By putting it into an array. A nested array at that.
We use a special little hash method called sort_by.
It’s not in descending order. If we did the proper magic to construct our string (getting to that soon), the string we’d get from before the _ would be fbnhzdjgwlqvepxki.
We’re not done yet. We could read this output and figure it out ourselves, but why? We have a computer, let’s use it.
The Secret Word is…
customary
So there we go! We solved it! You can see the full code of my solution here.
The Odd Bit:
While I was writing tests for this, I realized that this approach only works if the word has no repeating characters. For example, arial won’t work because the a in both places gets put into the same place. You will end up with aril as an output.