2

I have an n-depth array where n is a variable greater than or equal to 2:

[[1,1],[[1,1],[1,1]]]

I want to flatten this array to have exactly 2 depth, like this:

[[1,1],[1,1],[1,1]]

Can anyone think of a good way to achieve that?

2
  • 1
    It's unclear how you want the output; e.g. why does [[1,1],[1,1]] become [1,1], [1,1] and not [1,1,1,1]? Commented Mar 2, 2016 at 0:27
  • More cases may be necessary to get anything useful. But first, what have you tried? Perhaps #flatten with a level parameter? Anything? Commented Mar 2, 2016 at 1:52

3 Answers 3

3

This should do it.

def flatten_after_first(arr)
  arr.flat_map { |a| a.first.is_a?(Array) ? a.map(&:flatten) : [a] }
end

flatten_after_first [[1,1],[[1,1],[1,1]]]
  #=> [[1, 1], [1, 1], [1, 1]]

flatten_after_first [[1,1], [[2,2], [2,2]], [[[3,3], [3,3]], [[3,3], [3,3]]]] 
  #=> [[1, 1], [2, 2], [2, 2], [3, 3, 3, 3], [3, 3, 3, 3]]
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, the OP threw everyone off by writing "depth first" in the title. The example he gave in the question is not the result you would get with depth first flatten. But it looks like your answer is what he wants.
1

May be this will help

def flat(array)
  array.each do |item|
    if item.is_a?(Array) && item.flatten.count != item.count
      flat(item)
    else
      $arr << item
    end
  end
end

###
$arr = []
collection = [[1, 1], [[1, 1], [1, 1], [[1, 2], [1, 2, 3]]]]
flat(collection)
puts $arr.inspect

=> [[1, 1], [1, 1], [1, 1], [1, 2], [1, 2, 3]]


$arr = []
collection = [[1,1],[[[1,1],[1,1]],[1,1]]]
flat(collection)
$arr
=> [[1, 1], [1, 1], [1, 1], [1, 1]]

Comments

0

Try this:

def depth_first_flatten array
  result = []
  array.each do |element|
    if element.first.is_a? Array
      result += deph(element)
    else
      result << element
    end
  end
  result
end

# array = [[1,2],[[3,4],[5,6]]]
# depth_first_flatten(array)
#
# OUTPUT: [[1, 2], [3, 4], [5, 6]]

3 Comments

I also tested with: array = [[1, 2], [[3, 4], [5, 6]], [[[[[7, 8], [9, 10]]]]]] with the output [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
Tested array = [[1, 1], [[1, 1], [1, 1], [[1, 2], [1, 2, 3]]]] and output: [[1, 1], [1, 1], [1, 1], [1, 2], [1, 2, 3]]
Nice challenge! I liked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.