s = 0 unseen = 0 seen(v) = bit test(s, v) see(v) = s = bit or(s, 2^v); while (seen(unseen), unseen++) base = 10 \\ can the digits of x and of y be combined to form a palindrome ? ok(x,y) = { my (d = concat(apply(v -> if (v==0, [0], digits(v, base)), [x,y])), f=vector(base)); for (i=1, #d, f[d[i]+1]++); #select(v -> v%2, f)<=1 && f[1]+1!=#d } \\ least v not yet in the sequence whose digits can be combined with those of p to form a palindrome other(p) = { see(p); for (v=unseen, oo, if (!seen(v) && ok(p,v), return (v); ); ); } \\ combine digits of x and y to form the least palindrome mix(x,y) = { my (d = concat(apply(v -> if (v==0, [0], digits(v, base)), [x,y])), f=vector(base)); for (i=1, #d, f[d[i]+1]++); my (m=0); \\ middle digit if (#d%2, for (i=1, base, if (f[i]%2, m = i-1; f[i]--; break; ); ); ); my (left=0); for (i=2, base, if (f[i], left = i-1; f[i]-=2; break; ); ); for (i=1, base, while (f[i], left = base*left + i-1; f[i]-=2; ); ); return ((left * 10^(#d%2) + m) * base^(#d\2) + fromdigits(Vecrev(digits(left, base)), base)); } my (p=0); for (n=0, 10 000, v=other(p); print (n " " mix(p,v)); p=v); quit