Original article: http://blog.stevenlevithan.com/archives/algebra-with-regexes
I calculated the result based on the regular expression in the original text. Php example:
Copy codeThe Code is as follows:
<? Php
/**
* Calculate Ax + By = C
*/
Function suan ($ A, $ B, $ C ){
$ --;
$ 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 'calculate '. $ 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 will explain
In a simple formula: 2x + 3y = 9
Principle:
This function generates such a regular expression.
Copy codeThe Code is as follows: ^ (. *) \ 1 {1} (. *) \ 2 {2} $
To match a repeated string "-" with a length of 9, the length of the two groups is the value of x and y.
Regular Expression explanation:
[(. *)] Is a number ranging from 0 to countless.
\ 1 is to reference a group. The following [{1}] is repeated once.
The second half is \ 2, which is to reference two groups. The following [{2}] is repeated once.
The translation of the English blog is as follows:
The expression [^ (. *) \ 1 {16} (. *) \ 2 {11} $] of the binary equation 17x + 12y = 51 ]. It's easy to understand. [(. *)] Is a number ranging from 0 to countless. (This is followed by the above. In fact, [.] point number indicates the character "1 ")
That is, 0 to countless 1, followed by [\ 1] reference once. The next [{16}] is 16 times. Act on the previous [\ 1], that is, 16 references. In addition, the initial [(. *)] is exactly 17 times. The other one will not talk about it, just like this one.
The RegEx engine tries 【(. *): attempts to add 0 to countless characters including "1", 0 characters "1", 1 character "1", and 2 characters "1. Otherwise, the maximum number of all characters "1" (51 characters "1") must be tried ").
PS: when there is no solution, both x and y are 0.