裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

send+more=money その3

2013年10月21日 | ブログラミング

R の for の特性を生かせば,f5 は f6 のようにできる。そして,f6 は f5 より速い。あっという間に答えが出る。

関数の中で base::setdiff を最適化したものを使うようにしている。そのようにしないと(base::setdiff を使うと)むしろ f5 より遅くなる。

f6 = function() {
    setdiff = function (x, y) {
        x[match(x, y, 0L) == 0L]
    }
    m = 1L
    o = 0L
    domain = 2:9
    for (s in domain) {
        domain2 = setdiff(domain, s)
        for (e in domain2) {
            domain3 = setdiff(domain2, e)
            for (n in domain3) {
                domain4 = setdiff(domain3, n)
                for (d in domain4) {
                    domain5 = setdiff(domain4, d)
                    for (r in domain5) {
                        domain6 = setdiff(domain5, r)
                        for (y in domain6) {
                            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))
}}}}}}}}

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

send+more=money その2

2013年10月21日 | ブログラミング

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


コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村