import scala.util.matching.Regex
/**
* Program to extract and sort integer values from a mixed string of text and numbers.
* Demonstrates Scala's expressive regular expressions and functional Collections API.
*/
object NumberExtractorSort {
/**
* Extracts all contiguous digit sequences from a string and converts them to integers.
*
* @param input The raw string containing text and embedded numbers.
* @return A Vector containing the extracted integers in order of appearance.
*/
def extractNumbers(input: String): Vector[Int] = {
// The ".r" extension method on a String compactly compiles it into a Regex object.
// "\\d+" matches one or more contiguous ASCII digits.
val digitPattern: Regex = "\\d+".r
// 1. `findAllIn(input)` returns an Iterator[String] of all non-overlapping matches.
// 2. `map(_.toInt)` safely transforms each numeric string into an integer.
// 3. `toVector` materializes the iterator into an immutable, efficient indexed sequence.
digitPattern.findAllIn(input).map(_.toInt).toVector
}
/**
* Sorts a sequence of numbers in ascending order.
*
* @param numbers The collection of integers to be sorted.
* @return A new sequence sorted in ascending order.
*/
def sortNumbers(numbers: Vector[Int]): Vector[Int] = {
// The `.sorted` method leverages an implicit Ordering[Int] provided by the standard library.
// Under the hood, Scala collections use a highly optimized Timsort algorithm (O(N log N)).
numbers.sorted
}
def main(args: Array[String]): Unit = {
val inputStr = "1000withz7 and3 or 99 give42"
// String interpolation using the 's' interpolator
println(s"""Input String: "$inputStr"""")
// Extract numbers using the regex and transformation pipeline
val extractedNums = extractNumbers(inputStr)
// mkString formats the collection to explicitly match the requested array output style
println(s"Extracted Numbers: ${extractedNums.mkString("[", ", ", "]")}")
// Sort the extracted numbers into a new immutable Vector
val sortedNums = sortNumbers(extractedNums)
println(s"Sorted Numbers: ${sortedNums.mkString("[", ", ", "]")}")
}
}
/*
run:
Input String: "1000withz7 and3 or 99 give42"
Extracted Numbers: [1000, 7, 3, 99, 42]
Sorted Numbers: [3, 7, 42, 99, 1000]
*/