Skip to content

Instantly share code, notes, and snippets.

@gcasa
Created May 6, 2019 19:03
Show Gist options
  • Save gcasa/6a6b36f0a952501b0a8348319ec21816 to your computer and use it in GitHub Desktop.
Save gcasa/6a6b36f0a952501b0a8348319ec21816 to your computer and use it in GitHub Desktop.
# you can write to stdout for debugging purposes, e.g.
# puts "this is a debug message"
# Scores 66%, not sure why.
def solution(a)
# write your code in Ruby 2.2
# Exclude any arrays which aren't long enough to have adjacent pairs
if a.length == 0 || a.length == 1
return 0
end
# Sort array in place so that we may more easily detect adj pairs
# in O(n) time as opposed to O(n^3)
a.sort!
pr = a[0] # Seed the previous var
cc = 1
pc = 0
adjc = 0
min = 100000000
d = 0
(1..(a.length - 1)).each do |i|
# if we have something equal to the previous value we set the min to 0
if a[i] == pr
min = 0
cc = cc + 1
adjc += pc + cc - 1
else
d = (a[i] - pr).abs
if(d < min)
min = d
end
adjc += cc
pc = cc
cc = 1
end
pr = a[i]
end
return -1 if min > 100000000
return -2 if adjc == 0
return min
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment