Skip to content

Instantly share code, notes, and snippets.

@wrouesnel
Created September 29, 2015 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrouesnel/cb5a66e2e72e5a00ebda to your computer and use it in GitHub Desktop.
Save wrouesnel/cb5a66e2e72e5a00ebda to your computer and use it in GitHub Desktop.
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