/**
* Program to extract and sort integer values embedded within a string containing text.
* Demonstrates Kotlin's standard library extensions, regular expressions, and
* sequence-based processing.
*/
/**
* Extracts all contiguous sequences of digits from the provided string and converts
* them into a list of 64-bit integers.
*
* @param input The raw string containing text and embedded numbers.
* @return A [List] of [Long] numbers in their original order of appearance.
*/
fun extractNumbers(input: String): List<Long> {
// Regex pattern matching one or more contiguous digits (\d+)
val digitRegex = Regex("""\d+""")
// 1. findAll(input) returns a Sequence<MatchResult> of non-overlapping matches.
// Using sequences enables lazy evaluation, which avoids unnecessary intermediate allocations.
// 2. map transformation accesses each matched string value and parses it safely to Long.
// 3. toList() materializes the transformed sequence into an immutable List.
return digitRegex.findAll(input)
.map { match -> match.value.toLong() }
.toList()
}
/**
* Sorts a list of numbers in ascending order.
*
* @param numbers The list of numbers to sort.
* @return A new list containing the numbers sorted in ascending order.
*/
fun sortNumbers(numbers: List<Long>): List<Long> {
// sorted() uses an optimized dual-pivot Quicksort / Timsort algorithm under the hood (O(N log N)).
// It returns a new immutable sorted list while keeping the input collection untouched.
return numbers.sorted()
}
fun main() {
val inputStr = "1000withz7 and3 or 99 give42"
// Raw string template formatting for output display
println("Input String: \"$inputStr\"")
// Extract numbers using regular expressions and sequences
val extractedNums = extractNumbers(inputStr)
println("Extracted Numbers: $extractedNums")
// Sort the extracted numbers into a new list
val sortedNums = sortNumbers(extractedNums)
println("Sorted Numbers: $sortedNums")
}
/*
run:
Input String: "1000withz7 and3 or 99 give42"
Extracted Numbers: [1000, 7, 3, 99, 42]
Sorted Numbers: [3, 7, 42, 99, 1000]
*/