I need to create a function with below specification:
- it takes two lists of distinct ints as input and outputs list of tuples <int?, int?>,
- the structure of the tuple must be either (a, a), (a, null) or (null, a),
- the order of the tuples in the result list is irrelevant.
Cases:
Case 1
Input: [] , []
Output: []
Case 2
Input: [4, 2, 3, 1 ] , [ 1, 2, 3, 4]
Output: [(4,4), (2,2), (3,3), (1,1)]
Case 3
Input: [4, 2, 3, 1] , []
Output: [(4, null), (2,null), (3,null), (1,null)]
Case 4
Input: [] , [ 1, 2, 3, 4 ]
Output: [(null, 1), (null,2), (null,3), (null,4)]
Case 5
Input: [ 1, 2, 5] , [ 1, 2, 3, 4]
Output: [(1, 1), (2,2), (5,null), (null,3), (null,4)]
My implementation (C#)
Below is my implementation of the Function and it seems to work. However, it seems not to be very optimal and I am searching for a better approach.
internal static List<Tuple<int?, int?>> PairInts(List<int> firstList, List<int> secondList)
{
List<Tuple<int?, int?>> pairs = new List<Tuple<int?, int?>>();
List<int> firstListBackup = new List<int>(firstList);
List<int> secondListBackup = new List<int>(secondList);
foreach (int val in firstList)
{
foreach (int val2 in secondList)
{
if (val == val2)
{
pairs.Add(new Tuple<int?, int?>(val, val2));
firstListBackup.Remove(firstListBackup.Where(v => v == val).FirstOrDefault());
secondListBackup.Remove(secondListBackup.Where(v => v == val2).FirstOrDefault());
}
}
}
foreach (int val in firstListBackup)
{
pairs.Add(new Tuple<int?, int?>(val, null));
}
foreach (int val in secondListBackup)
{
pairs.Add(new Tuple<int?, int?>(null, val));
}
return pairs;
}