Introduction

Hello! Are you ready for an exciting journey into the world of strings and frequency analysis? Today, we’ll assist Alice, an aspiring cryptographer, with a fascinating task involving string transformations and calculations. Alice has developed a unique encoding scheme that shifts letters in the alphabet and analyzes their occurrences.

This should be a fun and insightful challenge that hones your problem-solving and coding skills. Let’s dive in!

Task Statement

Alice's encoding scheme involves two steps. First, she takes a word and shifts each character to the next one alphabetically. For example:

  • 'a' becomes 'b'
  • 'z' becomes 'a'

Next, Alice analyzes the frequency of each character in the transformed string. For each unique character, she calculates a product of its ASCII value and its frequency. Finally, she sorts these products in descending order.

Your task is to implement a Ruby method, character_frequency_encoding(word), that performs Alice’s encoding and returns the sorted list of products.

For example:

word = "banana"

The method should return:

[294, 222, 99]

Here’s how the process works:

  1. Transform "banana" into "cbobob".
  2. Calculate the products:
    • 'c': ASCII value 99, frequency 1, product 99 × 1 = 99.
    • 'b': ASCII value 98, frequency 3, product 98 × 3 = 294.
    • 'o': ASCII value 111, frequency 2, product 111 × 2 = 222.
  3. Sort the products in descending order: [294, 222, 99].
Solution Building: Step 1 - Shifting Characters

To implement Alice’s encoding scheme, we start by shifting each character to the next in the alphabet. Using Ruby’s each_char method, we iterate over the string and transform each character.

def character_frequency_encoding(word)
  # Shift each character to the next in the alphabet
  shifted_chars = word.each_char.map do |letter|
    if letter == 'z'
      'a' # Wrap around for 'z'
    else
      (letter.ord + 1).chr # Shift to the next character
    end
  end

At this stage, shifted_chars for "banana" will be ["c", "b", "o", "b", "o", "b"]. This array represents the transformed characters.

Solution Building: Step 2 - Tracking Frequencies

Next, we calculate the frequency of each character in the transformed array. By initializing a hash with a default value of 0, we can easily count occurrences as we iterate through the array of shifted characters.

  # Initialize a frequency hash
  frequency_hash = Hash.new(0)

  # Count the frequency of each character
  shifted_chars.each do |letter|
    frequency_hash[letter] += 1
  end

The frequency_hash now holds the counts of each character. For "banana", it will be:

{"c" => 1, "b" => 3, "o" => 2}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal