Skip to content

Instantly share code, notes, and snippets.

@dikiwidia
Created July 21, 2024 15:15
Show Gist options
  • Save dikiwidia/8fa2db527cfd8aee19dd58cfbffad8bc to your computer and use it in GitHub Desktop.
Save dikiwidia/8fa2db527cfd8aee19dd58cfbffad8bc to your computer and use it in GitHub Desktop.
Cryptarithm with PHP (basic)
<?php
$first_crypt = "AB";
$second_crypt = "AB";
$result_crypt = "BCC";
function calc($first_crypt, $second_crypt, $result_crypt, $operator = 'add') {
$crypt_input = str_split($first_crypt . $second_crypt . $result_crypt);
$merge_input = array_unique($crypt_input);
sort($merge_input);
$len_input = strlen(implode("", $merge_input));
$result_final = "";
$first_loop = pow(10, $len_input-1);
$last_loop = pow(10, $len_input);
for ($i = $first_loop ; $i < $last_loop; $i++) {
$number_string = (string) $i;
$split_number_strings = str_split($number_string);
$number_arrays = array_map('intval', $split_number_strings);
$key = 0;
$new_array = [];
foreach ($merge_input as $char_crypt) {
if (isset($number_arrays[$key])){
$new_array[$char_crypt] = $number_arrays[$key];
} else {
$new_array[$char_crypt] = 'X';
}
$key++;
}
$first_calc = convertStringToNumber($first_crypt, $new_array);
$second_calc = convertStringToNumber($second_crypt, $new_array);
$result_calc = convertStringToNumber($result_crypt, $new_array);
switch ($operator) {
case 'add':
if ($first_calc + $second_calc == $result_calc && $first_calc != 0 && $second_calc != 0){
$result_final .= $first_calc ."<br />";
$result_final .= $second_calc ."<br /><hr />";
$result_final .= $result_calc ."<br /><br /><br />";
}
break;
default:
$result_final .= "Not Operator Found !";
break;
}
}
if ($result_final == ""){
$result_final = "Tidak Ada Solusi untuk Soal ini";
}
return $result_final;
}
function convertStringToNumber($string, $list) {
$splits = str_split($string);
if (is_array($list) && count($list) > 0 && count($splits) > 0){
foreach ($splits as $char_original) {
// echo "c{$char}v{$value}";
$replace_value = "0";
if (isset($list[$char_original])){
$replace_value = $list[$char_original];
}
$result = str_replace($char_original, $replace_value, $string);
$string = $result;
}
}
return (int) $string;
}
echo calc($first_crypt, $second_crypt, $result_crypt);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment