Skip to content

Instantly share code, notes, and snippets.

@sukhchander
Last active April 19, 2016 21:02
Show Gist options
  • Save sukhchander/d258c932689fa356cca9553db87b5722 to your computer and use it in GitHub Desktop.
Save sukhchander/d258c932689fa356cca9553db87b5722 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
class Array
def flatflat
result = []
self.each do |elem|
if elem.is_a?(Array)
result.concat(elem.flatflat)
else
result.push(elem)
end
end
result
end
end
require 'test/unit'
class ArrayTest < Test::Unit::TestCase
def test_flatflat
arr = [[[]],[],[],[],[]]
assert_equal( [], arr.flatflat )
arr = [1, 2, 3, [[4,5,]], 6, 7, [8,9], 10, 11, [12]]
assert_equal( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], arr.flatflat )
end
end
require 'benchmark'
ARRAY = 10000.times.map { |i| rand(10000) }
ITERATIONS = 10000
Benchmark.bm do |benchmark|
puts "#{ITERATIONS} iterations"
benchmark.report("Array.flatten") do
ITERATIONS.times { |i| ARRAY.flatten }
end
benchmark.report("Array.flatflat") do
ITERATIONS.times { |i| ARRAY.flatflat }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment