Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "errors"
  6. )
  7.  
  8. func main(){
  9. arrayExample := []interface{}{1, []interface{}{2, 3}, []interface{}{[]interface{}{4}}, []interface{}{5, []interface{}{6}}}
  10. result, _ := flattenArray(arrayExample)
  11.  
  12. fmt.Println("Input array");
  13. fmt.Println(arrayExample);
  14.  
  15. fmt.Println("Result array");
  16. fmt.Println(result);
  17.  
  18. }
  19.  
  20. func flattenArray(array []interface{}) (flattened []int , err error){
  21. currentFlattened := []int{}
  22. return flattenArrayRecursive(array, currentFlattened)
  23. }
  24.  
  25. func flattenArrayRecursive(array interface{}, currentFlattened []int) (flattened []int , err error){
  26. switch copy := array.(type) {
  27. case int :
  28. currentFlattened = append(currentFlattened, copy)
  29.  
  30. case []int :
  31. currentFlattened = append(currentFlattened, copy...)
  32. case []interface{}:
  33. for index := range copy {
  34. currentFlattened, err = flattenArrayRecursive(copy[index], currentFlattened)
  35. if err != nil {
  36. return nil, err
  37. }
  38. }
  39. default:
  40. return nil, errors.New("Unable to flatten array")
  41. }
  42. return currentFlattened, nil
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement