Skip to content

Instantly share code, notes, and snippets.

@j3ck
Created November 7, 2021 22:35
Show Gist options
  • Save j3ck/f81cb1bf2698285b1f7027550451b497 to your computer and use it in GitHub Desktop.
Save j3ck/f81cb1bf2698285b1f7027550451b497 to your computer and use it in GitHub Desktop.
# https://www.codewars.com/kata/52b7ed099cdc285c300001cd/train/ruby
require 'pry'
def sum_of_intervals(intervals)
res = intervals
del = []
new_res = []
stop = false
while true do
res.each_with_index do |root_interval, index|
res[(index + 1)...res.size].each do |interval|
# root поглощает проверяемый интервал
if root_interval[0] < interval[0] && root_interval[1] > interval[1]
new_res << root_interval if new_res.index(root_interval).nil?
del << interval if del.index(interval).nil?
next
end
# проверяемый поглощает root
if interval[0] < root_interval[0] && interval[1] > root_interval[1]
new_res << interval if new_res.index(interval).nil?
del << root_interval if del.index(root_interval).nil?
next
end
#обьединение
if root_interval[1] > interval[0] && root_interval[1] <= interval[1] || (interval[1] > root_interval[0] && interval[1] <= root_interval[1])
new_int = [[root_interval[0], interval[0]].min, [root_interval[1], interval[1]].max]
new_res << new_int if new_res.index(new_int).nil?
del << root_interval if del.index(root_interval).nil? && new_int != root_interval
del << interval if del.index(interval).nil? && new_int != interval
next
end
# если не одно действие не сработал, добавляем оба элемента
new_res << root_interval if new_res.index(root_interval).nil?
new_res << interval if new_res.index(interval).nil?
end
# p "res: #{res}"
# p "new_res: #{new_res}"
# p "del: #{del}"
# p "~~~~~~~~~~~~"
end
if new_res - del == new_res && del.empty?
stop = true
end
new_res = new_res - del
del = []
res = new_res if new_res.any?
new_res = []
break if stop
end
res.inject(0) { |sum, interval| sum += interval[1] - interval[0] }
end
i1 = [[4,10], [5,7], [5,7], [4, 15], [1, 10], [20, 25]]
i2 = [[4,10]]
i3 = [[4,10], [4,10]]
i4 = [[394, 466], [298, 396], [-228, 132], [-239, 397], [224, 397], [406, 427], [-403, 154], [8, 268], [-194, -59], [384, 423], [-68, 91]]
puts "#{sum_of_intervals(i1)} == 19"
puts "#{sum_of_intervals(i2)} == 6"
puts "#{sum_of_intervals(i3)} == 6"
puts "#{sum_of_intervals(i4)} == 869"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment