Skip to content

Instantly share code, notes, and snippets.

@dimonomid
Created March 28, 2017 21:29
Show Gist options
  • Save dimonomid/334568fd0bb0ea97480cb35219461f64 to your computer and use it in GitHub Desktop.
Save dimonomid/334568fd0bb0ea97480cb35219461f64 to your computer and use it in GitHub Desktop.
Flatten array of integers
// Flatten integers array
//
// This simple utility flattens an arbitrarily nested array of integers.
// Example: [[1,2,[3]],4] -> [1,2,3,4]
//
// Example usage:
// $ ./flatten '[1,2,[4,5,[6],12],14]'
// [1 2 4 5 6 12 14]
//
// If no argument is provided, an example data is used: [[1,2,[3]],4]
package main
import (
"encoding/json"
"fmt"
"os"
)
type nestedArr []interface{}
func main() {
// Determine the input string: either the default one, or the first argument,
// if provided
str := `[[1,2,[3]],4]`
if len(os.Args) >= 2 {
str = os.Args[1]
}
// Unmarshal input string
var nested nestedArr
err := json.Unmarshal([]byte(str), &nested)
if err != nil {
fmt.Println("invalid data: argument must be an array of integers")
os.Exit(1)
}
// Flatten array and print the result
flat, err := flattenIntArr(nested)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println(flat)
}
// flattenIntArr flattens array of integers. Example: [[1,2,[3]],4] -> [1,2,3,4]
func flattenIntArr(nested nestedArr) ([]int, error) {
var ret []int
// Iterate all items in the input array (items should be either integers or
// other arrays)
for _, cur := range nested {
switch val := cur.(type) {
case float64:
// Current item is a number: check if it's an integer, and if so, append it
// to the resulting array
intval := int(val)
if float64(intval) != val {
return nil, fmt.Errorf("invalid data: %f is not an integer", val)
}
ret = append(ret, intval)
case []interface{}:
// Current item is an array: call flattenIntArr() recursively
flat, err := flattenIntArr(val)
if err != nil {
return nil, err
}
ret = append(ret, flat...)
default:
return nil, fmt.Errorf("invalid data: %v is neither an integer nor array", val)
}
}
return ret, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment