Skip to content

Instantly share code, notes, and snippets.

@derekkenney
Last active July 17, 2019 05:37
Show Gist options
  • Save derekkenney/58360a31ae123a3eac7bf72ba8dcbff4 to your computer and use it in GitHub Desktop.
Save derekkenney/58360a31ae123a3eac7bf72ba8dcbff4 to your computer and use it in GitHub Desktop.

Flatten a mutlidimensional array of nested int arrays into a one dimensional array

An example application that flattens nested int arrays into a single int array

Components

Testing

The application uses Go's standard package 'testing'. The test fixtures are setup before each test run

  • cd ./arrays
  • go test -v

Build and run package

  • $ cd ~/github.com/derekkenney/theorem
  • $ go build main.go
  • $ ./main
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
arrays "github.com/derekkenney/theorem/arrays"
"log"
"os"
)
func main() {
fmt.Println("Flatten a multidimensional array")
fmt.Println("starting ...")
//read from stdin
r := bufio.NewReader(os.Stdin)
fmt.Println("Enter a 2 dimensional array to be flatened ... [[1,2], [3,4], [5,6]]")
b, _ := r.ReadSlice('\n')
// b is a byte array of input. We now Marshal it into an []int
var ints [][]int
err := json.Unmarshal(b, &ints)
if err != nil {
log.Fatalf("Error unamarshalling input value into [][]int %v", err)
}
arr := arrays.IntArray{}
results, err := arr.FlattenIntArrays(context.Background(), ints)
if err != nil {
log.Fatalf("Error flattening the array %v\n", err)
}
fmt.Printf("Results of the flattened array are %v\n", results)
}
package arrays
import (
"context"
"errors"
"sort"
)
type TheoremArray interface {
FlattenIntArray(ctx context.Context, arr []int) ([]int, error)
}
type IntArray struct{}
// FlattenIntArrays takes a 2 dimensional array of []interface as an argument, and returns a one dimensional array of ints. The input can have ints, and nested arrays of ints.
//
// arr := FlattenIntArrays(ctx,arr)
func (n *IntArray) FlattenIntArrays(ctx context.Context, arr [][]int) ([]int, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if arr == nil {
err := errors.New("Input argument arr is nil")
return []int{}, err
cancel()
}
//create a map for our lookup of []int types
m := make(map[int][]int)
for i := 0; i < len(arr); i++ {
m[i] = arr[i]
}
// Iterate over the map
var results []int
for k, _ := range arr {
a := m[k]
for _, v := range a {
results = append(results, v)
}
}
sort.Ints(results)
return results, nil
}
package arrays_test
import (
"context"
arr "github.com/derekkenney/theorem/arrays"
"reflect"
"testing"
)
const (
checkMark = "\u2713"
ballotX = "\u2717"
)
var (
input = [][]int{{1}, {3, 2}, {4, 5}, {6, 7}}
output = []int{1, 2, 3, 4, 5, 6, 7}
)
//TestFlattenIntArray tests that an input of nested int arrays, can be returned as a flat arry of ints
func TestFlattenIntArrays(t *testing.T) {
a := arr.IntArray{}
t.Log("Given the need to flatten an array of nested int arrays")
{
t.Logf("When calling FlattenIntArrays(%v)\n", input)
{
//on error return empty arr, log error
results, err := a.FlattenIntArrays(context.Background(), input)
if err != nil {
t.Errorf(err.Error())
}
if results != nil {
t.Logf("\tWe expect a single array of ints back %v", checkMark)
} else {
t.Errorf("\tWe expect a single array of ints back %v", ballotX)
}
if reflect.DeepEqual(results, output) {
t.Logf("\t\tand the results to be %v, %v", results, checkMark)
}
if !reflect.DeepEqual(results, output) {
t.Errorf("\t\tand the results to be %v, not %v. %v", output, results, ballotX)
}
}
}
}
func TestHandleNullArgumentPredictably(t *testing.T) {
a := arr.IntArray{}
input = nil
output = []int{}
t.Log("When calling FlattenInArrays()\n")
{
t.Logf("\tWith an array input that's nil")
{
//on error return empty arr, log error
results, err := a.FlattenIntArrays(context.Background(), input)
if err != nil && err.Error() == "Input argument arr is nil" {
t.Logf("\t\tWe expect an error type, %v", checkMark)
} else {
t.Errorf("\t\ttWe expect an error type, %v", ballotX)
}
if reflect.DeepEqual(results, output) {
t.Logf("\t\t\tand an empty []int %v", checkMark)
} else {
t.Errorf("\t\t\tand an empty []int %v", ballotX)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment