View Category

Find the distance between two points

scala
val distance$ = distance((34, 78), (67, -45))
println(distance$)
val distance$ = distance(new Point(34, 78), new Point(67, -45))
println(distance$)
def distance (p1: (Int, Int), p2: (Int, Int)) = {
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))

def euclideanDistance(point1: List[Double], point2: List[Double]): Double = {
sqrt(point1.zip(point2).foldLeft(0.0){case(sum,(v1,v2)) => sum + pow(v1-v2, 2)})
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))

val num = 42
println(f"$num%08d")
println(f"${42}%08d")

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
scala
val formatted = String.format("%-6d", int2Integer(1024))
printf("%-6d\n", 1024)
println("%-6d".format(1024))

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
scala
val formatted = String.format("%10d", int2Integer(73))
printf("%10d\n", 73)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
scala
val rnd = new GenRandInt(100, 200)
val randomInt = rnd.next
val rnd = new scala.util.Random
val range = 100 to 200
println(range(rnd.nextInt(range length)))
val start = 100
val end = 200
val rnd = new scala.util.Random

println( start + rnd.nextInt( (end - start) + 1 ) )

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.
scala
val rnd = new scala.util.Random(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()

rnd.setSeed(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()