Skip to content

Instantly share code, notes, and snippets.

@nudded
Created March 4, 2020 09:17
Show Gist options
  • Save nudded/fac742cb15b9620539741377fd110445 to your computer and use it in GitHub Desktop.
Save nudded/fac742cb15b9620539741377fd110445 to your computer and use it in GitHub Desktop.
list = 10000000.times.map {rand(10)}
def answer(list)
amount_of_zeros = 0
index = list.size - 1
while index >= 0
if list[index].zero?
amount_of_zeros += 1
elsif amount_of_zeros > 0
list[index], list[index+amount_of_zeros] = list[index+amount_of_zeros], list[index]
end
index -= 1
end
list
end
def answer2(list)
list.partition(&:zero?).flatten!
end
require 'benchmark'
p answer(list.dup) == answer2(list.dup)
Benchmark.bmbm do |x|
x.report("answer1") { answer(list.dup) }
x.report("answer2") { answer2(list.dup) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment