Skip to content

Commit

Permalink
Merge 907df5a into 9051797
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 1, 2019
2 parents 9051797 + 907df5a commit 9373950
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,4 +372,5 @@ problems from
* [Day 374](https://github.com/vaskoz/dailycodingproblem-go/issues/754)
* [Day 375](https://github.com/vaskoz/dailycodingproblem-go/issues/756)
* [Day 376](https://github.com/vaskoz/dailycodingproblem-go/issues/758)
* [Day 377](https://github.com/vaskoz/dailycodingproblem-go/issues/760)

24 changes: 24 additions & 0 deletions day377/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package day377

import "sort"

// BruteKMedians calculates the median of every k-sized
// window using brute force.
// It runs in O(N*K log K).
func BruteKMedians(nums []float64, k int) []float64 {
ans := make([]float64, 0, len(nums)-k)
window := make([]float64, k)

for i := 0; i <= len(nums)-k; i++ {
copy(window, nums[i:k+i])
sort.Float64s(window)

if k%2 == 0 {
ans = append(ans, (window[k/2]+window[(k/2)-1])/2)
} else {
ans = append(ans, window[k/2])
}
}

return ans
}
42 changes: 42 additions & 0 deletions day377/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day377

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
input []float64
k int
expected []float64
}{
{
[]float64{-1, 5, 13, 8, 2, 3, 3, 1},
3,
[]float64{5, 8, 8, 3, 3, 3},
},
{
[]float64{-1, 5, 13, 8, 2, 3, 3, 1},
4,
[]float64{6.5, 6.5, 5.5, 3, 2.5},
},
}

func TestBruteKMedians(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := BruteKMedians(tc.input, tc.k); !reflect.DeepEqual(result, tc.expected) {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

func BenchmarkBruteKMedians(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BruteKMedians(tc.input, tc.k)
}
}
}

0 comments on commit 9373950

Please sign in to comment.