This was a homework assignment for my students (I am a teaching assistant) in c and I am trying to learn Ruby, so I thought I would code it up. The goal is to read integers from a redirected file and print some simple information. The first line in the file is the number of elements, and then each integer resides on its own line.
This code works (although perhaps inefficiently), but how can I make the code more Ruby-like?
#!/usr/bin/ruby -w
# first line is number of inputs (Don't need it)
num_inputs = STDIN.gets.to_i
# read inputs as ints
h = Hash.new
STDIN.each do |n|
n = n.to_i
h[n] = 1 unless h[n] and h[n] += 1
end
# find smallest mode
h.sort.each do |k,v|
break puts "Mode is: #{k}", "\n" if v == h.values.max
end
# mode unique?
v = h.values.sort
print "Mode is unique: "
puts v.pop == v.pop, "\n"
# print number of singleton odds,
# odd elems repeated odd number times in desc order
# even singletons in desc order
odd_once = 0
odd = Array.new
even = Array.new
h.each_pair do |k, v|
odd_once += 1 if v == 1 and k.odd?
odd << k if v.odd?
even << k if v == 1 and k.even?
end
puts "Number of elements with an odd value that appear only once: #{odd_once}", "\n"
puts "Elements repeated an odd number of times:"
puts odd.sort.reverse, "\n"
puts "Elements with an even value that appear exactly once:"
puts even.sort.reverse, "\n"
# print fib numbers in the hash
class Fixnum
def is_fib?
l, h = 0, 1
while h <= self
return true if h == self
l, h = h, l+h
end
end
end
puts "Fibonacci numbers:"
h.keys.sort.each do |n|
puts n if n.is_fib?
end
I don’t know if this is a “more Ruby way”. At least at is a more “higher-order” way, FWIW.
Not much to say here. Instead of simply looping over
ARGFand setting the hash keys, we usereduceto let it do the work for us. And we use a hash with a default value of0instead of manually checking the keys for existence.We use
Enumerable#dropto simply drop the first line.ARGFis a really cool feature stolen (like most of the scripting features) from Perl: if you simply call the script asscript.rbwithout arguments, thenARGFis the standard input. If, however, you call your script likescript.rb a.txt b.txt, then Ruby will interpret all the arguments as filenames, open all the files for reading andARGFwill be the concatenation of their contents. This allows you to very quickly write scripts that can take their input either via standard input or a file.Ruby doesn’t have an explicit key-value-pair type, instead most looping operations on hashes use two-element arrays. This allows us to refer to the key and the value with
Array#firstandArray#last.In this particular case, we are using
Enumerable#group_byto group the hash into different buckets, and the grouping criterion we use is thelastmethod, i.e. the value which in our hash is the frequency. In other words, we group by frequency.If we now sort the resulting hash, the very last element is the one with the highest frequency (i.e. the mode). We take the last element (the value of the key-value-pair) of that, and then the last element of that, which is an array of key-value-pairs (
number => frequency) of which we extract the keys (the numbers) and sort them.[Note: simply print out the results at every intermediate stage and it’s much easier to understand. Just replace the
modes = ...line above with something like this:]
modesis now a sorted array with all the numbers which have that particular frequency. If we take the first element, we have the smallest mode.And if the size of the array is not
1, then the mode was not unique.It looks like there is a lot going on here, but it’s actually straightforward. You start reading after the equals sign and simply read left to right.
1. IOW, we select all the singletons.now we finally look to the left side of the equals sign:
Enumerable#partitionreturns a two-element array containing the two arrays with the partitioned elements and we use Ruby’s destructuring assignment to assign the two arrays to two variablesputs “Number of elements with an odd value that appear only once: #{odds.size}”
Now that we have a list of odd singletons, their number is simply the size of the list.
This is very similar to the above: select all numbers with an odd frequency, map out the keys (i.e. numbers), sort, reverse and then convert them to a string by joining them together with a comma and space in between.
Again, now that we have a list of even singletons, printing them is just a matter of joining the list elements with commas.
I didn’t feel like refactoring this algorithm to be more efficient and specifically to memoize. I just made some small adjustments.
There was nothing in the algorithm that depended on the number being a certain size, so I pulled the method up into the
Integerclass.And I dropped the
is_prefix. The fact that this is a boolean method is already explicit in the question mark.This probably doesn’t need much explanation: take the keys, sort them, select all Fibonacci numbers and join them together with commas.
Here is an idea for how to refactor this algorithm. There is a very interesting implementation of Fibonacci using a
Hashwith default values for memoizing:It would look a little like this:
If anyone can think of an elegant way to get rid of the
i = 0,i += 1and the wholeuntilloop, I’d appreciate it.