Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active October 6, 2020 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/13d5101d583fdbecd378e61551eebca7 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/13d5101d583fdbecd378e61551eebca7 to your computer and use it in GitHub Desktop.
Just PHP FUN 121.
<?php
# https://www.codewars.com/kata/57814d79a56c88e3e0000786 Simple Encryption #1 - Alternating Split.
function encrypt($text, $n) {
if($n <= 0) return $text;
if(null === $text || 0 == strlen($text)) return $text;
while ($n > 0){
$text = e_step($text);
$n -= 1;
}
return $text;
}
function decrypt($text, $n) {
if($n <= 0) return $text;
if(null === $text || 0 == strlen($text)) return $text;
if(null === $text || 0 == strlen($text)) return $text;
while ($n > 0){
$text = d_step($text);
$n -= 1;
}
return $text;
}
function e_step($str){
$a = ""; $b = "";
for($i = 0; $i < strlen($str); $i+=1)
if(0 == $i % 2) $a .= $str[$i];
else $b .= $str[$i];
return $b.$a;
}
function d_step($str){
$a = ""; $b = ""; $ans ="";
for($i = 0; $i < strlen($str); $i+=1)
if( $i < floor(strlen($str)/2) ) $b .= $str[$i];
else $a .= $str[$i];
for($i = 0, $j = 0; $i < strlen($a) && $j < strlen($b); $i+=1, $j+=1) $ans .= $a[$i].$b[$j];
if($i < strlen($a)) $ans .= substr($a,$i);
return $ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment