fork download
  1. #
  2. # [odai_11_911 単語のグルーピング]
  3. # @param h [type] [グルーピング用ハッシュ]
  4. # @param words [type] [単語リスト。['goose', 'pigeon']など]
  5. # 戦略:
  6. # ・Hashを使う(単語 => グループ番号)
  7. # ・単語リストを入力から得るたびに、既存のハッシュ中に該当するグループ番号が有るか調べる
  8. # ・入力単語が全て既存のグループになければ、既存番号+1を割り当てる。
  9. # ・入力単語が1つでも全て既存のグループにあれば、得た番号リストの小さい方に紐つける。
  10. # 同時に、得た番号の大きい方は、番号の小さい方に紐つける。
  11. # @return [Hash] [入力単語リスト1行分を反映した後のハッシュ]
  12. def odai_11_911(h, words)
  13. w = (words.map { |e| h[e] }).compact
  14.  
  15. # 新規wordの場合
  16. if w == []
  17. vmax = h.values.compact.uniq
  18. vnext = vmax == [] ? 0 : vmax.max + 1
  19. words.map { |e| h[e] = vnext }
  20. return h
  21. end
  22.  
  23. # 既存wordの場合
  24. vmin = w.min
  25. vmax = w.max
  26. words.map { |e| h[e] = vmin }
  27. h.map { |k, v| h[k] = vmin if v == vmax }
  28. h
  29. end
  30.  
  31. h = {}
  32. while w = gets
  33. w = w.chomp
  34. words = w.split(' ')
  35. h = odai_11_911(h, words)
  36. end
  37.  
  38. h.values.uniq.map do |n|
  39. p (h.map { |k, v| k if v == n }).compact.sort
  40. end
Success #stdin #stdout 0s 28224KB
stdin
goose pigeon
cat dog
eel goldfish
goose duck
horse dog
cod eel
dove pigeon
dog rhino
goldfish squid
goose lark
stdout
["dove", "duck", "goose", "lark", "pigeon"]
["cat", "dog", "horse", "rhino"]
["cod", "eel", "goldfish", "squid"]