Last active
April 18, 2016 14:15
-
-
Save pca2/dba3931cd72bde69fa3ba83eb3cf60f6 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers
This file contains 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
#! /usr/bin/env ruby | |
def flatize(array) | |
error_msg = 'Method only accepts nested arrays of integers' | |
raise ArgumentError, error_msg unless array.is_a? Array | |
flattened_array = [] | |
array.each do |element| | |
if element.is_a? Array | |
flattened_array += flatize(element) | |
else | |
raise ArgumentError, error_msg unless element.is_a? Integer | |
flattened_array << element | |
end | |
end | |
return flattened_array | |
end |
This file contains 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
#! /usr/bin/env ruby | |
require 'minitest/autorun' | |
require_relative 'flatize.rb' | |
class FlatTest < Minitest::Test | |
def test_simple | |
assert_equal [1,2,3,4], flatize([[1,2,[3]],4]) | |
end | |
def test_deep_nest | |
assert_equal [1,2,3,5,14], flatize([[1,2,[3]],[],[[5,[[[14]]]]]]) | |
end | |
def test_bignum | |
assert_equal [4,6,98,11111111111111111111], flatize([4,6,98,[[11111111111111111111]]]) | |
end | |
def test_empty_param | |
assert_equal [], flatize([]) | |
end | |
def test_invalid_array_elements | |
assert_raises(ArgumentError) {flatize(['foo',0.65,nil])} | |
end | |
def test_non_array_param | |
assert_raises(ArgumentError) {flatize('bar')} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment