In: Computer Science
Must be done in Ruby
Histogram
Create a Ruby program which reads a string of information and uses
a Hash to keep track of letter frequencies and then displays a
Histogram using this frequency information.
IN ORDER TO RECEIVE FULL CREDIT, YOUR CODE SHOULD PROPERLY PROCESS THE STRING INFORMATION, COUNTING FREQUENCIES BY USING A HASH.
A number of different program dialogues describe the program I am looking for.
Enter Data:
supercalifragilisticexpialadocious
A - 4 - ****
C - 3 - ***
D - 1 - *
E - 2 - **
F - 1 - *
G - 1 - *
I - 6 - ******
L - 3 - ***
O - 2 - **
P - 2 - **
R - 2 - **
S - 3 - ***
T - 1 - *
U - 2 - **
X - 1 - *
Kindly find the program as below:
print "Enter Data : "
x = gets.chomp # used to get the input
h = Hash.new #creating Hash
# loop through each character and counting frequencies of them
x.each_char { |w|
if (w != ' ')
if h.has_key?(w)
h[w] = h[w] + 1
else
h[w] = 1
end
end
}
# sorting as per alphabet order and displaying the histogram as required
h.sort{|a,b| a[0]<=>b[0]}.each { |elem|
str =""
$i=1
begin
str = str + "*"
$i +=1
end until $i >elem[1]
puts "\"#{elem[0].capitalize}\" - #{elem[1]} - #{str}"
} # end of program
Find the screenshot s of the code
Output :