Michael Borgwardt
Michael Borgwardt

Reputation: 346327

Groovy range with a 0.5 step size

What's the most elgant way in Groovy to specify a range of integers and the 0.5 steps between them? e.g.: 1, 1.5, 2, 2.5, 3, 3.5, 4

Edit: To clarify: As an end result I need a range object for use in a Grails constraint. Though I suppose a list would be OK too.

Upvotes: 12

Views: 10765

Answers (8)

user1925718
user1925718

Reputation: 9

(1..7).collect{0.5*it} is the best I can think of

Upvotes: 0

macao
macao

Reputation: 19

my answer is the following:

(1..4).step(0.5)

Upvotes: 0

Reverend Gonzo
Reverend Gonzo

Reputation: 40831

A little late, but this works too

A one-liner for your above set:

(2..8)*.div(2)

Upvotes: 5

Matt Christianson
Matt Christianson

Reputation: 149

def r = []
(0..12).each() {
  r << it
  r << it + 0.5
}

Upvotes: 0

billjamesdev
billjamesdev

Reputation: 14640

Soo, to build on above. To test if a value val is in the range 1..n but with half values:

def range = 2..(n*2).collect { return it/2.0 }
return range.contains( val )

Something like that would work, but isn't as pretty as I'd like, but it lets you build the range once and use it multiple times, if you need that.

Upvotes: 1

Allen
Allen

Reputation: 2258

Cheat.

Map your desired range into another that is more easily handled by Groovy. You want something like:

 y in [x, x+0.5, x+1, x+1.5, ..., x+n] // tricky if you want a range object

which is true if and only if:

 2*y in [2x,2x+1,2x+2,2x+3,...,2x+2n] // over whole integers only

which is the same as the range object:

(2*x)..(2*x+2*n).contains(2*y)   //simple!

or:

switch (2*y) {
   case (2*x)..(2*x+2*n): doSomething(); break;
   ...}

Upvotes: 0

chanwit
chanwit

Reputation: 3214

FYI, as of Groovy 1.6.0, it seems not to support natively. There exists only ObjectRange.step(int) at the moment.

http://groovy.codehaus.org/api/groovy/lang/ObjectRange.html#step%28int%29

Upvotes: 0

kgrad
kgrad

Reputation: 4792

Best way I can see is using the step command.

i.e.


    1.step(4, 0.5){ print "$it "}

would print out: "1 1.5 2.0 2.5 3.0 3.5"

Upvotes: 30

Related Questions