Created
July 10, 2018 11:49
-
-
Save Cowa/7b6a6355ff6ed0e7c601b1a7ab1ac6c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PhenixDisplays.EnumUtils do | |
@doc """ | |
Make a sliding window of a list | |
## Example | |
iex> alias PhenixDisplays.EnumUtils | |
iex> EnumUtils.sliding([1,2,3], 2) | |
[[1, 2], [2, 3]] | |
iex> EnumUtils.sliding([1,2,3,4], 2) | |
[[1, 2], [2, 3], [3, 4]] | |
iex> EnumUtils.sliding([1,2,3,4], 3) | |
[[1, 2, 3], [2, 3, 4]] | |
""" | |
def sliding(list, n) do | |
do_sliding(list, n, []) | |
end | |
defp do_sliding([], _, acc), do: acc | |
defp do_sliding([_ | tl], n, acc) when length(tl) < n - 1, do: acc | |
defp do_sliding([hd | tl], n, acc), do: do_sliding(tl, n, acc ++ [[hd] ++ Enum.take(tl, n - 1)]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment