I implemented the Greedy algorithim in ruby using the following code:
class Greedy
def initialize(unit, total, *coins)
@total_coins1 = 0
@total_coins2 = 0
@unit = unit
@total = total
@reset_total = total
@currency = coins.map
@currency.sort!
@currency = @currency.reverse
unless @currency.include?(1)
@currency.push(1)
end
end
def sorter
@currency.each do |x|
@pos = @total / x
@pos = @pos.floor
@total_coins1 += @pos
@total -= x * @pos
puts "#{@pos}: #{x} #{@unit}"
end
puts "#{@total_coins1} total coins"
end
end
When I try to run the code:
x = Greedy.new("cents", 130, 50, 25, 10, 5)
I get an error:
NoMethodError: undefined method `sort!' for #<Enumerator: [50, 25, 10, 5]:map>
from /Users/Solomon/Desktop/Ruby/greedy.rb:9:in `initialize'
from (irb):2:in `new'
from (irb):2
from /Users/Solomon/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
Being very new to Ruby, I have no idea what this means, nor how to fix it, because [50, 25, 10, 5].sort! is a perfectly valid method... How do I fix this error?
Your problem is here: @currency = coins.map
If you call map without a block, it will return an Enumerator. What is it you wanted to map here? If there's nothing you want to do with the values of coins, just assign @currency = coins.sort.reverse and save yourself the sort! and reverse steps.
Enumerator does not have sort method. It belongs to Enumerable. Map method without block returns an enumerator.
In your example you already use * splatten operator so coins is already an array. But if you insist to force converting it, you can use
@currency = coins.to_a
@currency = @currency.sort!
Or just shorten to:
@currency = coins.to_a.sort
to_a method will convert it to array and equivalent to:
coins = coins.map{|x| x}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With