Organizing Containers of Balls

  • + 0 comments

    These sorting are used in CMS especially WordPress . I design a website in WordPress( https://goldrateinfo.ae/سوق-الذهب-الشارقة ) and used it internally in func.php

    PHP Solution

    function sortBalls( $containers ) { 
        $ballTypes = [];
        $swaps = 0;
    
        // Group the balls by type
        foreach ($containers as $container) {
            $ballType = $container[0];
            if (!isset($ballTypes[$ballType])) {
                $ballTypes[$ballType] = [];
            }
            $ballTypes[$ballType] = array_merge($ballTypes[$ballType], $container);
        }
    
        // Assign the balls back to the containers
        $index = 0;
        foreach ($ballTypes as $type => $balls) {
            foreach ($balls as $ball) {
                if ($containers[$index][0] != $ball) {
                    // Swap the ball to its correct container
                    $swaps++;
                    $temp = $containers[$index][0];
                    $containers[$index][0] = $ball;
                    $containers[$index + 1][0] = $temp;
                }
                $index++;
            }
        }
    
        return $swaps;
    }
    
    // Example usage
    $containers = [
        [1, 1, 2, 2, 3, 3],
        [1, 1, 2, 2, 3, 3],
        [1, 2, 3, 1, 2, 3]
    ];
    
    $swaps = sortBalls($containers);
    echo "Minimum number of swaps required: " . $swaps;