Skip to content

Instantly share code, notes, and snippets.

@atzkey
Created March 24, 2020 18:45
Show Gist options
  • Save atzkey/75c7aa493db4bbd2557456989837d85f to your computer and use it in GitHub Desktop.
Save atzkey/75c7aa493db4bbd2557456989837d85f to your computer and use it in GitHub Desktop.
Theorem screening question
# An idiomatic Ruby mixin to Array-like classes.
module ArrayX
# A re-implementation of the native `Array#flatten` method.
# Returns a one-dimensional flattened version of `self`,
# or flattens it to a degree, specified by `level`.
#
# @param level [Number] level of recursion
# @return [Array] flattened array
def smoothen(level = -1)
return self if level == 0
inject([]) do |acc, x|
if x.respond_to? :smoothen
acc + x.smoothen(level - 1)
else
acc + [x]
end
end
end
end
if __FILE__ == $0
require 'test/unit'
Array.include(ArrayX)
class TestArrayX < Test::Unit::TestCase
def test_smoothening_of_arrays
assert_equal [], Array.new([]).smoothen
arr = Array.new([[0], 1, [2, [3, [4, [5], 6], 7], 8], 9])
assert_equal [[0], 1, [2, [3, [4, [5], 6], 7], 8], 9], arr.smoothen(0)
assert_equal [0, 1, 2, [3, [4, [5], 6], 7], 8, 9], arr.smoothen(1)
assert_equal [0, 1, 2, 3, [4, [5], 6], 7, 8, 9], arr.smoothen(2)
assert_equal [0, 1, 2, 3, 4, [5], 6, 7, 8, 9], arr.smoothen(3)
assert_equal [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], arr.smoothen(4)
assert_equal [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], arr.smoothen(5)
assert_equal [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], arr.smoothen(-1)
assert_equal [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], arr.smoothen
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment