相等長度的給定兩個串使得其中的差異發生
s1 = "ACCT"
s2 = "ATCT"
我想找出其中存在字符串不同的位置比較相等的長度的串並注意到。所以我已經做到了。 (請建議一個更好的做法,我敢打賭應該有)
z= seq1.chars.zip(seq2.chars).each_with_index.map{|(s1,s2),index| index+1 if s1!=s2}.compact
z是兩個字符串不同的位置數組。在這種情況下z返回2
想象一下,我添加了一個新的字符串
s3 = "AGCT"
,我希望將它與其他人比較,看看那裏的3串不同。我們可以使用與上面相同的方法,但是這一次
s1.chars.zip(s2.chars,s3.chars)
返回一個數組數組。給定兩個字符串,我只是比較兩個字符的平等,但隨着我添加更多的字符串,它開始變得壓倒性的,並且隨着字符串變長。
#=> [["A", "A", "A"], ["C", "T", "G"], ["C", "C", "C"], ["T", "T", "T"]]
運行
s1.chars.zip(s2.chars,s3.chars).each_with_index.map{|item| item.uniq}
#=> [["A"], ["C", "T", "G"], ["C"], ["T"]]
可以幫助減少冗餘和返回是完全一樣的(大小爲1的非空的子陣列)的位置。然後,我可以打印出的大小的子陣列的索引和內容> 1.
s1.chars.zip(s2.chars,s3.chars,s4.chars).each_with_index.map{|item| item.uniq}.each_with_index.map{|a,index| [index+1,a] unless a.size== 1}.compact.map{|h| Hash[*h]}
#=> [{2=>["C", "T", "G"]}]
我覺得這將下滑停頓或很慢,因爲我增加字符串數量和字符串長度變長。什麼是最佳做法的其他方法? 謝謝。
你可能想看看通用的差異算法:http://en.wikipedia.org/wiki/Diff#Algorithm – 2011-04-29 07:43:38
[diff a ruby string or array](http:// stackoverflow。 com/questions/80091/diff-a-ruby-string-or-array) – sawa 2011-05-23 08:23:25