6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

需要が無いのか、整数刻み以外の方法が検索で出てこなかったのでまとめておく。

TD;DR

例えば、0.5刻みで0から5までの数値の配列を得る方法。

こうする

def a = []

0.step(5.1, 0.5) { a << it }

println a
output
[0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

ポイント

  • Groovy-jdk Numberクラスのstepメソッドを使う
  • 終端の値を欲しい値よりも少し大きめに取る
  • 終端の値、刻みともに数値型ならばなんでもOK

stepメソッド

  • 第一引数が終端(ただしこの値を含まない半開区間)
  • 第二引数が刻み(数値型全て使える)

こんなこともできる

def b = []

0.step(-5.1, -0.5) { b << it }

println b
output
[0, -0.5, -1.0, -1.5, -2.0, -2.5, -3.0, -3.5, -4.0, -4.5, -5.0]

thanks for

GroovyのRangeメモ http://qiita.com/saba1024/items/75f507b0de843255d2fa

6
2
0

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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?