Last active
April 28, 2019 12:35
-
-
Save ilovelili/fb28fe136b4c9cfb2851252f9018b7f1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"errors" | |
"fmt" | |
) | |
func main() { | |
fmt.Println(`[1,2,3] -> [1,2,3]`) | |
input := []interface{}{1, 2, 3} | |
result, err := Flatten(input) | |
fmt.Println(result, err) | |
fmt.Println(`[1,2,[3],4] -> [1,2,3,4]`) | |
input = []interface{}{1, 2, []int{3}, 4} | |
result, err = Flatten(input) | |
fmt.Println(result, err) | |
fmt.Println(`[[1,2,[3]],4] -> [1,2,3,4]`) | |
input = []interface{}{[]interface{}{1, 2, []int{3}}, 4} | |
result, err = Flatten(input) | |
fmt.Println(result, err) | |
fmt.Println(`[[1,2,[3]],[[1,2,3],4]] -> [1,2,3,1,2,3,4]`) | |
input = []interface{}{1, 2, []int{3}, []interface{}{[]int{1, 2, 3}, 4}} | |
result, err = Flatten(input) | |
fmt.Println(result, err) | |
} | |
// Flatten flattens an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
func Flatten(input interface{}) (result []int, err error) { | |
result = []int{} | |
// check by input type | |
switch t := input.(type) { | |
// if int array, append | |
case []int: | |
result = append(result, t...) | |
return | |
// if int, append | |
case int: | |
result = append(result, t) | |
return | |
// if []interface{}, do Flatten recursively | |
case []interface{}: | |
for _, i := range t { | |
_result, _err := Flatten(i) | |
if _err != nil { | |
err = _err | |
return | |
} | |
result = append(result, _result...) | |
} | |
// else throw error since type is not supported | |
default: | |
err = errors.New("wrong array type") | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment