How to define user base of numbers in php?

I need to define a new number base for my user calculations,

I have a list of orders of 11 characters (say, a, h, k, d, e, f, g, z, i, j, m) I want to be able to perform math tasks on them as if they were a number base. For example, a + h = k, a + k = d, j ++ = m, etc.

Is it possible?

The best way I was thinking was to take a regular base of 11 and just replace all the characters before and after the calculation itself (so that j ++ would actually be 9 ++ = a, and then a would be converted to m). This method is not very effective, but will work.

Any better ideas?

Thank.

+4
source share
1 answer

PHP , , . , .

base11 - . PHP base_convert() . , base11, base11 , .

Hackish!, .

function add($a, $b) {
    $custom_digits = 'ahkdefgzijm';
    $base11_digits = '0123456789A';

    // translate custom numbers to base11
    $base11_a = strtr($a, $custom_digits, $base11_digits);
    $base11_b = strtr($a, $custom_digits, $base11_digits);

    // translate base11 numbers to decimal
    $decimal_a = base_convert($base11_a, 11, 10);
    $decimal_b = base_convert($base11_b, 11, 10);

    // Do the calculation
    $result = $decimal_a + $decimal_b;

    // Convert result back to base11
    $base11_result = base_convert($result, 10, 11);

    // Translate base11 result into customer digits
    return strtr($base11_result, $base11_digits, $custom_digits);
}

!:

h + h == k

:)


:

function dec_to_custom($n) {
    static $custom_digits = 'ahkdefgzijm';
    static $base11_digits = '0123456789a';
    return strtr(base_convert($n, 10, 11), $base11_digits, $custom_digits);
}

function custom_to_dec($n) {
    static $custom_digits = 'ahkdefgzijm';
    static $base11_digits = '0123456789a';
    $base11 = strtr($n, $custom_digits, $base11_digits);
    return base_convert($base11, 11, 10);
}

, (!) :

echo dec_to_custom(custom_to_dec(1) + custom_to_dec(1));

, . , , strtr(). , strtr(), .

+4

All Articles