Add a sliding window function as shared here: https://gophers.slack.com/archives/C02A8LZKT/p1588980407253800

Tim Heckman 2020-05-08 16:37:16 -07:00
parent 127eb13fb8
commit e5998399c8

@ -240,4 +240,23 @@ func moveToFront(needle string, haystack []string) []string {
haystack := []string{"a", "b", "c", "d", "e"} // [a b c d e] haystack := []string{"a", "b", "c", "d", "e"} // [a b c d e]
haystack = moveToFront("c", haystack) // [c a b d e] haystack = moveToFront("c", haystack) // [c a b d e]
haystack = moveToFront("f", haystack) // [f c a b d e] haystack = moveToFront("f", haystack) // [f c a b d e]
```
### Sliding Window
```go
func slidingWindow(size int, input []int) [][]int {
// returns the input slice as the first element
if len(input) <= size {
return [][]int{input}
}
// allocate slice at the precise size we need
r := make([][]int, 0, len(input)-size+1)
for i, j := 0, size; j <= len(input); i, j = i+1, j+1 {
r = append(r, input[i:j])
}
return r
}
``` ```