View Category
Find the distance between two points
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
groovy
formatted = new DecimalFormat('00000000').format(42)
formatted = 42.toString().padLeft(8, '0')
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
groovy
def result = 7/8
println result.round(new MathContext(2))
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
printf "%.2g", result
new Double(7/8).round(2)
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100
randomInt = random.nextInt(200-100+1)+100
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
groovy
random = new Random(12345)
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat
