Turning a method into an enumerable method - ruby

I rewrote the map method:
def my_map(input, &block)
mod_input = []
x = -1
while x < input.length - 1
x = x + 1
if block == nil
return input
break
end
mod_input.push(block.call(input[x]))
end
return mod_input
end
I need to call this code as I would call map or reverse. Does anyone know the syntax for that?

Are you asking how you put a method into a module? That's trivial:
module Enumerable
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
if block == nil
return self
break
end
mod_input.push(block.call(self[x]))
end
return mod_input
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
Or are you asking how to make your method an Enumerable method? That's more involved: your method currently uses many methods that are not part of the Enumerable API. So, even if you make it a member of the Enumerable module, it won't be an Enumerable method. Enumerable methods can only use each or other Enumerable methods. You use length and [] both of which are not part of the Enumerable interface, for example, Set doesn't respond to [].
This would be a possible implementation, using the Enumerable#inject method:
module Enumerable
def my_map
return enum_for(__method__) unless block_given?
inject([]) {|res, el| res << yield(el) }
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
A less elegant implementation using each
module Enumerable
def my_map
return enum_for(__method__) unless block_given?
[].tap {|res| each {|el| res << yield(el) }}
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
Note that apart from being simply wrong, your code is very un-idiomatic. There is also dead code in there.
the break is dead code: the method returns in the line just before it, therefore the break will never be executed. You can just get rid of it.
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
if block == nil
return self
end
mod_input.push(block.call(self[x]))
end
return mod_input
end
Now that we have gotten rid of the break, we can convert the conditional into a guard-style statement modifier conditional.
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
return self if block == nil
mod_input.push(block.call(self[x]))
end
return mod_input
end
It also doesn't make sense that it is in the middle of the loop. It should be at the beginning of the method.
def my_map(&block)
return self if block == nil
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
return mod_input
end
Instead of comparing an object against nil, you should just ask it whether it is nil?: block.nil?
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
return mod_input
end
Ruby is an expression-oriented language, the value of the last expression that is evaluated in a method body is the return value of that method body, there is no need for an explicit return.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
mod_input
end
x = x + 1 is more idiomatically written x += 1.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input.push(block.call(self[x]))
end
mod_input
end
Instead of Array#push with a single argument it is more idiomatic to use Array#<<.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << block.call(self[x])
end
mod_input
end
Instead of Proc#call, you can use the .() syntactic sugar.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << block.(self[x])
end
mod_input
end
If you don't want to store, pass on or otherwise manipulate the block as an object, there is no need to capture it as a Proc. Just use block_given? and yield instead.
def my_map
return self unless block_given?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << yield(self[x])
end
mod_input
end
This one is opinionated. You could move incrementing the counter into the condition.
def my_map
return self unless block_given?
mod_input = []
x = -1
while (x += 1) < length
mod_input << yield(self[x])
end
mod_input
end
And then use the statement modifier form.
def my_map
return self unless block_given?
mod_input = []
x = -1
mod_input << yield(self[x]) while (x += 1) < length
mod_input
end
Also, your variable names could use some improvements. For example, what does mod_input even mean? All I can see is that it is what you output, so why does it even have "input" in its name? And what is x?
def my_map
return self unless block_given?
result = []
index = -1
result << yield(self[index]) while (index += 1) < length
result
end
This whole sequence of initializing a variable, then mutating the object assigned to that variable and lastly returning the object can be simplified by using the K Combinator, which is available in Ruby as Object#tap.
def my_map
return self unless block_given?
[].tap {|result|
index = -1
result << yield(self[index]) while (index += 1) < length
}
end
The entire while loop is useless. It's just re-implementing Array#each, which is a) unnecessary because Array#each already exists, and b) means that your my_map method will only work with Arrays but not other Enumerables (for example Set or Enumerator). So, let's just use each instead.
def my_map
return self unless block_given?
[].tap {|result|
each {|element|
result << yield(element)
}
}
end
Now it starts to look like Ruby code! What you had before was more like BASIC written in Ruby syntax.
This pattern of first creating a result object, then modifying that result object based on each element of a collection and in the end returning the result is very common, and it even has a fancy mathematical name: Catamorphism, although in the programming world, we usually call it fold or reduce. In Ruby, it is called Enumerable#inject.
def my_map
return self unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
That return self is strange. map is supposed to return a new object! You don't return a new object, you return the same object. Let's fix that.
def my_map
return dup unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
And actually, map is also supposed to return an Array, but you return whatever it is that you called map on.
def my_map
return to_a unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
But really, if you look at the documentation of Enumerable#map, you will find that it returns an Enumerator and not an Array when called without a block.
def my_map
return enum_for(:my_map) unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
And lastly, we can get rid of the hardcoded method name using the Kernel#__method__ method.
def my_map
return enum_for(__method__) unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
Now, that looks a lot better!

