Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active November 4, 2020 18:14
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/f6396c0661e157c20c00bb12d4259d12 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/f6396c0661e157c20c00bb12d4259d12 to your computer and use it in GitHub Desktop.
Just PHP FUN 143.
<?php
# https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e Error correction #1 - Hamming Code.
function encode($text){
if(empty($text)) return '';
$a = str_split($text);
return implode(array_map('chr2code',$a));
}
function chr2code($chr){
$chr = str_pad(decbin(ord($chr)),8,"0",STR_PAD_LEFT);
$answer = "";
for($i = 0; $i < strlen($chr) ; $i += 1) $answer .= str_repeat($chr[$i],3);
return $answer;
}
function decode($bits){
$single_bit = "";
for($i = 2; $i < strlen($bits); $i += 3){
$x = [$bits[$i-2],$bits[$i-1],$bits[$i]];
$z = array_count_values($x);
if(2 <= $z['1']){ $single_bit .= '1'; }
else{ $single_bit .= "0";}
}
$arr = [];
for($i = 0; $i < strlen($single_bit); $i += 1){
if(0 == $i%8) array_push($arr,"");
$arr[count($arr) - 1] .= $single_bit[$i];
}
$arr = array_map(fn($x) => chr(bindec($x)), $arr);
return implode($arr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment