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

1 Answer

0 votes
/*
   Function: mergeArrays
   Purpose:  Combine three integer arrays into a single list.
*/
func mergeArrays(_ arrA: [Int], _ arrB: [Int], _ arrC: [Int]) -> [Int] {
    let lstMerged = arrA + arrB + arrC
    
    return lstMerged
}

/*
   Function: uniqueSorted
   Purpose:  Convert a list into a sorted list with unique elements.
             Uses Set to remove duplicates, then sorts the result.
*/
func uniqueSorted(_ lst: [Int]) -> [Int] {
    let arrUnique = Array(Set(lst)).sorted()
    
    return arrUnique
}

// Input arrays
let arr1 = [5, 1, 14, 3, 8, 9, 1, 1, 7]
let arr2 = [3, 5, 7, 2, 3]
let arr3 = [2, 9, 8]

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

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

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



/*
run:

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

*/

 



answered 6 days ago by avibootz

Related questions

...