Skip to content

Instantly share code, notes, and snippets.

@overloadedargs
Created April 21, 2020 12:43
Show Gist options
  • Save overloadedargs/9f99d560c020ac5c2631962b9ef5c544 to your computer and use it in GitHub Desktop.
Save overloadedargs/9f99d560c020ac5c2631962b9ef5c544 to your computer and use it in GitHub Desktop.
Longest distance between identical numbers in a list ignoring identical numbers in between
# Longest distance between identical numbers in a list ignoring identical numbers in between
# e.g. input number of numbers 5, then each number followed by a return
# use gets.chomp to get console input
n = gets.chomp.to_i
h = Hash.new
(1..n).each do |i|
n = gets.chomp.to_i
if h[n]
h[n] << i
else
h[n] = [i]
end
end
count = 0
max_distance = 0
p h
# Could check in the loop here using a boolean if
# there were any array length > 1 to save looping
# twice with the.any? call
h.each do |key, array|
if array.length > 1
count += array.combination(2).to_a.length
dist = array.max - array.min
max_distance = dist if dist > max_distance
end
end
if h.values.any? {|arr| arr.length > 1}
puts count
puts "distance: #{max_distance}"
else
p "NA"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment