challenge 重複する要素を取り除く

与えられたリストxsの中から、 2回以上出現するものを全部取り除いてください。

サンプル入力
[3, 1, 4, 1, 5, 9, 2, 6, 5]
サンプル出力
[3, 4, 9, 2, 6]

これはアレイのuniqの派生問題です。 リストとかアレイという言葉は言語によってまちまちの意味で使われているので、 「配列のようなもの」という漠然とした意味にとって構いません。

Posted feedbacks - Ruby


	
1
2
3
4
5
def only_unique(ary)
  freq = ary.inject(Hash.new(0)){|h,x| h[x]+=1; h }
  ary.select{|x| freq[x]==1 }
end
only_unique([3, 1, 4, 1, 5, 9, 2, 6, 5]) # => [3, 4, 9, 2, 6]

無難に
1
2
3
4
5
def remove_dups(a)
  a.select{|x|a.grep(x).size == 1}
end

p remove_dups([3, 1, 4, 1, 5, 9, 2, 6, 5]) #=> [3, 4, 9, 2, 6]

正規表現で。
一桁専用+数字専用+ruby1.9じゃ動かないですが。
1
2
3
4
5
6
7
8
9
def string_only_unique(s)
  s.gsub(/(\d)(\d*)\1/){|s|
    string_only_unique($2)
  }
end

def only_unique(ary)
  string_only_unique(ary.to_s).split(//).map{|n| n.to_i}
end

rubyにはArray#uniqがあるというのになぜか使われていないので。

Dan the Occasional Rubyist

1
2
3
4
5
% ruby -e 'puts ARGV.uniq' 1 2 1 2 3 1 2 3 4
1
2
3
4

折角なので, uniqメソッドを利用してみました.

1
2
3
4
5
class Array
  def get_uniq
    uniq.delete_if{|x| index(x) != rindex(x)}
  end
end

Index

Feed

Other

Link

Pathtraq

loading...