How to create a common sorted unique array from 3 integer arrays in Kotlin

1 Answer

0 votes
/*
   Function: mergeArrays
   Purpose:  Combine three integer arrays into a single list.
*/
fun mergeArrays(arrA: Array<Int>, arrB: Array<Int>, arrC: Array<Int>): List<Int> {
    val lstMerged = arrA.toList() + arrB.toList() + arrC.toList()
    
    return lstMerged
}

/*
   Function: uniqueSorted
   Purpose:  Convert a list into a sorted list with unique elements.
             Uses distinct() to remove duplicates, then sorts the result.
*/
fun uniqueSorted(lst: List<Int>): List<Int> {
    val arrUnique = lst.distinct().sorted()
    return arrUnique
}

fun main() {
    // Input arrays
    val arr1 = arrayOf(5, 1, 14, 3, 8, 9, 1, 1, 7)
    val arr2 = arrayOf(3, 5, 7, 2, 3)
    val arr3 = arrayOf(2, 9, 8)

    // Step 1: Merge all arrays
    val lstMerged = mergeArrays(arr1, arr2, arr3)

    // Step 2: Create sorted unique array
    val lstResult = uniqueSorted(lstMerged)

    // Step 3: Print result
    print("Sorted unique array: ")
    lstResult.forEach { print("$it ") }
}



/*
run:

Sorted unique array: 1 2 3 5 7 8 9 14 

*/

 



answered 6 days ago by avibootz

Related questions

...