Last active
April 19, 2020 15:23
-
-
Save kirylrb/6d06895b68b36d0ea18827cda6beaf84 to your computer and use it in GitHub Desktop.
Smallest positive integer that does not occur in Array in Ruby
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
class Array | |
def sum | |
inject(0) { |sum, x| sum + x } | |
end | |
end | |
def solution(a) | |
# write your code in Ruby 2.2 | |
return unless a.is_a? Array | |
a = a.sort.uniq | |
last_elem = a.last | |
return 1 if last_elem <= 0 | |
first_elem = a.first | |
b = (first_elem..last_elem).to_a | |
c = b.sum - a.sum | |
c > 0 ? c : last_elem+1 | |
end | |
def slow_solution_2(a) | |
a = a.sort.uniq | |
b = (a.first.to_i..a.last.to_i+1).to_a | |
c = (b-a).first.to_i #=> [4, 6] | |
c > 0 ? c : 1 | |
end | |
def slow_solution(a) | |
return unless a.is_a? Array | |
sorted_array = a.sort.uniq | |
first_elem = sorted_array.sort.uniq.first | |
first_from = first_elem >= 0 ? first_elem : 0 | |
n = 0 | |
b = 0 | |
loop do | |
n += 1 | |
b = first_from + n | |
break if !sorted_array.include?(b) && b > 0 | |
end | |
b | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment