Created
September 21, 2017 04:00
-
-
Save gcasa/62ab73bb44aa59ca3479c59f49eb3aef to your computer and use it in GitHub Desktop.
Recursively flatten an array without using built-in methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
require 'test/unit' | |
require 'test/unit/ui/console/testrunner' | |
class Array | |
# Flatten the Array of nested arrays recursively | |
# without using any pre-written methods. | |
def flatten_array(result = []) | |
self.each do |element| | |
if element.instance_of?( Array ) | |
element.flatten_array(result) | |
else | |
result.push(element) | |
end | |
end | |
result | |
end | |
end | |
class ArrayTest < Test::Unit::TestCase | |
# Main test case | |
def test_array | |
array = [[1,2,[3]],4] | |
expected_result = [1,2,3,4] | |
actual_result = array.flatten_array | |
puts "Result: #{actual_result}" | |
assert_equal expected_result, actual_result, 'Arrays are not equal!' | |
end | |
def test_array_individual_nesting | |
array = [[[1],[2],[3]],[4]] | |
expected_result = [1,2,3,4] | |
actual_result = array.flatten_array | |
puts "Result: #{actual_result}" | |
assert_equal expected_result, actual_result, 'Arrays are not equal!' | |
end | |
def test_array_multiple_nesting | |
array = [[[1],[[[2]]],[3]],[4]] | |
expected_result = [1,2,3,4] | |
actual_result = array.flatten_array | |
puts "Result: #{actual_result}" | |
assert_equal expected_result, actual_result, 'Arrays are not equal!' | |
end | |
end | |
# Run it... | |
my_tests = Test::Unit::TestSuite.new('Array tests') | |
my_tests << ArrayTest.new('test_array') | |
my_tests << ArrayTest.new('test_array_individual_nesting') | |
my_tests << ArrayTest.new('test_array_multiple_nesting') | |
Test::Unit::UI::Console::TestRunner.run(my_tests) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment