1

とがそれぞれ次のように定義された文字列であるSとします。T

;; S
A
B
C

;; T
B
C
D

以下を満たす類似の clojure(script) 操作string-intersectionstring-union(より適切な名前がないため) はありますか?

(string-intersection S T)
;; => 
;; B
;; C

(string-union S T)
;; => 
;; A
;; B
;; C
;; D

ご覧のとおり、string-intersectionは (行ごとに) 一致しない行を削除し (一致する行のみを残します)、行string-unionを結合して重複を無視する効果があります。

注:私はclojurescriptを使用していますが、答えはclojureにも一般化されると思います。

4

1 に答える 1

2

あなたの説明から、文字列を一連の線として扱い、集合の交点と和集合を計算したいと思われます。

セットを操作するには、clojure.set名前空間を使用できます。

まず、文字列を一連の行に変換します。

(require '[clojure.string :as str]
         '[clojure.set :as set])

(def s "A\nB\nC")
(def t "B\nC\nD")

(def s-set (into #{} (str/split-lines s)))
(def t-set (into #{} (str/split-lines t)))

次に、和集合と交点を計算できます。

(def s-t-union (set/union s-set t-set))
;; => #{"C" "B" "A" "D"}

(def s-t-intersection (set/intersection s-set t-set))
;; => #{"C" "B"}

そしてそれを並べ替えます:

(def s-t-union-sorted (sort s-t-union))
;; => ("A" "B" "C" "D")

(def s-t-intersection-sorted (sort s-t-intersection))
;; => ("B" "C")

また、行の文字列に戻すこともできます:

(str/join "\n" s-t-union-sorted)
;; => "A\nB\nC\D"

(str/join "\n" s-t-intersection-sorted)
;; => "B\nC"
于 2016-04-25T07:16:53.617 に答える