Last active
September 8, 2022 15:14
-
-
Save deHelden/f5b1e6ec2f4173a921770cba39de1048 to your computer and use it in GitHub Desktop.
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
## Task 1 | |
# find closest border number in fib sequence | |
# near_fib_number(9) => 8 | |
# near_fib_number(12) => 13 | |
require 'benchmark' | |
def near_fib_number(num) | |
start_array = [0, 1] | |
while !(start_array[0] <= num && start_array[1] >= num) do | |
start_array[2] = start_array[0] + start_array[1] | |
start_array.shift | |
end | |
left_diff = (num - start_array[0]).abs | |
puts "left_diff: #{left_diff}" | |
right_diff = (num - start_array[1]).abs | |
puts "right_diff: #{right_diff}" | |
if left_diff < right_diff | |
puts start_array[0] | |
else | |
puts start_array[1] | |
end | |
end | |
near_fib_number(8) | |
#=> | |
# left_diff: 3 | |
# right_diff: 0 | |
# 8 | |
near_fib_number(9) | |
# left_diff: 1 | |
# right_diff: 4 | |
# 8 | |
near_fib_number(12) | |
# left_diff: 4 | |
# right_diff: 1 | |
# 13 | |
near_fib_number(14) | |
# left_diff: 1 | |
# right_diff: 7 | |
# 13 | |
near_fib_number(20) | |
# left_diff: 7 | |
# right_diff: 1 | |
# 21 | |
Benchmark.bm do |x| | |
# user system total real | |
x.report {near_fib_number(12)} | |
# 0.000009 0.000005 0.000014 ( 0.000011) | |
x.report {near_fib_number(2_000_000)} | |
# 0.000005 0.000003 0.000008 ( 0.000007) | |
x.report {near_fib_number(200_000_000)} | |
# 0.000006 0.000002 0.000008 ( 0.000008) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment