Ruby: Standard recursion patterns - ruby

One of the things I commonly get hooked up on in ruby is recursion patterns. For example, suppose I have an array, and that may contain arrays as elements to an unlimited depth. So, for example:
my_array = [1, [2, 3, [4, 5, [6, 7]]]]
I'd like to create a method which can flatten the array into [1, 2, 3, 4, 5, 6, 7].
I'm aware that .flatten would do the job, but this problem is meant as an example of recursion issues I regularly run into - and as such I'm trying to find a more reusable solution.
In short - I'm guessing there's a standard pattern for this sort of thing, but I can't come up with anything particularly elegant. Any ideas appreciated

Recursion is a method, it does not depend on the language. You write the algorithm with two kind of cases in mind: the ones that call the function again (recursion cases) and the ones that break it (base cases). For example, to do a recursive flatten in Ruby:
class Array
def deep_flatten
flat_map do |item|
if item.is_a?(Array)
item.deep_flatten
else
[item]
end
end
end
end
[[[1]], [2, 3], [4, 5, [[6]], 7]].deep_flatten
#=> [1, 2, 3, 4, 5, 6, 7]
Does this help? anyway, a useful pattern shown here is that when you are using recusion on arrays, you usually need flat_map (the functional alternative to each + concat/push).

Well, if you know a bit of C , you just have to visit the docs and click the ruby function to get the C source and it is all there..
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-flatten
And for this case, here is a Ruby implementation
def flatten values, level=-1
flat = []
values.each do |value|
if level != 0 && value.kind_of?(Array)
flat.concat(flatten(value, level-1))
else
flat << value
end
end
flat
end
p flatten [1, [2, 3, [4, 5, [6, 7]]]]
#=> [1, 2, 3, 4, 5, 6, 7]

Here's an example of a flatten that's written in a tail recursive style.
class Array
# Monkeypatching the flatten class
def flatten(new_arr = [])
self.each do |el|
if el.is_a?(Array)
el.flatten(new_arr)
else
new_arr << el
end
end
new_arr
end
end
p flatten [1, [2, 3, [4, 5, [6, 7]]]]
#=> [1, 2, 3, 4, 5, 6, 7]
ruby
Although it looks like ruby isn't always optimized for tail recursion: Does ruby perform tail call optimization?

Related

Ruby inject daisy chaining?

I'm not sure what sugar syntax this is, but let me just show you the problem.
def factors num
(1..num).select {|n| num % n == 0}
end
def mutual_factors(*nums)
nums
.map { |n| factors(n) }
.inject(:&)
end
p mutual_factors(50, 30) # [1, 2, 5, 10]
p mutual_factors(50, 30, 45, 105) # [1, 5]
p mutual_factors(8, 4) # [1, 2, 4]
p mutual_factors(8, 4, 10) # [1, 2]
p mutual_factors(12, 24) # [1, 2, 3, 4, 6, 12]
p mutual_factors(12, 24, 64) # [1, 2, 4]
p mutual_factors(22, 44) # [1, 2, 11, 22]
p mutual_factors(22, 44, 11) # [1, 11]
p mutual_factors(7) # [1, 7]
p mutual_factors(7, 9) # [1]
with this being the portion in questioning:
nums
.map { |n| factors(n) }
.inject(:&)
okay, so this is my mental trace: first, map uses the helper method to get the factors, and outputs the factors into another array, and then that array gets injected?
I think the
.inject(:&)
is what is throwing me off. I ran a quick google on it, but I haven't used inject for many things other than summing arrays, and basic stuff like that. I've also done things like
test = "hello".split("").map(&:upcase)
p test.join
but .inject(:&)? I know & is a proc, but I've only used them in arguments. I don't know the fundamentals under the hood. Please, take my current level into mind when trying to explain this to me =), I know how the basic inject works, and the splat operator also.
Partial quote form the documentation of Enumerable#inject.
inject(symbol) → object
[...]
Returns an object formed from operands via either:
A method named by symbol.
[...]
With method-name argument symbol, combines operands using the method:
# Sum, without initial_operand.
(1..4).inject(:+) # => 10
That means in the context of inject the (:&) is not a proc but simply the symbol :& that tells inject what operation to perform to combine the elements in the array.
Let's look at this example:
mutual_factors(8, 4, 10)
#=> [1, 2]
and let's look what happens at each step:
nums
.map { |n| factors(n) } #=> [[1, 2, 4, 8], [1, 2, 4], [1, 2, 5, 10]]
.inject(:&) #=> [1, 2, 4, 8] & [1, 2, 4] & [1, 2, 5, 10]
And Array#& is a method that returns a new array containing each element found in both arrays (duplicates are omitted).

