Range consolidation: Difference between revisions

m (Third time lucky?)
Line 208:
| | | | 3 10| |
+-------+-------+---+-----+-----+</lang>
 
 
=={{header|Julia}}==
In Julia, a Range is a type of iterator, generally one over a specified interval.
The task as specified is orthogonal to the iteration purpose of a Julia Range,
since the task is about merging sets of numbers, not ranges. Therefore, a translation
of the Python code is done, rather than using a native Julia Range.
{{trans|Python}}
<lang julia>normalize(s) = sort([sort(bounds) for bounds in s])
 
function consolidate(ranges)
norm = normalize(ranges)
for (i, r1) in enumerate(norm)
if !isempty(r1)
for r2 in norm[i+1:end]
if !isempty(r2) && r1[end] >= r2[1] # intersect?
r1 .= [r1[1], max(r1[end], r2[end])]
empty!(r2)
end
end
end
end
[r for r in norm if !isempty(r)]
end
 
function testranges()
for s in [[[1.1, 2.2]], [[6.1, 7.2], [7.2, 8.3]], [[4, 3], [2, 1]],
[[4, 3], [2, 1], [-1, -2], [3.9, 10]],
[[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]]]
println("$s => $(consolidate(s))")
end
end
 
testranges()
</lang>
<pre>
Array{Float64,1}[[1.1, 2.2]] => Array{Float64,1}[[1.1, 2.2]]
Array{Float64,1}[[6.1, 7.2], [7.2, 8.3]] => Array{Float64,1}[[6.1, 8.3]]
Array{Float64,1}[[4.0, 3.0], [2.0, 1.0]] => Array{Float64,1}[[1.0, 2.0], [3.0, 4.0]]
Array{Float64,1}[[4.0, 3.0], [2.0, 1.0], [-1.0, -2.0], [3.9, 10.0]] => Array{Float64,1}[[-2.0, -1.0], [1.0, 2.0], [3.0, 10.0]]
Array{Float64,1}[[1.0, 3.0], [-6.0, -1.0], [-4.0, -5.0], [8.0, 2.0], [-6.0, -6.0]] => Array{Float64,1}[[-6.0, -1.0], [1.0, 8.0]]
</pre>
 
=={{header|Perl 6}}==
4,105

edits