即使编译了代码,也解决不了数独游戏。实际上,它所做的只是将 9 个变量 bN 设置为 true,如果 81 个变量 aPQ 中的任何一个等于 N。
而且它甚至不能有效地做到这个。有 1458 (=18*81) 个条件将每个 bN 变量设置为 true。 (简单检查:每个条件为 3 行;对 9 个变量中的每一个进行 1458 次检查:3 * 1458 * 9 = 39366,文件的大致长度)。
bN的所有setter都是独立的,并且是幂等的,所以可以任意重排,去掉条件的17次重复检查。
此代码的等效(并且足够高效)版本 - 使用数组 - 是:
// Using 10 as array size, as OP's code is one-based;
// first element is unused.
int a[][] = new int[10][10];
// Initialize the elements of a.
boolean b[] = new boolean[10];
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if (a[i][j] >= 1 && a[i][j] <= 9) {
b[a[i][j]] = true;
}
}
}
应该很容易适应方法的最大大小。
在考虑如何使其高效之前,您应该专注于编写 正确、可维护 代码 - 该代码不能达到其既定目的,我不会想成为解决 40k 行代码中的错误所在的人。我能够分析这么多代码的唯一原因是它似乎是生成的,因为它的模式非常统一。
我使用(非常hacky)Python脚本进行了上述分析。
运行使用:
curl http://pastebin.com/raw/NbyTTAdX | python script.py
script.py:
import sys
import re
with open('/dev/stdin') as fh:
lines = fh.readlines()
bequals = re.compile(r'^b\d\s*= true;$')
i = 0
bvariablesetters = {}
while i < len(lines):
if lines[i].strip().startswith('if (') and lines[i].strip().endswith('{'):
# Match the conditionals setting one of the b variables.
if lines[i+2].strip() == '}' and bequals.search(lines[i+1].strip()):
newline = ' '.join(map(str.strip, lines[i:i+3]))
spl = newline.split()
# This is the "b=" variable
bvar = spl[5]
bvariablesetters.setdefault(bvar, []).append(' '.join(newline))
i += 3
continue
else:
# Print out lines which don't match the conditional-set-b pattern, so you
# can see that there's nothing else going on.
sys.stdout.write(lines[i])
i += 1
# Print the number of conditionals setting each of the b variables.
print {(k, len(v)) for k, v in bvariablesetters.iteritems()}
# Print the number of unique conditionals setting each of the b variables.
print {(k, len(set(v))) for k, v in bvariablesetters.iteritems()}
# Print one of the lists of conditions to set a b variable.
print bvariablesetters['b1=']
# Print one of the sets of conditions to set a b variable.
print sorted(set(bvariablesetters['b1=']))