Last active
December 18, 2015 00:09
-
-
Save rkjha/5694490 to your computer and use it in GitHub Desktop.
First ruby program reads a file containing numbers (separated by space), and calculates the each occurrence of the number (a.k.a frequency distribution). Second one, simply prints a number from 1 to n with the condition (if it's divisible by 3 then Hip, divisible by 5, then Hop, and if it's divisible by both 3 and 5, then it prints Whazaa)
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
# assuming the file is there in the same dir as numbers.txt | |
file = File.open("numbers.txt", 'r') | |
frequency_db = Hash.new | |
file.each_line do |line| | |
line_n = line.split | |
line_n.each do |n| | |
if frequency_db.has_key?(n) | |
frequency_db[n]+=1 | |
else | |
frequency_db.store(n,1) | |
end | |
end | |
end | |
#now displays the frequency distribution | |
frequency_db.each do |number, frequency| | |
puts "#{number}: #{frequency}" | |
end |
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
def take_n n | |
number = n.to_i | |
i=1 | |
while i<= number do | |
if i%3 == 0 | |
if i%5 == 0 | |
puts "Whazaa" | |
else | |
puts "Hip" | |
end | |
elsif i%5 ==0 | |
puts "Hop" | |
else | |
puts i | |
end | |
i = i+1 | |
end | |
end | |
# get first number as the input (e.g ruby file_name.rb 20) | |
take_n ARGV[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment