Comment detail

四字熟語パズルの作成 (Nested Flatten)
サンプルデータ(8312件),CPU1.8GHz,3秒で14,456件出力されました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def jukugo(f)
  r, ht, a, h, t = {}, {}, {}, {}, {}
  open(f) {|fin|
    cnt = 0
    while line = fin.gets
      a[cnt] = line

      h[line[0..1]] = [] if not h[line[0..1]]
      h[line[0..1]] << cnt #--- head

      t[cnt] = line[6..7] #--- tail
      cnt+=1
    end
  }
  t.each{|c,i|
    next if not h[i]
    
    hh = a[c][0..1]
    h[i].each{|k|
      tt = a[k][6..7]
      next if hh == tt
      hhtt = hh+tt
      ht[hhtt] = [] if not ht[hhtt]

      ht[hhtt].each {|m|
        mm = [a[m[0]], a[m[1]], a[c], a[k]].flatten.sort
        r[sprintf("%s\n",mm)] = true if mm.uniq.size == 4
      }
      ht[hhtt] << [c, k]
    }
  }
  r.each {|i|puts i}
end

jukugo(ARGV[0])
なぜ4人とも結果が違うのかがむしろ新たな問題になっちゃうかも(笑
ソースコードは公開されていますし。

とりあえず僕のコードも公開することにします。
変数dataにユニコード文字列のリストが入っています。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
starts = set(w[0] for w in data)
ends = set(w[3] for w in data)

from collections import defaultdict
start_dict = defaultdict(list)
end_dict = defaultdict(list)

for w in data:
    start_dict[w[0]].append(w)
    end_dict[w[3]].append(w)

count = 0
for s in start_dict:
    starts = start_dict[s]
    n = len(starts)
    if n < 2: continue
    for e in end_dict:
        ends = end_dict[e]
        if len(ends) < 2: continue
        heads = [w[0] for w in ends]
        for i in range(n):
            w = starts[i]
            tail = w[3]
            if tail not in heads: continue
            for j in range(i + 1, n):
                w2 = starts[j]
                tail2 = w2[3]
                if tail == tail2: continue
                if tail2 in heads:
                    w3 = ends[heads.index(tail)]
                    w4 = ends[heads.index(tail2)]
                    count += 1
                    print w
                    print u"%s  %s" % (w2[1], w3[1]) 
                    print u"%s  %s" % (w2[2], w3[2]) 
                    print w4
                    print
僕のコードも30~31行目あたり手抜きなので
もう一度きちんと考える必要がありそうだ…

Index

Feed

Other

Link

Pathtraq

loading...