aboutsummaryrefslogtreecommitdiff
path: root/challenge-092/stuart-little/lua/ch-2.lua
blob: 4f100e87efd9552e7dfaaf9fced3cdd2f3ad3b66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env lua

--[[
run <script> <initial ordered intervals followed by extra interval>

each interval should be entered as <left> <space> <right>, with spaces between the individual intervals

e.g. <script> 1 4 8 10 2 6
--]]

function lt(t1,t2)
   return t1 and t2 and t1[2] < t2[1]
end

function overlap(t1,t2)
   return t1 and t2 and t1[2] >= t2[1] and t2[2] >= t1[1]
end

function mergeOver(t1,t2)
   return {math.min(t1[1],t2[1]),math.max(t1[2],t2[2])}
end

local ints={}
while #arg>0 do
   table.insert(ints,{tonumber(table.remove(arg,1)),tonumber(table.remove(arg,1))})
end
extra=table.remove(ints)

local i=1
while lt(ints[i],extra) do i=i+1 end
while overlap(ints[i],extra) do
   local t=table.remove(ints,i)
   extra=mergeOver(extra,t)
end
table.insert(ints,i,extra)
for _,t in ipairs(ints) do print(table.unpack(t)) end