Skip to content

Instantly share code, notes, and snippets.

@ocpodariu
Last active September 20, 2017 10:40
Show Gist options
  • Save ocpodariu/5d51812719f7478251b7854cfce766bd to your computer and use it in GitHub Desktop.
Save ocpodariu/5d51812719f7478251b7854cfce766bd to your computer and use it in GitHub Desktop.
Flatten a list of lists and integers
// Given a list that contains integers and lists of integers,
// build a list containing all the integers.
//
// Example:
// given L = [1 2 [7 [8 9]] 3 [4 5] 6]
// obtain M = [1 2 7 8 9 3 4 5 6]
package main
import (
"fmt"
"reflect"
)
func flatten(list interface{}) []int64 {
if reflect.TypeOf(list).Kind() != reflect.Slice {
fmt.Println("err: expected slice")
return nil
}
var m []int64
l := reflect.ValueOf(list)
for i := 0; i < l.Len(); i++ {
val := l.Index(i).Interface()
t := reflect.TypeOf(val).Kind()
switch t {
case reflect.Slice:
temp := flatten(val)
m = append(m, temp...)
case reflect.Int:
fallthrough
case reflect.Int64:
m = append(m, reflect.ValueOf(val).Int())
default:
fmt.Println("unknown:", t)
}
}
return m
}
func main() {
list := []interface{}{1, 2, []interface{}{7, []int64{8, 9}}, 3, []int64{4, 5}, 6}
fmt.Println(list)
fmt.Println(flatten(list))
}
@ocpodariu
Copy link
Author

ocpodariu commented Jul 28, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment