Last active
August 29, 2015 14:26
-
-
Save mikhailov/8298048fbc258de0d50b to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers (can't use Array#flatten built-in method)
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
class Flattenizer | |
def initialize(params) | |
if params.empty? | |
raise ArgumentError, 'Data set is empty' | |
end | |
if !params.is_a?(Array) | |
raise TypeError, 'Data set is not an array' | |
end | |
@input_array = params | |
end | |
def flatten | |
@resulted_array = [] | |
inner_flatten_loop(@input_array) | |
return @resulted_array | |
end | |
private | |
def inner_flatten_loop(inner_array) | |
inner_array.each do |i| | |
if i.is_a?(Fixnum) | |
@resulted_array << i | |
elsif i.is_a?(Array) | |
inner_flatten_loop(i) | |
end | |
end | |
end | |
end | |
require 'minitest/autorun' | |
class TestFlattenizer < Minitest::Unit::TestCase | |
def test_that_array1_flattens | |
object = Flattenizer.new([[1,2,[3]],4]).flatten | |
assert_equal( [1,2,3,4], object ) | |
end | |
def test_that_array2_flattens | |
object = Flattenizer.new([[1,2,[3],[[1]]],[1],[[[[3]]]],4]).flatten | |
assert_equal( [1,2,3,1,1,3,4], object ) | |
end | |
def test_that_array3_flattens | |
object = Flattenizer.new([[1,2,[3]],"","bug",4]).flatten | |
assert_equal( [1,2,3,4], object ) | |
end | |
def test_that_string_doesnt_flatten | |
assert_raises( TypeError ) { Flattenizer.new("string not an array") } | |
end | |
def test_that_empty_array_doesnt_flatten | |
assert_raises( ArgumentError ) { Flattenizer.new([]) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment