Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package flatten_array
- import "errors"
- // Write a function that will flatten an array of arbitrarily nested arrays of
- // integers into a flat array of integers. e.g. [[1,2,[3]],4] → [1,2,3,4]. If
- // the language you're using has a function to flatten arrays, you should
- // pretend it doesn't exist.
- var ErrInvalidType = errors.New("Invalid type, should be int")
- func FlattenArray(values []interface{}) ([]int, error) {
- result := make([]int, 0)
- for _, value := range values {
- switch value.(type) {
- case int:
- result = append(result, value.(int))
- case []interface{}:
- recursiveResult, err := FlattenArray(value.([]interface{}))
- if err != nil {
- return nil, err
- }
- result = append(result, recursiveResult...)
- case []int:
- result = append(result, value.([]int)...)
- default:
- return nil, ErrInvalidType
- }
- }
- return result, nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement