Quick actions

cmd+k|ctrl+k

Navigation

Languages

Script de Noémie

Snippet info

Language

Php

Visibility

public

Author

mosi

Created

2018-11-21T04:00:13Z

Updated

2018-11-21T04:00:13Z

<?php

// Function to generate a list of '(' and ')'
// This represents (1, 3)...(n-1, n)
function generateList($n) {
    $array = array();
    for ($i = 0; $i<$n; $i++) {
        $array[2*$i] = '(';
        $array[2*$i+1] = ')';
    }
    
    return $array;
}

// Function to display the previous list
function displayList($array) {
    $list = '';
    $i = 1;
    
    foreach ($array as $value) {
        if ($value == '(') {
            $list = $list.$value.$i.',';
        } else { // It's ')' case
            $list = $list.','.$i.$value;
        }
        $i = $i+2;
    }
    
    // The function is not perfect.
    $list = str_replace(',,', ',', $list);
    
    echo $list."\n";
}

// Function to sort the list with cocktailSort
function sortList($array) {
    $n = count($array);
    $isSwap = true;
    
    while ($isSwap) {
        $isSwap = false;
        
        for ($i = 0; $i < $n-1; $i++) {
            // If we have ')(' we swap the parenthesis
            if ($array[$i] == ')' && $array[$i+1] == '(') {
                $array[$i] = '(';
                $array[$i+1] = ')';
                
                // We display the new list
                displayList($array);
                $isSwap = true;
            }
        }
        for ($i = $n-2; $i >= 0; $i--) {
            // If we have ')(' we swap the parenthesis
            if ($array[$i] == ')' && $array[$i+1] == '(') {
                $array[$i] = '(';
                $array[$i+1] = ')';
                
                // We display the new list
                displayList($array);
                $isSwap = true;
            }
        }
    }
}

function show($n) {
    $array = generateList($n);
    displayList($array);
    sortList($array);
}

show(8);

?>
INFO