Scala Seq.indexOf and lastIndexOf
Find both ends of a repeated stop in a travel itinerary.
A simple example
Seq.indexOf and lastIndexOf
- Start with A, B, A
- Do this Locate the first and last A
- Result First and third positions
Syntax
stops.lastIndexOf(stop)
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 LessonFind both visits to the market
A circular bus route visits the market on both the outward and return journeys. A timetable editor needs the first and last positions of the market to label the two visits correctly.
object Lesson {
def main(args: Array[String]): Unit = {
val stops = Vector("Depot", "Market", "Park", "Market")
println(s"${stops.indexOf("Market")} and ${stops.lastIndexOf("Market")}")
}
}
1 and 3
The zero-based positions show Market on the outward trip at one and on the return trip at three.
Locate a transfer stop
A bus calls at Hill twice on its circular route. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.
Find a returned item
A desk checks the earliest entry marked Pen. Find the first occurrence and count the entries before it. The duplicate later in the list does not change that count.
What to watch for
Both searches return -1 when the route does not contain the requested stop.