Last active
September 20, 2017 10:40
-
-
Save ocpodariu/5d51812719f7478251b7854cfce766bd to your computer and use it in GitHub Desktop.
Flatten a list of lists and integers
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
// 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.com/p/NJDleDwg82