Skip to content

Commit

Permalink
Add tapeequilibrium solution, unit test and benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
alesr committed Mar 12, 2017
1 parent 75fe586 commit 33718af
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
26 changes: 26 additions & 0 deletions tapeequilibrium.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package goexercises

import "math"

// TapeEquilibrium - https://codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/
// Minimize the value `|(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|`
func TapeEquilibrium(slice []int) int {
total := sumSliceInt(slice)
min, leftSide := math.MaxFloat64, 0
for _, v := range slice {
rightSide := total - v - leftSide
leftSide += v
difference := math.Abs(float64(rightSide - leftSide))
if difference < min {
min = difference
}
}
return int(min)
}

func sumSliceInt(slice []int) (sum int) {
for _, v := range slice {
sum += v
}
return
}
56 changes: 56 additions & 0 deletions tapeequilibrium_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package goexercises

import "testing"

func TestTapeEquilibrium(t *testing.T) {
testCases := []struct {
slice []int
expected int
}{
{[]int{3, 1, 2, 4, 3}, 1},
{[]int{3, 1, 2, 4, 3, 1, 2, 3, 10}, 1},
{[]int{2, 3, 10}, 5},
{[]int{0}, 0},
{[]int{0, 1}, 1},
}
for _, test := range testCases {
observed := TapeEquilibrium(test.slice)
if observed != test.expected {
t.Errorf("for slice '%v', expected '%d', observed '%d'\n",
test.slice, test.expected, observed)
}
}
}

func BenchmarkTapeEquilibrium(b *testing.B) {
for i := 0; i < b.N; i++ {
TapeEquilibrium([]int{0, 1, 2, 3, 4, 5})
}
}

func TestSumSliceInt(t *testing.T) {
testCases := []struct {
slice []int
expected int
}{
{[]int{1, 1, 1}, 3},
{[]int{0}, 0},
{[]int{1}, 1},
{[]int{1, 3}, 4},
{[]int{1, -1}, 0},
{[]int{-1, -1}, -2},
}
for _, test := range testCases {
observed := sumSliceInt(test.slice)
if observed != test.expected {
t.Errorf("for slice '%v', expected '%d', observed '%d'\n",
test.slice, test.expected, observed)
}
}
}

func BenchmarkSumSliceInt(b *testing.B) {
for i := 0; i < b.N; i++ {
sumSliceInt([]int{0, 1, 2, 3, 4, 5})
}
}

0 comments on commit 33718af

Please sign in to comment.