Lesson 2

String Encoding and Frequency Analysis with JavaScript

Introduction

Hello! Are you ready for an exciting voyage into the wonderful realm of strings and data structures? Today, we will assist Alice, an aspiring cryptographer, with an intriguing string manipulation task. She loves playing with strings and has come up with a unique string encoding scheme. I assure you, this will be an enlightening journey that will stretch your programming muscles. Let's get started!

Task Statement

Alice has devised a unique way of encoding words. She takes a word and replaces each character with the next character in the alphabetical order. In other words, given a string word, for each character, if it is not z, she replaces it with the character that comes next alphabetically. For the character z, she replaces it with a.

Another element of Alice's algorithm involves frequency analysis. After shifting the characters, she counts the frequency of each character in the new string. Then, she creates an association of each character with its frequency and ASCII value. Each character maps to a number, which is a product of the ASCII value of the character and its frequency. Our task is to construct a list containing these products, sorted in descending order.

Example

For the input string "banana", the output should be [294, 222, 99].

The string "banana" will be shifted to "cbobob".

Calculating the product of frequency and ASCII value for each character:

  • The ASCII value for c is 9999; it appears once in the string, so its product is 991=9999 \cdot 1 = 99.
  • The ASCII value for b is 9898; it appears three times in the string, so its product is 983=29498 \cdot 3 = 294.
  • The ASCII value for o is 111111; it appears twice in the string, so its product is 1112=222111 \cdot 2 = 222.

Collecting these products into a list gives [99, 294, 222]. Sorting this list in descending order results in [294, 222, 99].

Solution Building: Step 1 - Mapping each character to the next alphabetical character

Our first step involves mapping each character of the input string to the next alphabetical character. For this, we define nextString as an empty string, storing the shift operation result. We then iterate over each character of the input string. If a character is not z, we replace it with the next alphabetical character. If it is z, we replace it with a.

Here's the updated function in JavaScript:

JavaScript
1function characterFrequencyEncoding(word) { 2 let nextString = ''; 3 for (let i = 0; i < word.length; i++) { 4 let letter = word[i]; 5 if (letter === 'z') { 6 nextString += 'a'; 7 } else { 8 nextString += String.fromCharCode(letter.charCodeAt(0) + 1); 9 } 10 } 11 return nextString; 12}
Solution Building: Step 2 - Counting the frequency of characters in `nextString`

The next step is to track the frequency of each character in nextString. We start by initializing an empty object frequencyMap. Then, we iterate over nextString. If the current character exists in frequencyMap, we increment its frequency by 1. If it doesn't exist, we add it to frequencyMap with a frequency of 1.

Incorporating this step into the function, our code now looks like this:

JavaScript
1function countFrequency(nextString) { 2 const frequencyMap = {}; 3 for (let i = 0; i < nextString.length; i++) { 4 let letter = nextString[i]; 5 if (frequencyMap[letter]) { 6 frequencyMap[letter]++; 7 } else { 8 frequencyMap[letter] = 1; 9 } 10 } 11 return frequencyMap; 12}
Solution Building: Step 3 - Building the product list

Next, we calculate the numerical representation for each unique character. We initialize an empty array combinedValues to store these numbers. For each character in frequencyMap, we calculate the product of its ASCII representation and its frequency in nextString and append this to combinedValues.

Here's the updated function:

JavaScript
1function buildProductList(frequencyMap) { 2 const combinedValues = []; 3 for (let letter in frequencyMap) { 4 const asciiValue = letter.charCodeAt(0); 5 const frequency = frequencyMap[letter]; 6 combinedValues.push(asciiValue * frequency); 7 } 8 return combinedValues; 9}
Solution Building: Step 4 - Sorting the final values

The final step is to sort the list combinedValues in descending order using JavaScript's sort method with a custom comparison function.

Here's our complete function:

JavaScript
1function characterFrequencyEncoding(word) { 2 // Step 1: Mapping each character to the next alphabetical character 3 let nextString = ''; 4 for (let i = 0; i < word.length; i++) { 5 let letter = word[i]; 6 if (letter === 'z') { 7 nextString += 'a'; 8 } else { 9 nextString += String.fromCharCode(letter.charCodeAt(0) + 1); 10 } 11 } 12 13 // Step 2: Counting the frequency of characters in nextString 14 const frequencyMap = {}; 15 for (let i = 0; i < nextString.length; i++) { 16 let letter = nextString[i]; 17 if (frequencyMap[letter]) { 18 frequencyMap[letter]++; 19 } else { 20 frequencyMap[letter] = 1; 21 } 22 } 23 24 // Step 3: Building the product list 25 const combinedValues = []; 26 for (let letter in frequencyMap) { 27 const asciiValue = letter.charCodeAt(0); 28 const frequency = frequencyMap[letter]; 29 combinedValues.push(asciiValue * frequency); 30 } 31 32 // Step 4: Sorting the final values in descending order 33 combinedValues.sort((a, b) => b - a); 34 35 // Return the sorted list 36 return combinedValues; 37} 38 39// Testing the function 40const word = 'banana'; 41const result = characterFrequencyEncoding(word); 42console.log(result); // Prints: [294, 222, 99]
Lesson Summary

Well done! You've successfully tackled an intricate problem that required you to exercise multiple topics such as string manipulation, object processing, and array sorting. This task underscored the importance of reusing already calculated values. I encourage you to apply what you've learned today to other tasks. Many more exciting challenges are waiting for you in the upcoming practice sessions. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.