Skip to content

Instantly share code, notes, and snippets.

@calvernaz
Created June 12, 2019 19:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save calvernaz/6a80b2f58ac59ba6975435e02329cbac to your computer and use it in GitHub Desktop.
Golang Flatten
package flatten
// FlattenCopy flattens array of integers
// using the built-in copy function
func FlattenCopy(arr [][]int) []int {
r := make([]int, len(arr))
i := 0
for _, a := range arr {
if len(a) + i <= cap(r) {
copy(r[i:], a)
i += len(a)
} else {
rr := make([]int, i + len(a))
copy(rr, r)
copy(rr[i:], a)
r = rr
i += len(a)
}
}
return r
}
// FlattenAppend flattens array of integers
// using the built-in append function
func FlattenAppend(arr [][]int) []int {
r := make([]int, 0, len(arr))
for _, a := range arr {
r = append(r, a...)
}
return r
}
package flatten
import (
"fmt"
"reflect"
"testing"
)
func TestFlattenAppend(t *testing.T) {
tt := []struct {
in [][]int
out []int
}{
{[][]int{}, []int{}},
{[][]int{{1}, {2}, {3}}, []int{1, 2, 3}},
{[][]int{{1}, {3, 5}, {7}, {8, 9}, {10, 11, 12}}, []int{1, 3, 5, 7, 8, 9, 10, 11, 12}},
{[][]int{{1}, {3, 5}, {7, 8}}, []int{1, 3, 5, 7, 8}},
}
for _, tin := range tt {
r := FlattenAppend(tin.in)
if !reflect.DeepEqual(r, tin.out) {
t.Errorf("expected %+q, got %+q", tin.out, r)
}
}
}
func TestFlattenCopy(t *testing.T) {
tt := []struct {
in [][]int
out []int
}{
{[][]int{}, []int{}},
{[][]int{{1}, {2}, {3}}, []int{1, 2, 3}},
{[][]int{{1}, {3, 5}, {7}, {8, 9}, {10, 11, 12}}, []int{1, 3, 5, 7, 8, 9, 10, 11, 12}},
{[][]int{{1}, {3, 5}, {7, 8}}, []int{1, 3, 5, 7, 8}},
}
for _, tin := range tt {
r := FlattenCopy(tin.in)
if !reflect.DeepEqual(r, tin.out) {
t.Errorf("expected %v, got %v", tin.out, r)
}
}
}
func ExampleFlattenAppend() {
arr := [][]int { {1}, {3, 5}, {7}, {8, 9}, {10, 11, 12}}
fmt.Println(FlattenAppend(arr))
// Output: [1 3 5 7 8 9 10 11 12]
}
func ExampleFlattenCopy() {
arr := [][]int{{1}, {2}, {3}, {5, 6, 7, 8}, {9, 10}}
fmt.Println(FlattenCopy(arr))
// Output: [1 2 3 5 6 7 8 9 10]
}
@calvernaz
Copy link
Author

Two versions of a possible implementation for flatten slices.

  • The first version uses the built-in copy to add the values to the final slice.
  • The second one uses the built-in append to add the values to the final slice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment