Last active
March 7, 2021 13:56
-
-
Save rainyjonne/7b3185e9e5869749e0a6272fb61d16b0 to your computer and use it in GitHub Desktop.
short_string_packer.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Packs/Unpacks a String to and from an Integer | |
class ShortStringPacker | |
## Packs a short string into a Integer | |
# Arguments: | |
# str - String object | |
# Returns: a Integer object | |
def self.pack(str) | |
# IMPLEMENT THIS METHOD | |
mapping_hash = Hash[('a'..'z').to_a.zip(1..26)] | |
chars = str.split('') | |
bit_arr = chars.map do |char| | |
mapping_hash[char].to_s(2).rjust(5, '0') | |
end | |
bit_arr.join('').to_i(2) | |
end | |
## Unpacks a Integer from pack() method into a short string | |
# Arguments: | |
# packed - a Integer object | |
# Returns: a String object | |
def self.unpack(packed) | |
# IMPLEMENT THIS METHOD | |
bit_arr = packed.to_s(2).reverse.scan(/.{1,5}/).join(',').reverse.split(',') | |
mapping_hash = Hash[(1..26).to_a.zip('a'..'z')] | |
str_arr = bit_arr.map do |ele| | |
int = ele.to_i(2) | |
mapping_hash[int] | |
end | |
str_arr.join('') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment