Created
June 12, 2019 19:46
Star
You must be signed in to star a gist
Golang Flatten
This file contains 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 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 | |
} |
This file contains 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 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] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two versions of a possible implementation for flatten slices.
copy
to add the values to the final slice.append
to add the values to the final slice.