Organizing Containers of Balls

  • + 1 comment

    Here is my C# solution.

    In short, we calculate sizes of containers and count of balls of each type. And then, for each type of balls we try to find a container of appropriate size. If we can do this we succeed, otherwise we fail.

    static bool OrganizingContainersCore(List<List<int>> containers) {
        // containers: size of container -> count of that size
        Dictionary<int, int> containerInfo = new();
    
        // balls
        int[] balls = new int[containers.Count];
    
        foreach(var container in containers) {
            int containerSz = 0;
    
            for(int j = 0; j < container.Count; j++) {
                int num = container[j];
                balls[j] += num;
                containerSz += num;
            }
            containerInfo.TryGetValue(containerSz, out int count);
            containerInfo[containerSz] = count + 1;
        }
    
        // compare
        foreach(int ballCount in balls) {
            if(!containerInfo.TryGetValue(ballCount, out int b))
                return false;
    
            if(b > 1)
                containerInfo[ballCount] = b - 1;
            else
                containerInfo.Remove(ballCount);
        }
        return containerInfo.Count == 0;
    }