RosettaCodeData/Task/Range-extraction/Julia/range-extraction.jl

18 lines
597 B
Julia
Raw Permalink Normal View History

2026-04-30 12:34:36 -04:00
function sprintfrange(a::Vector{T}) where T<:Integer
isempty(a) && return ""
2023-07-01 11:58:00 -04:00
len = length(a)
dropme = falses(len)
dropme[2:end-1] = Bool[a[i-1]==a[i]-1 && a[i+1]==a[i]+1 for i in 2:(len-1)]
2026-04-30 12:34:36 -04:00
s = [dropme[i] ? "X" : string(a[i]) for i in 1:len]
2023-07-01 11:58:00 -04:00
s = join(s, ",")
2026-04-30 12:34:36 -04:00
replace(s, r",[,X]+," => "-")
2023-07-01 11:58:00 -04:00
end
testa = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39]
println("Testing range-style formatting.")
println(" ", testa, "\n =>\n ", sprintfrange(testa))