Created
May 24, 2021 16:35
-
-
Save johncongdon/7f21af3ed2589a83828fe13cf03d21fa to your computer and use it in GitHub Desktop.
This is very ugly code that solves the php[magazine] puzzle of the month for May 2021
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$chars = array_merge(range('a', 'z'), range('A','Z'), range(0,9), [' ', ',', "'"]); | |
shuffle($chars); | |
$table = []; | |
$header = ' '; | |
foreach (range(1,8) as $row) { | |
$header .= " $row "; | |
$table[$row] = array_slice($chars, ($row-1)*8, 8); | |
} | |
print " " . $header . "\n"; | |
foreach ($table as $row => $col) { | |
print " $row "; | |
print implode($col, " "); | |
print "\n"; | |
} | |
$message = "Let's Record A Podcast"; | |
print $message . "\n"; | |
$cipher = encrypt($message, $table); | |
print $cipher . "\n"; | |
$decrypted = decrypt($cipher, $table); | |
print $decrypted . "\n"; | |
function encrypt($message, $table) { | |
$chars = str_split($message); | |
$cipher = ''; | |
foreach ($chars as $char) { | |
$cipher .= find_coords($table, $char); | |
} | |
return $cipher; | |
} | |
function find_coords($table, $char) { | |
foreach ($table as $row => $col) { | |
if (in_array($char, $col)) { | |
foreach ($col as $pos => $check) { | |
if ($check === $char) { | |
return $row . $pos + 1; | |
} | |
} | |
} | |
} | |
return "|$char|"; | |
} | |
function decrypt($message, $table) { | |
$coords = str_split($message, 2); | |
$decrypted = ''; | |
foreach ($coords as $coord) { | |
[$row, $col] = str_split($coord); | |
$decrypted .= $table[$row][$col-1]; | |
} | |
return $decrypted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment