Minizinc 中回文的高效谓词

Efficient predicate for palindrome in Minizinc

为了帮助我学习 Minizinc,我正在尝试解决一个简单的问题。我的代码找到了答案,但我很惊讶 运行 这么简单的问题需要大约 10 秒。

问题是"What is the smallest palindromic integer > 10, so that the sum of its digits is > 10 and palindromic too ?"。 我希望代码只做大的假设:答案最多有 8 位数字。

我的代码是(toNum谓词来自hakank网站):

predicate toNum(array[int] of var int: a, var int: n,  int: base) =
          let { int: len = length(a) }
          in
          n = sum(i in 1..len) (
            ceil(pow(int2float(base), int2float(len-i))) * a[i]
          )
          /\ forall(i in 1..len) (a[i] >= 0 /\ a[i] < base)
;

predicate toNum10(array[int] of var 0..9: a, var int: n) = toNum(a, n, 10);

predicate palindrome_array(array[int] of var int: t) =
   let { int: l = length(t), var 1..l: d } in (
   forall(j in 1..d-1) (t[j] = 0) /\
   t[d] != 0 /\
   forall(j in d..(l+d-1) div 2) (t[j] = t[l+d-j])
   )
;
predicate palindrome_int(var int: n) =
   let { int: size = ceil(log10(int2float(ub(n))))+1,
         array[1..size] of var 0..9: digits } in (
   toNum10(digits, n) /\
   palindrome_array(digits)
   )
;

var int: n;
array[1..8] of var 0..9: t;
constraint toNum10(t, n);
constraint palindrome_int(n);
constraint n>10;  
var int: s = sum(t);
constraint palindrome_int(s);
constraint s>10;
constraint alldifferent([n, s]);
solve minimize n;

完整版有以下附加限制:

var int: s2 = sum(i in 1..8) (t[i]*t[i]);
constraint palindrome_int(s2);
constraint s2 > 10;

var int: s3 = sum(i in 1..8) (t[i]*t[i]*t[i]);
constraint palindrome_int(s3);
constraint s3 > 10;

constraint alldifferent([n, s, s2, s3]);

我的代码 wrong/slow 有什么用?

尝试用以下标签策略替换"solve minimize n;":

solve :: int_search(t, first_fail, indomain_min, complete) minimize n;

在我的机器上,它需要 < 0.1 秒。