Home > Software design >  C# sort with Comparer is giving incorrect result
C# sort with Comparer is giving incorrect result

Time:11-17

class Solution {

    List<List<int>> ans = new List<List<int>>();

    public List<List<int>> subsets(List<int> A) {

        var currList = new List<int>();
        A.Sort();
        GenerateSubSets(A, 0, currList);
        ans.Sort(new ListComparer());
        return ans;
    }

    public void GenerateSubSets(List<int> A, int position, List<int> currList)
    {
        if(position > A.Count-1)
        {
            ans.Add(currList);
            return;
        }
    
        GenerateSubSets(A, position 1, new List<int>(currList));
        currList.Add(A[position]);
        GenerateSubSets(A, position 1, new List<int>(currList));

        return; 
    }
}

public class ListComparer : IComparer<List<int>>
{
    public int Compare(List<int> list1, List<int> list2)
    {
        var list1Index = 0;
        var list2Index = 0;

        while((list1Index < list1.Count) && (list2Index < list2.Count))
        {
            if(list1[list1Index].CompareTo(list2[list2Index]) == 0)
            {
                list1Index  ;
                list2Index  ;
                continue;
            }
            return list1[list1Index].CompareTo(list2[list2Index]);
        }
        return list1.Count > list2.Count ? 1 : -1; 
    }
}

The above code when run for test case

[ 8, 5, 19, 11, 10, 7, 18, 16, 13, 17 ]

gives me incorrect answer.

Instead of getting

... [5 10 16 17 ] [5 10 16 17 18 ] ...

I get

... [5 10 16 17 18 ] [5 10 16 17 ] ...

Except for this line all other comparisons seems to be working fine. Also, if I call the sort function twice,

ans.Sort(new ListComparer())

this issue goes away. What am I missing? I am running this code in a leetcode style editor.

CodePudding user response:

Change

return list1.Count > list2.Count ? 1 : -1; 

To

return list1.Count > list2.Count ? -1 : 1; 

Or more straightforward

return list1.Count.CompareTo(list2.Count); 

CodePudding user response:

This is how I normally write this code

 public class ListComparer : IComparer<List<int>>
    {
        public int Compare(List<int> list1, List<int> list2)
        {
            int min = Math.Min(list1.Count(), list2.Count());

            for (int i = 0; i < min; i  )
            {
                if(list1[i] != list2[i])
                    return list1[i].CompareTo(list2[i]);
            }
            return list1.Count().CompareTo(list2.Count());
        }
    }
  • Related