Can I have a ruby block inside another ruby block?

I have a hash whose keys are a range of integers (lets say [1..5]) and its corresponding 5 values are all nil. I have also an array of integers (lets say [1,2,3,4,5]. What I want to do is very specific: I want to take every single key and add it to every single of the array elements, giving me a hash that has the original keys, but has now for values the entire shifted array.
After spending a few hours I have concluded that this is impossible through a really laconic expression, because it is leading to .each shadowing statements.
I think that the only way to go through with this is to create 5 almost identical methods and call them separately.
def a1
array.each do |x|
x+1
end
end
def a2
array.each do |x|
x+2
end
end
and so on..
The end product I want to achieve is this:
{1=>[2,3,4,5,6],2=>[3,4,5,6,7],3=>[4,5,6,7,8],4=>[5,6,7,8,9],5=>[6,7,8,9,10]}
It feels like there should be a more DRY way to achieve this. Any ideas?
Assuming these initial conditions:
h = {1=>nil, 2=>nil, 3=>nil, 4=>nil, 5=>nil}
arr = [1,2,3,4,5]
...it's pretty straightforward:
h.keys.each do |key|
h[key] = arr.map {|i| i+key}
end
# h is now: {1=>[2, 3, 4, 5, 6], 2=>[3, 4, 5, 6, 7], 3=>[4, 5, 6, 7, 8], 4=>[5, 6, 7, 8, 9], 5=>[6, 7, 8, 9, 10]}
(However, it may be that your question is about achieving the initial conditions. If so, I didn't grasp that, and I didn't worry about it; I just started with what I took to be your initial conditions and ended up with your desired result.)
Why don't you do this
h = {}
rng.each{|i| h[i] = ary.map{|j| j + i}}
That should work where rng is the range and ary is the array.
For example
h = {}
(1..5).each{|i| h[i] = [1,2,3,4,5].map{|j| j+i}}
results in
h = {1=>[2, 3, 4, 5, 6], 2=>[3, 4, 5, 6, 7], 3=>[4, 5, 6, 7, 8], 4=>[5, 6, 7, 8, 9], 5=>[6, 7, 8, 9, 10]}

How do I explode an internal array in Ruby if the internal count is less than a certain value?

Using Ruby 2.1, if I have an array like:
[[1,1], [2,3], [5,8], [6, 4]]
How can I convert that to an array that only has internal arrays with a count > 3?
For example, it should be:
[1, 2, 2, 2, [5,8], [6,4]]
So [5,8] and [6,4] would "pass" because their counts are > 3 but [1,1] and [2,3] would "fail" and explode out because their counts are < than 4.
EDIT
Sorry, I wasn't very clear. By "counts" I mean the second value in the internal arrays. For example, the [2,3] would have a value of 2 and a count of 3. [5,8] would have a value of 5 and a count of 8.
So if the count is > 3 then keep the original array. If the count is 3 or less, then explode the value out count number of times.
I'm pretty sure someone can come up with a better way of doing this, but:
input = [[1,1], [2,3], [5,8], [6, 4]]
input.flat_map {|val, ct| ct > 3 ? [[val, ct]] : Array.new(ct, val) }
# => [1, 2, 2, 2, [5, 8], [6, 4]]
The basic idea is that we just map the inputs (each entry) to an output (the original entry or an exploded list of values) by the count. I'm using flat_map here, but you could use the same technique with map {}.flatten(1) if you wanted. You could also use inject or each_with_object to collect the output values, which may be more straightforward but slightly less terse.
Try this:
data = [[1,1], [2,3], [5,8], [6, 4]]
results = []
data.each do |arr|
val, count = arr
if count > 3
results << arr
else
results.concat [val] * count
end
end
p results
--output:--
[1, 2, 2, 2, [5, 8], [6, 4]]
arr = [[1,1], [2,3], [5,8], [6, 4]]
arr.flat_map { |a| (a.last > 3) ? [a] : [a.first]*a.last }
#=> [1, 2, 2, 2, [5, 8], [6, 4]]
Thanks to #ChrisHeald for pointing out that flat_map is equivalent to map {}.flatten(1) (I previously had the latter) and to #7stud for telling me my original solution was incorrect, which gave me the opportunity to make my solution more interesting as well as (hopefully) correct.

How do I split an array using nil as delimitor?

I'm searching a method for converting:
[1,2,3,nil,4,5,nil,6,7,8,9]
into:
[[1,2,3],[4,5],[6,7,8,9]]
Is there a built-in way to do that in Ruby?
I'd use:
[1,2,3,nil,4,5,nil,6,7,8,9].slice_before{ |e| e.nil? }.map(&:compact)
=> [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
slice_before is really powerful when you want to break an array into chunks, either by searching for a repeating pattern by passing in a regex, or something you can compute via the block. It's much too powerful to summarize right here so take time to read the documentation and play with the examples.
This should work:
array = [1,2,3,nil,4,5,nil,6,7,8,9]
array.inject([[]]) do |result, number|
number ? result.last << number : result << []
result
end
#=> [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Explanation time :-)
inject starts with an array containing an empty array
for each element, it checks if it's nil
if it isn't, it appends the current number to the previous array
if it is, it creates a new empty array
all this while updating result, which is an array of arrays
-- EDIT --
Checking David's reply I checked Rails implementation of this:
def split(value = nil)
using_block = block_given?
inject([[]]) do |results, element|
if (using_block && yield(element)) || (value == element)
results << []
else
results.last << element
end
results
end
end
If you skip the block implementation, it has the exact same structure of my code. Yay! :)
[1,2,3,nil,4,5,nil,6,7,8,9].split(nil)
Whoops array#split is a Rails method
I found kind of an interesting one. There's probably a way to shorten it:
[1,2,3,nil,4,5,nil,6,7,8,9].chunk {|e| e.nil?}.select {|e| not e[0]}.flatten(1).delete_if {|e| not e}
I would join the array and then split the array.
a =[1,2,3,nil,4,5,nil,6,7,8,9]
a = a.join("-").split("--")
a.map! { |a| a.split("-") }
a.map! {|e| e.map! {|f| f.to_i}}
puts a.inspect
#[[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Made edits (based on comments), to make it an integer once again. Still not a good answer though.

Ruby hypothetical - variable nested loops

This is just a thought exercise and I'd be interested in any opinions. Although if it works I can think of a few ways I'd use it.
Traditionally, if you wanted to perform a function on the results of a nested loop formed from arrays or ranges etc, you would write something like this:
def foo(x, y)
# Processing with x, y
end
iterable_one.each do |x|
iterable_two.each do |y|
my_func(x, y)
end
end
However, what if I had to add another level of nesting. Yes, I could just add an additonal level of looping. At this point, let's make foo take a variable number of arguments.
def foo(*inputs)
# Processing with variable inputs
end
iterable_one.each do |x|
iterable_two.each do |y|
iterable_three.each do |z|
my_func(x, y, x)
end
end
end
Now, assume I need to add another level of nesting. At this point, it's getting pretty gnarly.
My question, therefore is this: Is it possible to write something like the below?
[iterable_one, iterable_two, iterable_three].nested_each(my_func)
or perhaps
[iterable_one, iterable_two, iterable_three].nested_each { |args| my_func(args) }
Perhaps passing the arguments as actual arguments isn't feasible, could you maybe pass an array to my_func, containing parameters from combinations of the enumerables?
I'd be curious to know if this is possible, it's probably not that likely a scenario but after it occurred to me I wanted to know.
Array.product yields combinations of enums as if they were in nested loops. It takes multiple arguments. Demo:
a = [1,2,3]
b = %w(a b c)
c = [true, false]
all_enums = [a,b,c]
all_enums.shift.product(*all_enums) do |combi|
p combi
end
#[1, "a", true]
#[1, "a", false]
#[1, "b", true]
#...
You can use product:
[1,4].product([5,6],[3,5]) #=> [[1, 5, 3], [1, 5, 5], [1, 6, 3], [1, 6, 5], [4, 5, 3], [4, 5, 5], [4, 6, 3], [4, 6, 5]]

Resources