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

1 Answer

0 votes
using System;
using System.Collections.Generic;

class MergeUniqueSorted
{
    /*
       Function: MergeArrays
       Purpose:  Combine three integer arrays into a single list.
    */
    static List<int> MergeArrays(int[] arrA, int[] arrB, int[] arrC) {
        List<int> lstMerged = new List<int>();
        lstMerged.AddRange(arrA);
        lstMerged.AddRange(arrB);
        lstMerged.AddRange(arrC);
        
        return lstMerged;
    }

    /*
       Function: UniqueSorted
       Purpose:  Convert a list into a sorted list with unique elements.
                 Uses HashSet to remove duplicates, then sorts the result.
    */
    static List<int> UniqueSorted(List<int> lst) {
        HashSet<int> setUnique = new HashSet<int>(lst);   // unique values
        List<int> lstResult = new List<int>(setUnique);
        
        lstResult.Sort();                                 // sort ascending
        
        return lstResult;
    }

    static void Main()
    {
        // Input arrays
        int[] arr1 = { 5, 1, 14, 3, 8, 9, 1, 1, 7 };
        int[] arr2 = { 3, 5, 7, 2, 3 };
        int[] arr3 = { 2, 9, 8 };

        // Step 1: Merge all arrays
        List<int> lstMerged = MergeArrays(arr1, arr2, arr3);

        // Step 2: Create sorted unique list
        List<int> lstResult = UniqueSorted(lstMerged);

        // Step 3: Print result
        Console.Write("Sorted unique array: ");
        foreach (int x in lstResult) {
            Console.Write(x + " ");
        }
    }
}



/*
run:

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

*/

 



answered May 6 by avibootz

Related questions

...