Created
September 29, 2015 05:27
-
-
Save wrouesnel/cb5a66e2e72e5a00ebda to your computer and use it in GitHub Desktop.
Turn a sorted list of ints into number ranges in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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