Jump to content

not sure if you'll get it. But it is very difficult.


lecestan96

Recommended Posts

so im on chapter 4 of basic java and the teacher said his program implements a simple "decoder ring".

It will prompt the user for a message to decode and decode the message
based on the following substitution rules:
 
ABCDEFGHIJKLMNOPQRSTUVWXYZ will map to
ZEBRASCDFGHIJKLMNOPQTUVWXY
 
abcdefghijklmnopqrstuvwxyz will also map to
ZEBRASCDFGHIJKLMNOPQTUVWXY
 
any other characters (like space, punctuation, will map to themselves)
 
so if it sees an 'A' (or an 'a'), it will map to 'Z', etc
 i've tried switch statements and for loop and such but van't figure it out please help.

You want to replace one character with another.

 

You can explode the string and do replaces that way.

str_ireplace() or preg_replace()

 

I chose another way.

<?php
$text = "A test string to see the output of this replace.";
$loweralpha = range('a', 'z');
$upperalpha = range('A', 'Z');
$alpha = array_merge($loweralpha,$upperalpha);
$replace = array('Z','E','B','R','A','S','C','D','F','G','H','I','J','K','L','M','N','O','P','Q','T','U','V','W','X','Y','Z','E','B','R','A','S','C','D','F','G','H','I','J','K','L','M','N','O','P','Q','T','U','V','W','X','Y');

echo strtr($text, array_combine($alpha, $replace));

?>

Returns

Z QAPQ PQOFKC QL PAA QDA LTQMTQ LS QDFP OAMIZBA.

You don't really want to create that replace array manually every time

<?php
$str = isset($_GET['str']) ? $_GET['str'] : '';
$kw = isset($_GET['keyword']) ? $_GET['keyword'] : '';
$decode = isset($_GET['decode']) ? 1 : 0;

$str2 = $str ? translate($str, $kw, $decode) : $str;

function translate($str, $kw, $decode=0)
{
    $str = strtoupper($str);
    $alpha = range('A','Z');
    $karr = keyArray($kw, $alpha);
    $trans = $decode ? array_combine($karr, $alpha) : array_combine($alpha, $karr);
    return strtr($str,$trans);
}

function keyArray($keyword, &$alpha)
{   // create translation array from given keyword
    $kw = array_unique(str_split(strtoupper($keyword)));
    $diff = array_diff($alpha, $kw);
    return array_merge($kw, $diff);
}

    
?>
<html>
<head>

<title>Encoder</title>
</head>
<body>
<form>
Input text/Translation<br>
<textarea name="str" rows="5" cols="50"><?=$str2?></textarea>
<br>
Keyword <input type="text" name="keyword" value="<?=$kw?>">
Decode <input type='checkbox' name='decode' value='1'>
<br>
<input type="submit" name="btnSub" value="Translate">
</form>

</body>
</html>

post-3105-0-40131600-1415459571_thumb.png

post-3105-0-02140100-1415459580_thumb.png

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.