Could a computer send BANANA using shorter codes for the letters it sees most?
A fruit stall in Leeds sends the word BANANA to its label printer. The letter A appears three times. Could you give A a shorter code and still let the printer tell exactly where each letter ends?
When you compress data, you use fewer bits. That saves storage space and means there are fewer bits to send to the printer. Every letter on the label must come back exactly as you sent it. That's what makes the compression lossless.
The table counts each letter in BANANA. In the fixed-width column, every letter gets two bits. That's a code for just these three letters. In the last column, A gets one bit because it occurs most often. B and N still use two bits each.
In the word TATTOO, T occurs three times, O occurs twice and A occurs once. If you could give just one letter a one-bit code, which would save the most bits? Pick an answer.
Back to BANANA. Start with B at one, N at two and A at three. Join B and N, the two smallest counts, under a parent with count three. Now join that parent and A. Their counts add to six.
This is the Huffman tree. Start at the root at the top. A is a leaf one branch away, so its code is zero. To reach B, follow one then zero. To reach N, follow one then one. Each code ends at a leaf.
From the root, B is one zero, A is zero, and N is one one. Join the codes. To decode, follow one zero to B, restart for zero to A, then restart for one one to N. If you split into pairs, the second pair, zero one, isn't a code.
Use the same tree to decode one one zero one zero. Follow the bits from the root until you reach a letter, then go back to the root for the next unread bit. Pick the message you get.
For BANANA, count one bit for each of three As, two for B and two for each of two Ns. That's nine bits for the message alone. With seven-bit ASCII, six characters take forty-two bits. Subtract nine from forty-two to get a saving of thirty-three bits, ignoring the tree.
Run length encoding counts consecutive repeats. In AAABBA, the first run is three As, the next is two Bs, and the last is one A. The Bs separate the As into two runs. If an exam asks for frequency and data pairs, write the count first and the symbol second.