I had never heard of this thing, so I went to Wikipedia and found some more examples:
The Hamming distance between:
- “karolin” and “kathrin” is 3.
- “karolin” and “kerstin” is 3.
- 1011101 and 1001001 is 2.
- 2173896 and 2233796 is 3.
I see it now. A very simple idea: line up the strings of characters, go through them one character at a time, and count each instance in which the characters don’t match. Done!
The instructions have one more important note: “The Hamming distance is only defined for sequences of equal length.” And the last test expects an error message if the two sequences are not the same length.
“Exceptions are a mechanism that make it possible for code that runs into a problem to raise (or throw) an exception, which is simply a value. Raising an exception somewhat resembles a super-charged return from a function: it jumps out of not just the current function but also out of its callers, all the way down to the first call that started the current execution. This is called unwinding the stack.”
The code examples from that chapter pointed me in the right direction (and gave me some syntax that I could copy-paste). So I think I can do something like this:
#Comparing Strings (or DNA Strands)
To compute the Hamming difference of two strings, I think all I need to do is iterate through each character of the strings and see if they match. If they do match, great! If they don’t match, then I need to count up how many chracters are different. The final count will be the Hamming difference.
When in doubt, I just use a for loop because it’s compatible with older browsers and it’s very straightforward:
Let’s see if that works… Yeah, it passed every test! This one was way too easy.
Well, it’s time for me to do some chores, eat some food, and get ready to go to work. But if I have any downtime at the office, I’ll do some more studying! And I hope to learn some more at the front-end web development meetup group that I’m hosting tonight.