for なんか使うと遅いだろうと思うだろうが,制約条件をせばめてやれば,むしろ他の方法より速くなる。
f5 = function() {
m = 1
o = 0
for (s in 2:9) {
for (e in 2:9) {
if (e == s) next
for (n in 2:9) {
if (n == s || n == e) next
for (d in 2:9) {
if (d == s || d == e || d == n) next
for (r in 2:9) {
if (r == s || r == e || r == n || r == d) next
for (y in 2:9) {
if (y == s || y == e || y == n || y == d || y == r) next
if (sum(10^(3:0)*c(s+m, e+o, n+r, d+e)) == sum(10^(4:0)*c(m, o, n, e, y))) {
cat(sprintf("%s%s%s%s + %s%s%s%s = %s%s%s%s%s\n",
s, e, n, d, m, o, r, e, m, o, n, e, y))
}}}}}}}}
> benchmark(f2(), f3(), f5(), replications=2)
test replications elapsed relative user.self sys.self user.child sys.child
1 f2() 2 24.983 32.488 23.649 1.541 0 0
2 f3() 2 8.835 11.489 6.934 1.980 0 0
3 f5() 2 0.769 1.000 0.755 0.005 0 0