Reputation: 1
I'm to write a method in Ruby that partitions an array based on a proc, both passed in the arguments. Here is my full method:
def proctition(arr, &prc)
failed = []
passed = []
debugger
if arr != arr.flatten
passed.push(*arr[0])
arr[1].each_with_index do |ele, i|
if prc.call(ele)
passed.push(ele)
remainder = arr[1].pop(arr.size - i + 1)
self.proctition([passed, remainder], &prc)
else
failed.push(ele)
remainder = arr[1].pop(arr.size - i + 1)
self.proctition([passed, remainder], &prc)
end
end
else
[*passed, *failed]
end
end
As far as I know there's no method that selectively both removes an element from an array and evaluates to those removed elements like pop() does for the last default 1 or however many digits you specify. I was able to figure out how to use recursion to my advantage in a previous method and I feel the solution is along this track. My strategy was to populate passed and failed arrays that maintain their scope through each level of recursion, with my recursive call to my method passing a 2D array, I then added what I thought would be a simple check at the beginning whether or not an array is 2D or not
arr != arr.flatten
and I have run this exact statement through pry during the runtime of this program, and gotten what I expected this statement to evaluate to in the original method call: false, which is to say that this array is the same as the array when you 'flatten' it by a call to the method by the same name. And then within this if block I do the sorting and pruning and the recursive call on the pruned array. However, in actual execution it must be evaluating to the opposite as it goes right to the else block to return an empty concatenation of arrays.
Upvotes: -1
Views: 74
Reputation: 36620
It's unclear why you're iterating over your array while trying to modify it and trying to use recursion. It appears a very overthought and overcomplicated solution for a very straightforward problem.
def proctition(arr, &prc)
good, bad = [], []
arr.each do |x|
if prc.call(x)
good << x
else
bad << x
end
end
[*good, *bad]
end
And now:
irb(main):012:0> proctition([1, 2, 3, 4], &:even?)
=> [2, 4, 1, 3]
Upvotes: 1