SoFunction
Updated on 2025-03-03

Regular expression solution binary equation code

original:/archives/algebra-with-regexes
I actually calculated the results according to the rules I wrote in the original text. On php example:

Copy the codeThe code is as follows:

<?php
/**
* Calculate Ax+By=C
 */
function suan($A, $B, $C) {
 $A--;
 $B--;
 $str = str_repeat('-', $C);
 $search = '/^(.*)\1{' . $A . '}(.*)\2{' . $B . '}$/';
 preg_match($search, $str, $r);
 return array('x' => strlen($r[1]), 'y' => strlen($r[2]));
}
$A = 2;
$B = 3;
$C = 9;
$r = suan($A, $B, $C);
// test
echo 'calculation' . $A . 'x+' . $B . 'y=' . $C . '<br />';
echo 'x=' . ($r[x]) . '<br />';
echo 'y=' . ($r[y]);
// Output
// Calculate 2x+3y=9
// x=3
// y=1
?>

I'll explain
Let's talk about it in a simple formula: 2x+3y=9

principle:
This function generates a regularity
Copy the codeThe code is as follows:
^(.*)\1{1}(.*)\2{2}$

To match a repeat string of length 9 "-" and match the length of two groups, it is the values ​​of x   and y

Regular explanation:
【(.*)】that is, 0 to countless [.】point numbers.
\1 is to refer to a group. The following [{1}] is repeated once.
The second half is \2, which refers to 2 groups. The following [{2}] is repeated once.
Here is the translation of that English blog:
The binary equation 17x + 12y = 51, and its expression [^(.*)\1{16}(.*)\2{11}$]. Very easy to understand. 【(.*)】that is, 0 to countless [.】point numbers. (This is what I said above. In fact, the dot sign wants to represent the character "1")
That is, 0 to countless 1s, followed by [\1] once. The next [{16}] is 16 times. It acts on the previous [\1], that is, 16 quotes. Add the first [(.*)] to a total of exactly 17 times. I won’t talk about the next one, just like this one.
The regular engine will try to try to increase the number of characters "1", 0 characters "1", 1 character "1", and 2 characters "1" in [(.*)] in sequence. Until successful, otherwise you have to try the maximum number of all characters "1" (here is 51 characters "1").

PS: No solution is considered, when there is no solution, both x and y are 0