Scala java.lang.Math.floorMod
Floor modulus gives a wrapped index for a positive cycle length.
A simple example
java.lang.Math.floorMod
- Start with −7 and 3
- Do this Use the floor quotient −3
- Result 2
object Lesson extends App {
println(java.lang.Math.floorMod(-7, 3))
}
2
Syntax
java.lang.Math.floorMod(position, shelves)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonWrap a shelf position back to the last shelf
A picker cycles through a fixed set of shelves and can step backwards from the first position. Map that earlier position back into the valid shelf range before indexing the list.
object Lesson {
def main(args: Array[String]): Unit = {
val position = -1
val shelves = 7
println(java.lang.Math.floorMod(position, shelves))
}
}
6
Moving back from shelf zero produces shelf six in a seven-shelf cycle.
Locate a complete carousel turn
A carousel holds six numbered trays. After twelve forward steps the indexing routine checks the remainder at a complete turn.
An exact number of turns gives zero with either rounding convention.
Step back on a weekly rota
A seven-day rota stores Monday at index zero. An editor moves back two days and needs an index that still lies inside the rota.
With a positive width, floor modulus wraps the negative step to index five.
What to watch for
Supply a positive cycle length for an index in the range zero through length minus one.