Advertisement
Guest User

Untitled

a guest
May 26th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. package flatten_array
  2.  
  3. import "errors"
  4.  
  5. // Write a function that will flatten an array of arbitrarily nested arrays of
  6. // integers into a flat array of integers. e.g. [[1,2,[3]],4] → [1,2,3,4]. If
  7. // the language you're using has a function to flatten arrays, you should
  8. // pretend it doesn't exist.
  9.  
  10. var ErrInvalidType = errors.New("Invalid type, should be int")
  11.  
  12. func FlattenArray(values []interface{}) ([]int, error) {
  13. result := make([]int, 0)
  14.  
  15. for _, value := range values {
  16. switch value.(type) {
  17. case int:
  18. result = append(result, value.(int))
  19. case []interface{}:
  20. recursiveResult, err := FlattenArray(value.([]interface{}))
  21. if err != nil {
  22. return nil, err
  23. }
  24.  
  25. result = append(result, recursiveResult...)
  26. case []int:
  27. result = append(result, value.([]int)...)
  28. default:
  29. return nil, ErrInvalidType
  30. }
  31. }
  32.  
  33. return result, nil
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement