Skip to content

Commit

Permalink
day 2 solution. both with division and without
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Aug 24, 2018
1 parent d678ccc commit 6719914
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
35 changes: 35 additions & 0 deletions day2/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package day2

// ProductsExceptI returns an array with the products of all numbers
// except the value at the i-th position.
// O(N) time complexity.
// O(1) space complexity.
func ProductsExceptI(arr []int) []int {
result := make([]int, len(arr))
total := 1
for _, v := range arr {
total *= v
}
for i, v := range arr {
result[i] = total / v
}
return result
}

// ProductsExceptINoDivision returns an array with the products of all numbers
// except the value at the i-th position. Without using division.
// O(N^2) time complexity.
// O(1) space complexity.
func ProductsExceptINoDivision(arr []int) []int {
result := make([]int, len(arr))
for i := range arr {
total := 1
for j, w := range arr {
if i != j {
total *= w
}
}
result[i] = total
}
return result
}
49 changes: 49 additions & 0 deletions day2/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package day2

import (
"reflect"
"testing"
)

var testcases = []struct {
input, expected []int
}{
{[]int{1, 2, 3, 4, 5}, []int{120, 60, 40, 30, 24}},
{[]int{3, 2, 1}, []int{2, 3, 6}},
}

func TestProductsExceptI(t *testing.T) {
t.Run("ProductsExceptI", func(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := ProductsExceptI(tc.input); !reflect.DeepEqual(result, tc.expected) {
t.Error("didn't get what I expected")
}
}
})
t.Run("ProductsExceptINoDivision", func(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := ProductsExceptINoDivision(tc.input); !reflect.DeepEqual(result, tc.expected) {
t.Error("didn't get what I expected")
}
}
})
}

func BenchmarkProductsExceptI(b *testing.B) {
b.Run("ProductsExceptI", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
ProductsExceptI(tc.input)
}
}
})
b.Run("ProductsExceptINoDivision", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
ProductsExceptI(tc.input)
}
}
})
}

0 comments on commit 6719914

Please sign in to comment.