发布于 2022-04-19 10:41:32
f=n=>n&&+"0123212342"[n%10]+f(n/10|0)在标准减法表示法中,数字的长度对于单位、几十个、数百个和数千个(最多3000)是相同的。所以我们可以递归地计算总长度。
| units | tens | 100's | 1000's | length
---+-------+------+-------+--------+--------
0 | - | - | - | - | 0
1 | I | X | C | M | 1
2 | II | XX | CC | MM | 2
3 | III | XXX | CCC | MMM | 3
4 | IV | XL | CD | | 2
5 | V | L | D | | 1
6 | VI | LX | DC | | 2
7 | VII | LXX | DCC | | 3
8 | VIII | LXXX | DCCC | | 4
9 | IX | XC | CM | | 2这是试图找到一个简短的公式,而不是查找表。但它还是更长。
f=n=>n&&f(n/10|0)+(30%(n%=10)&171/n^n%4)如果我们可以把输入作为数字列表,那么它就会变得更短:
a=>a.map(n=>t+=30%n&171/n^n%4,t=0)|t发布于 2022-04-19 10:04:04
发布于 2022-04-19 23:54:12
分别使用计算每个十进制数字长度的@Arnauld的想法。x**a%b%5表单中的神奇哈希似乎运行得很好。
f=lambda n:n and(n%10)**24%8684%5+f(n/10)其他魔法:
lambda n:sum(7125144/ord(c)%5for c in`n`) # 41
f=lambda n:n and(n%5+n/5%2>>n%5/4)+f(n/10) # 42 (has actual strategy)或者,同样的长度,但谁不喜欢小魔法hash?
lambda n:sum(hash(c+'WQDE')%5for c in`n`)下面的小C脚本查找所有可能的4字节长后缀作为散列的种子,大约需要1秒钟才能完成。有趣的是,在12个有效的解决方案中,'WQDE'是唯一一个具有所有大写字符的解决方案。如果你想一想,这种情况发生的机会只有26^4/127^4 ~ 0.176%!
// https://github.com/python/cpython/blob/v2.7/Objects/stringobject.c#L1263
#include <stdio.h>
#include <time.h>
int py_mod(long long x, int m) { int ret = x % m; return ret >= 0 ? ret : ret + m; }
const long long h[10] = {6144036912055440, 6272037681056595, 6400038450057750, 6528039219058905, 6656039988060060, 6784040757061215, 6912041526062370, 7040042295063525, 7168043064064680, 7296043833065835};
long long h0[10], h1[10], h2[10];
int main() {
clock_t sclock = clock();
for (int c0 = 1; c0 < 128; c0++) {
for (int i0 = 0; i0 < 10; i0++) h0[i0] = (h[i0] ^ c0) * 1000003;
for (int c1 = 1; c1 < 128; c1++) {
for (int i1 = 0; i1 < 10; i1++) h1[i1] = (h0[i1] ^ c1) * 1000003;
for (int c2 = 1; c2 < 128; c2++) {
for (int i2 = 0; i2 < 10; i2++) h2[i2] = (h1[i2] ^ c2) * 1000003 ^ 5;
for (int c3 = 1; c3 < 128; c3++) {
if (py_mod(h2[0] ^ c3, 5) != 0) continue;
if (py_mod(h2[1] ^ c3, 5) != 1) continue;
if (py_mod(h2[2] ^ c3, 5) != 2) continue;
if (py_mod(h2[3] ^ c3, 5) != 3) continue;
if (py_mod(h2[4] ^ c3, 5) != 2) continue;
if (py_mod(h2[5] ^ c3, 5) != 1) continue;
if (py_mod(h2[6] ^ c3, 5) != 2) continue;
if (py_mod(h2[7] ^ c3, 5) != 3) continue;
if (py_mod(h2[8] ^ c3, 5) != 4) continue;
if (py_mod(h2[9] ^ c3, 5) != 2) continue;
printf("found: (%d,%d,%d,%d) [%c%c%c%c]\n",
c0, c1, c2, c3, c0, c1, c2, c3);
}
}
}
}
printf("Time elapsed: %.3fs\n", (double) (clock() - sclock) / CLOCKS_PER_SEC);
return 0;
}https://codegolf.stackexchange.com/questions/246360
复制相似问题