Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
my first functional ruby
def reorder_numbers
reload_relations
return if pages.empty?
# this solution has a time complexity of O(log n)
get_missing_number = lambda { |source, min = 0, max = (source.length - 1)|
if min >= max
return false if min + 1 == source.max
return min + 1
end
pivot = ((min + max) / 2).floor
# problem is in right side. Only look at right sub array
return get_missing_number.call(source, pivot + 1, max) if source[pivot] == pivot + 1
get_missing_number.call(source, min, pivot)
}
get_next_existing_box = lambda { |number, pages|
next_number = pages.pluck(:number).sort.select { |i| i > number }.min
pages.find_by(number: next_number)
}
reset_box_number = lambda { |page, number|
page.number = number
page.save!
}
func = lambda {
num = get_missing_number.call(pages.pluck(:number).sort)
box = get_next_existing_box.call(num, pages)
reset_box_number.call(box, num)
reload_relations
func.call if get_missing_number.call(pages.pluck(:number).sort)
}
func.call if get_missing_number.call(pages.pluck(:number).sort)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.