Last active
March 18, 2020 20:47
-
-
Save leon486/2d273f6bd09363f0d1e96d2c702fb737 to your computer and use it in GitHub Desktop.
array flattening exercise written in ruby
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
| =begin | |
| To run this excercise, run this file. | |
| To run tests run: flatten_array_test.rb | |
| =end | |
| require_relative "flatten_array" | |
| input_array = [[1,2,[3]],nil,4,'a',[3,[55,[3]]]] | |
| p flatten_array input_array |
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
| =begin | |
| Recursive array flattening function | |
| Params: | |
| original_array: Array | Array to sort | |
| output: Array | Sorted array | |
| Return: | |
| output: Array | Sorted array | |
| =end | |
| def flatten_array original_array, output = [] | |
| if !original_array.is_a? Array | |
| raise TypeError, "flatten_array() expects an array" | |
| end | |
| original_array.each do |a| | |
| if a.is_a? Array | |
| flatten_array a, output | |
| elsif a.is_a? Integer | |
| output << a | |
| end | |
| end | |
| return output | |
| end |
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
| require_relative "flatten_array" | |
| require "test/unit" | |
| class TestFlattenArray < Test::Unit::TestCase | |
| def test_flatten_array_types | |
| #Function needs one argument | |
| assert_raise(ArgumentError){ flatten_array() } | |
| #Function should not work with plain Ints, only arrays | |
| assert_raise(TypeError){ flatten_array(0) } | |
| end | |
| def test_flatten_array | |
| assert_equal([], flatten_array([]) ) | |
| assert_equal([], flatten_array([nil]) ) | |
| assert_equal([], flatten_array(['e','d']) ) | |
| assert_equal([0,1], flatten_array([0,1]) ) | |
| assert_equal([0,1,2,3], flatten_array([[0,1],[2,3]]) ) | |
| assert_equal([0,1,2,3,4], flatten_array([0,1,[2],[3,4]]) ) | |
| assert_equal([0,1,2,3,4], flatten_array([0,[1,2,[3,[4]]]]) ) | |
| assert_equal([0,1,2,3,4], flatten_array([0,[1,nil,2,[3,['d',4]]]]) ) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment