我在问自己,你有多容易把一个数列,比如= 1,2,3,6,7,8,9,12,13,15转换成一个字符串,“最小化”数字,比如= "1-3,6-9,12-13,15“。
我可能想得太多了,因为现在我不知道如何才能轻易做到这一点。
我的尝试:
$newArray = ""
$array = 1,2,3,6,7,8,9,12,13,15
$before
Foreach($num in $array){
If(($num-1) -eq $before){
# Here Im probably overthinking it because I don't know how I should continue
}else{
$before = $num
$newArray += $num
}
}
发布于 2020-01-29 09:37:52
这应该是可行的,代码是自我解释的,希望:
$array = @( 1,2,3,6,7,8,9,12,13,15 )
$result = "$($array[0])"
$last = $array[0]
for( $i = 1; $i -lt $array.Length; $i++ ) {
$current = $array[$i]
if( $current -eq $last + 1 ) {
if( !$result.EndsWith('-') ) {
$result += '-'
}
}
elseif( $result.EndsWith('-') ) {
$result += "$last,$current"
}
else {
$result += ",$current"
}
$last = $current
}
if( $result.EndsWith('-') ) {
$result += "$last"
}
$result = $result.Trim(',')
$result = '"' + $result.Replace(',', '","') +'"'
$result
发布于 2020-01-29 09:58:10
我有一个稍微不同的方法,但有点太慢,无法回答。下面是:
$newArray = ""
$array = 1,2,3,6,7,8,9,12,13,15
$i = 0
while($i -lt $array.Length)
{
$first = $array[$i]
$last = $array[$i]
# while the next number is the successor increment last
while ($array[$i]+1 -eq $array[$i+1] -and ($i -lt $array.Length))
{
$last = $array[++$i]
}
# if only one in the interval, output that
if ($first -eq $last)
{
$newArray += $first
}
else
{
# else output first and last
$newArray += "$first-$last"
}
# don't add the final comma
if ($i -ne $array.Length-1)
{
$newArray += ","
}
$i++
}
$newArray
发布于 2020-01-29 12:24:08
这是另一种解决这个问题的方法。首先,您可以使用index - element
作为键,根据索引将元素分组到哈希表中。其次,您需要按键对字典进行排序,然后在数组中收集由"-"
拆分的范围字符串。最后,您可以通过","
加入这个数组并输出结果。
$array = 1, 2, 3, 6, 7, 8, 9, 12, 13, 15
$ranges = @{ }
for ($i = 0; $i -lt $array.Length; $i++) {
$key = $i - $array[$i]
if (-not ($ranges.ContainsKey($key))) {
$ranges[$key] = @()
}
$ranges[$key] += $array[$i]
}
$sequences = @()
$ranges.GetEnumerator() | Sort-Object -Property Key -Descending | ForEach-Object {
$sequence = $_.Value
$start = $sequence[0]
if ($sequence.Length -gt 1) {
$end = $sequence[-1]
$sequences += "$start-$end"
}
else {
$sequences += $start
}
}
Write-Output ($sequences -join ",")
输出:
1-3,6-9,12-13,15
https://stackoverflow.com/questions/59963494
复制相似问题