class Array
def my_map(&block)
# your code, replacing `input` with `self`
end
end
The code itself is not really idiomatic Ruby - while is very rarely used for iteration over collections, and if you don't need to pass a block somewhere else, it is generally cleaner to use block_given? instead of block.nil? (let alone block == nil), and yield input[x] instead of block.call(input[x]).

Related

How to implement Java's Comparable module in Ruby

I'm currently going over Robert Sedgewick's Algorithms book. In the book for the implementation of a Priority Queue there is the use of the Comparable module. While going over the top k frequent elements leetcode problem I noticed that there would be an error in my Ruby implementation.
def top_k_frequent(nums, k)
ans = []
h = Hash.new(0)
nums.each do |num|
h[num] += 1
end
heap = Heap.new
h.each do |k,v|
heap.insert({k => v})
end
k.times do
a = heap.del_max
ans.push(a.keys[0])
end
ans
end
class Heap
def initialize
#n = 0
#pq = []
end
def insert(v)
#pq[#n += 1] = v
swim(#n)
end
def swim(k)
while k > 1 && less((k / 2).floor, k)
swap((k / 2).floor, k)
k = k/2
end
end
def swap(i, j)
temp = #pq[i]
#pq[i] = #pq[j]
#pq[j] = temp
end
def less(i, j)
#pq[i].values[0] < #pq[j].values[0]
end
def del_max
max = #pq[1]
swap(1, #n)
#n -= 1
#pq[#n + 1] = nil
sink(1)
max
end
def sink(k)
while 2 * k <= #n
j = 2 * k
if !#pq[j + 1].nil?
j += 1 if j > 1 && #pq[j].values[0] < #pq[j + 1].values[0]
end
break if !less(k, j)
swap(k, j)
k = j
end
end
end
Above is the Java Priority Queue implementation.
Ruby's comparable operator is <=> which will return one of -1, 0, 1 and nil (nil mean could not compare).
In order to compare two objects , both need to implement a method def <=>(other). This is not on Object, so is not available on any objects that don't implement it or extend from a class that does implement it. Numbers and Strings, for example, do have an implementation. Hashes do not.
I think in your case, the issue is slightly different.
When you call queue.insert(my_hash) what you're expecting is for the algorithm to break up my_hash and build from that. Instead, the algorithm takes the hash as a single, atomic object and inserts that.
If you add something like:
class Tuple
attr_accessor :key, :value
def initialize(key, value)
#key = key
#value = value
end
def <=>(other)
return nil unless other.is_a?(Tuple)
value <=> other.value
end
end
then this will allow you to do something like:
hsh = { 1 => 3, 2 => 2, 3 => 1}
tuples = hsh.map { |k, v| Tuple.new(k, v) }
tuples.each { |tuple| my_heap.insert(tuple) }
you will have all of your data in the heap.
When you retrieve an item, it will be a tuple, so you can just call item.key and item.value to access the data.

Ruby Program to solve Circular Primes below number x

I'm working on project Euler #35. I am getting the wrong number returned and I can't find where I have done wrong!
def is_prime?(num)
(2..Math.sqrt(num)).each { |i| return false if num % i == 0}
true
end
def is_circular?(num)
len = num.to_s.length
return true if len == 1
(len - 1).times do
new_n = cycle(num)
break unless is_prime?(new_n)
end
end
def cycle(num)
ary = num.to_s.split("")
return ary.rotate!.join.to_i
end
def how_many
circulars = []
(2..1000000).each do |num|
if is_prime?(num) && is_circular?(num)
circulars << num
end
end
p circulars.count
end
how_many #=> 14426
The returned number is '14426'. I am only returning the circular primes, supposedly the correct answer is '55'
I have edited your code with few fixes in Ruby way. Your mistake was including corect set of [a, b, c] three times to count, instead of counting them as a one circular prime number. Your answer was correct, while 55 is the number of unique sets.
require 'prime'
class Euler35
def is_circular?(num)
circulars_for(num).all?{ |el| ::Prime.instance.prime?(el) }
end
def circulars_for(a)
a.to_s.split("").length.times.map{|el| a.to_s.split("").rotate(el).join.to_i }
end
def how_many
circulars = []
::Prime.each(1_000_000) do |num|
continue if circulars.include?(num)
if is_circular?(num)
circulars << circulars_for(num)
end
end
circulars.count
end
end
puts Euler35.new.how_many # => 55

How does the memo in #inject work?

I'm trying to use a while loop inside #inject. However, the last memo becomes nil at some point and I don't understand why. Here is my example (I use #each on the example just to show the expected result):
class TestClass
BASE_ARRAY = [5, 1]
def test_method(value)
result = []
BASE_ARRAY.each do |item|
while item <= value
result << item
value -= item
end
end
result
end
def test_method_alternate(value)
BASE_ARRAY.inject do |memo, item|
while item <= value
p memo
# memo << item (if left, returns NoMethodError for nil Class)
value -= item
end
end
end
end
solution_one = TestClass.new.test_method(11)
p solution_one # => [5, 5, 1]
solution_two = TestClass.new.test_method_alternate(11)
p solution_two
# => []
[]
nil
How does the accumulator become nil?
You're getting nil initially from the while loop:
The result of a while loop is nil unless break is used to supply a value.
That result becomes the result of other statements in a chain:
while
-> do |memo, item|
-> BASE_ARRAY.inject
-> test_method_alternate(11)
-> solution_two
To have .inject fill up an array, you'll want to provide an empty array to use as the first memo:
BASE_ARRAY.inject([]) do |memo, item|
# ... ^^^^
Then, be sure the array is the result of the block:
... do |memo, item|
while item <= value
memo << item
value -= item
end
memo # <---
end
Two things:
You need to initialize the memo with a value, in this case, you'll want a [].
You need to return the memo on each iteration of inject.
So, you should get your desired result of [5, 5, 1] by changing your method to be like this:
def test_method_alternate(value)
BASE_ARRAY.inject([]) do |memo, item|
while item <= value
memo << item
value -= item
end
memo
end
end

Defining my_times Enumerator based on my_each Enumerator?

Say that I have my own implementation of each:
class Array
def my_each
c = 0
until c == size
yield(self[c])
c += 1
end
self
end
end
How would I do my own implementation of times by using my_each? Here is my approach:
class Integer
def my_times
Array.new(self) { |i| i }.my_each do |el|
yield el
end
end
end
But I don't particularly like it because I am creating an Array. But, is there any other way I could accomplish this?
You could do it like this:
class Integer
def my_times
return (0...self).to_enum unless block_given?
(0...self).each { |i| yield i }
end
end
5.my_times { |i| puts i*i }
0
1
4
9
16
5.my_times #=> #<Enumerator: 0...5:each>
I have used Range#each. To use Array#my_each we'd have to convert the range to an array:
[*(0...self)].my_each { |i| yield i }
Recall that Integer#times returns an enumerator if no block is given. The same is true of Array#each; you need to fix my_each for it to be equivalent to Array#each.
You don't need each or my_each, however:
class Integer
def my_times
return (0...self).to_enum unless block_given?
i = 0
while(i < self) do
yield i
i += 1
end
end
end
5.my_times { |i| puts i*i }
0
1
4
9
16
5.my_times #=> #<Enumerator: 0...5:each>

Stack level too deep error in ruby's recursive call

I am trying to implement the quick sort algorithm using ruby. See what I did:
class Array
def quick_sort #line 14
less=[];greater=[]
if self.length<=1
self[0]
else
i=1
while i<self.length
if self[i]<=self[0]
less << self[i]
else
greater << self[i]
end
i=i+1
end
end
less.quick_sort + self[0] + greater.quick_sort #line 29
end
end
[1,3,2,5,4].quick_sort #line 32
This generated the error:
bubble_sort.rb:29:in `quick_sort': stack level too deep (SystemStackError)
from bubble_sort.rb:29:in `quick_sort'
from bubble_sort.rb:32
Why is this happening?
I think the problem in your example was you needed an explicit return.
if self.length<=1
self[0]
should have been
return [] if self == []
and
less.quick_sort + self[0] + greater.quick_sort #line 29
should have been
less.quick_sort + [self[0]] + greater.quick_sort #line 29
Here is a working example
class Array
def quick_sort
return [] if self == []
pivotal = self.shift;
less, greater = [], []
self.each do |x|
if x <= pivotal
less << x
else
greater << x
end
end
return less.quick_sort + [pivotal] + greater.quick_sort
end
end
[1,3,2,5,4].quick_sort # => [1, 2, 3, 4, 5]
less.quick_sort + self[0] + greater.quick_sort
This line is outside of the if statement, so it gets executed whether self.length<=1 is true or not. Consequently the method recurses infinitely, which causes the stack to overflow.
It should also be pointed out that self[0] does not return an array (unless self is an array of arrays), so it does not make sense to use Array#+ on it. Nor does it make sense as a return value for your quick_sort method.
In that part you should not handle the "=" case. Only < and > should be handled. Therefore your algorithm never stops and causes an infinite recursion.
if self[i]<=self[0]
less << self[i]
else
greater << self[i]
end

Resources