【发布时间】:2021-12-23 21:48:05
【问题描述】:
我想将连续整数组合到一个排序数组中,并使用jq 将它们替换为范围。
示例 1
输入:
[1,2,3,4,6,98,99,101]
所需输出:"1-4,6,98-99,101"
示例 2
输入:
[1,3,5]
所需输出:"1,3,5"
示例 3
输入:
[1,2,3,4,5]
所需输出:"1-5"
我找到了一个使用foreach 的解决方案,但它对我来说似乎不是很优雅和紧凑。
这个任务有更简单的解决方案吗?
[foreach (.[], 99999) as $current
({};
if length == 0 then
{first: $current}
elif (has("last") | not) and .first + 1 != $current then
{first: $current, extract: "\(.first)"}
elif has("last") and .last + 1 != $current then
{first: $current, extract: "\(.first)-\(.last)"}
else
{first, last: $current}
end;
.extract // empty
)]
| join(",")
【问题讨论】:
标签: jq