Organizing Containers of Balls

  • + 0 comments

    Solution in C#, first thing I did was realize that there is very little sorting necessary in this problem. What we have to do is find the sums of the x rows and the sums of the y columns. Once we've done that we sort both arrays and compare the arrays to ensure they match 1-to-1. If they do not, they are impossible to sort otherwise they are possible. I left my debugging code for brevity.

    Essentially this swap sort method only works if each bucket has enough storage in it to hold the maximum count of a given item. (i.e. if there are two items of type A, there must be a corresponding bucket with two slots) this must be true for each item.

     public static string organizingContainers(List<List<int>> container)
    {
        List<int> xSum = new List<int>();
        List<int> ySum = new List<int>();
        int localXSum = 0;
        int localYSum = 0;
    
        for(int i = 0; i < container.Count; i++){
            localXSum = 0;
            localYSum = 0;           
            for(int j = 0; j < container[i].Count; j++){
                localXSum +=  container[i][j];
                localYSum += container [j][i];
            }
            xSum.Add(localXSum);
            ySum.Add(localYSum);
        }
    
        xSum.Sort();
        ySum.Sort();
    
        foreach(int pos in xSum){
            Console.Write(pos + " ");
        }
    
        Console.WriteLine();
    
        foreach(int pos in ySum){
            Console.Write(pos + " ");
        }
    
        Console.WriteLine();
    
        for(int i = 0; i < xSum.Count; i++){
            if(xSum[i] != ySum[i]){
                return "Impossible";
            }
        }
    
        return "Possible";
    }