Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turn a sorted list of ints into number ranges in Go
package main
import (
"fmt"
)
func main() {
var statusCodes []int = []int{100,101,102,103,104,105,106,107,110,111,112,115,119,120,121,124}
var output []string
idx := 0
for {
start := statusCodes[idx]
prev := start
for {
idx++
if idx >= len(statusCodes) {
break
}
if statusCodes[idx] - prev != 1 {
// Check if it's a single number
if statusCodes[idx-1] == start {
output = append(output, fmt.Sprintf("%d", start))
} else {
output = append(output, fmt.Sprintf("%d-%d", start, statusCodes[idx-1]))
}
break
}
prev = statusCodes[idx]
}
if idx >= len(statusCodes) {
break
}
}
fmt.Println(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment