Last active
May 18, 2016 20:02
-
-
Save romankovt/a1433f80124671a869037e0d5437394a to your computer and use it in GitHub Desktop.
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 | |
# Write some code, that will flatten an array of arbitrarily nested arrays of | |
# integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
# Your solution should be a link to a gist on gist.github.com | |
# with your implementation. | |
# When writing this code, you can use any language you're comfortable with. | |
# The code must be well tested and documented if necessary, | |
# and in general please treat the quality of the code as if it was ready | |
# to ship to production. | |
# Try to avoid using language defined methods like Ruby's Array#flatten.* | |
require 'benchmark' | |
require 'pp' | |
# flattens any deep level array using recursing strategy | |
class Array | |
def flat | |
each_with_object([]) do |element, obj| | |
if element.kind_of? Array | |
# if element is array call self again with sub-array as an arguement | |
element.flat.each { |sub_element| obj << sub_element } | |
else | |
obj << element | |
end | |
end | |
end | |
end | |
sample1 = [1, 2, [(1..10_000).to_a]] | |
sample2 = [[1, 2], [(1..10_000).to_a]] | |
sample3 = [17, [22, [33, 123], 555, [8, 12, 8]]] | |
sample4 = [[[]]] | |
sample5 = [9, 8, 7, [], 6, [5], [4, 3]] | |
sample6 = [[1, 2, [3]], 4] | |
Benchmark.bm do |x| | |
x.report { 100.times { sample1.flat } } | |
x.report { 100.times { sample2.flat } } | |
x.report { 100.times { sample3.flat } } | |
x.report { 100.times { sample4.flat } } | |
x.report { 100.times { sample5.flat } } | |
x.report { 100.times { sample6.flat } } | |
end | |
# print small arrays just to show it's working properly | |
pp sample3.flat | |
pp sample4.flat | |
pp sample5.flat | |
pp sample6.flat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment