Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Created December 27, 2012 10:20
Show Gist options
  • Select an option

  • Save yuroyoro/4387132 to your computer and use it in GitHub Desktop.

Select an option

Save yuroyoro/4387132 to your computer and use it in GitHub Desktop.
RubyでScalaのIterator#slidingを実装してみた
class Array
def sliding(n)
self.inject([]){|xs,e| xs.last.tap{|r| r.nil? ? xs << [e] : if r.length < n then r << e else xs << r.dup.tap{|_| _.shift ; _ << e } end }; xs}
end
end
[42] pry(main)> arr = (1..10).to_a
[43] pry(main)> arr.sliding(3)
[
[0] [
[0] 1,
[1] 2,
[2] 3
],
[1] [
[0] 2,
[1] 3,
[2] 4
],
[2] [
[0] 3,
[1] 4,
[2] 5
],
[3] [
[0] 4,
[1] 5,
[2] 6
],
[4] [
[0] 5,
[1] 6,
[2] 7
],
[5] [
[0] 6,
[1] 7,
[2] 8
],
[6] [
[0] 7,
[1] 8,
[2] 9
],
[7] [
[0] 8,
[1] 9,
[2] 10
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment