Keyword Transposition Cipher

  • + 0 comments

    PHP Solution

    <?php
    $_fp = fopen("php://stdin", "r");
    $num_tests = intval(trim(fgets(STDIN)));
    
    for ($t = 0; $t < $num_tests; $t++) {
        $keyword = trim(fgets(STDIN));
        $ciphertext = trim(fgets(STDIN));
    
        echo decode($keyword, $ciphertext) . "\n";
    }
    
    
    
    function decode($keyword, $ciphertext) {
        #Step 1: Generate the substitution cipher based on the keyword
    
        //Remove duplicate letter from key and sort it.
        $keyword = array_values(array_unique(str_split($keyword)));
        asort($keyword);
        
        // Get aplhabet without letter in key
        $alphabet = array_diff(range('A', 'Z'), $keyword);
        
        // Chunk alphabet
        $chunk = array_chunk($alphabet, count($keyword));
        
        foreach($keyword as $k=>$v) {
            $substitution[] = $v;
            foreach ($chunk as $arr) {
                if (isset($arr[$k])) {
                    $substitution[] = $arr[$k];
                }
            }
        }
        
        // Create dictionary
        $dictionary = array_combine($substitution, range('A', 'Z'));
    
                
        # Step 2: Decode (Apply the substitution cipher to the ciphertext)
    
        
        $decoded = '';
        $ciphertext = str_split($ciphertext);
        foreach ($ciphertext as $char) {
            if (array_key_exists($char, $dictionary)) {
                $decoded .= $dictionary[$char];
            } else {
                $decoded .= " ";
            }        
        }
        
        return $decoded;
    }
    
    ?>