We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
<?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));echodecode($keyword,$ciphertext)."\n";}functiondecode($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($keywordas$k=>$v){$substitution[]=$v;foreach($chunkas$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($ciphertextas$char){if(array_key_exists($char,$dictionary)){$decoded.=$dictionary[$char];}else{$decoded.=" ";}}return$decoded;}?>
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Keyword Transposition Cipher
You are viewing a single comment's thread. Return to all comments →
PHP Solution