我有一些情况如下.
> 1? 2?
>?2 ?? 3
>? ?
> 5?0
现在我应该做的是找到一些代表问号的值,这将产生2个数字之间的最小可能差异.
答案应该是
> 19 20
> 023 023
> 0 0
> 05 00
注意:在2个值之间的最小绝对差之后将产生的数字必须最小.如上所述,最后一种情况可能是15和10,绝对差值为5,但无效.
我尝试了一些排列组合的想法,用于单独替换两个数字的问号,然后找出数字,但是数字的长度最多可以达到每个数字18位数.所以我相信这不是一个好主意.
然后我试图搜索类似的问题,但没有帮助.
我仍然认为正则表达式可能有助于解决这个问题,但我坚持如何做到这一点.
任何帮助欢迎!感谢名单!
好的,我有一个解决方案.
说明:
使用正则表达式来获取两个数字,然后从左到右成对比较,从假设相等.意思是他们都尽可能地解决相同的号码,如果两者都同时解决了0.
在有一对不相等的数字后,开始将较低的数字设置为9,将较高的数字设置为0,使其尽可能靠近.
Here是它的一个例子.
- function minDiff($str) {
- preg_match("/([\d\?]+) ([\d\?]+)/",$str,$matches);
- $first = $matches[1];
- $second = $matches[2];
- $biggest = 0; // -1 = first,0 = none,1 = second
- $firstResult = 0;
- $secondResult = 0;
- for ($i = 0; $i < strlen($first); $i++) {
- $powerValue = strlen($first) - $i - 1;
- if ($biggest != 0) { // not equal
- if (!strcmp($first[$i],'?') && !strcmp($second[$i],'?')) {
- if ($biggest > 0) { // second is biggest
- $firstResult += 9 * pow(10,$powerValue);
- } else { // first is biggest
- $secondResult += 9 * pow(10,$powerValue);
- }
- } elseif (!strcmp($first[$i],$powerValue);
- }
- $secondResult += $second[$i] * pow(10,$powerValue);
- } elseif (!strcmp($second[$i],'?')) {
- if ($biggest < 0) { // first is biggest
- $secondResult += 9 * pow(10,$powerValue);
- }
- $firstResult += $first[$i] * pow(10,$powerValue);
- } else {
- $firstResult += $first[$i] * pow(10,$powerValue);
- $secondResult += $second[$i] * pow(10,$powerValue);
- }
- } else { // both equal (so far)
- if (!strcmp($first[$i],'?')) {
- $firstResult += $second[$i] * pow(10,'?')) {
- $firstResult += $first[$i] * pow(10,$powerValue);
- $secondResult += $first[$i] * pow(10,$powerValue);
- } else {
- if (intval($first[$i]) > intval($second[$i])) {
- $biggest = -1;
- } elseif (intval($first[$i]) < intval($second[$i])) {
- $biggest = 1;
- }
- $firstResult += $first[$i] * pow(10,$powerValue);
- }
- // Find if next number will change
- if (($i + 1) < strlen($first) && strcmp($first[$i + 1],'?') && strcmp($second[$i + 1],'?')) {
- $diff = preg_replace('/\?/','0',substr($first,$i + 1)) - preg_replace('/\?/',substr($second,$i + 1));
- echo "$diff\n";
- // Check to see if you need to add 1 to the value for this loop
- if ($diff > pow(10,$powerValue) / 2) {
- $secondResult += pow(10,$powerValue);
- $biggest = 1;
- } elseif ($diff < pow(10,$powerValue) / -2) {
- $firstResult += pow(10,$powerValue);
- $biggest = -1;
- }
- }
- }
- }
- echo "first: ".str_pad($firstResult,strlen($first),"0",STR_PAD_LEFT)."\n";
- echo "second: ".str_pad($secondResult,strlen($second),STR_PAD_LEFT)."\n\n";
- }