LoginSignup
0
0

More than 5 years have passed since last update.

ちょっとしたことがGroovy「ある値まで一定間隔のRangeのリストを作りたい」

Last updated at Posted at 2013-06-27

ちょっとしたことがGroovy「ある値まで一定間隔のRangeのリストを作りたい」

getRanges.groovy
def getSteps = {start=1,max,step=1000 ->
  if(max <= start + step) return [[start..max]]
  def rs = (start..max).step(step).inject([]) {a,c -> (c>start) && a << [ ((a!=[])?a.last().to[0]+1:start)..c-1];a}
  (rs.last().to[0] != max) && rs << [rs.last().to[0]+1..max];rs
}
println"""
getSteps(max=10020) = ${getSteps(max=10020)}
"""

println"""
getSteps(100,1000) = ${getSteps(100,1000)}
"""

println"""
getSteps(100,1015,10) = ${getSteps(100,1015,10)}
"""

巨大なテーブルの処理を小さなトランザクションに分けて実行したいときとか。

亜種でこんなの。

def getRangeMaps = {start=1,max,step=1000 ->
  if(max <= start + step) return [[start:start,end:max]]
  def rs = (start..max).step(step).inject([]) {a,c -> (c>start) && a << [ start:((a!=[])?a.last().end+1:start),end:c-1];a}
  (rs.last().end != max) && rs << [start:rs.last().end+1,end:max];rs
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0