ruby array中找出重复元素


#上文的inject现在用上了
module Enumerable
def dups
inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
end
end



arr = %w{foo bar baz bar baz qux foo zub}
puts arr.dups.inspect
# => ["baz", "foo", "bar"]



#替换一
inject(Hash.new(0)) {|h,v| h[v] += 1; h}.reject{|k,v| v==1}.keys


这个是比较好理解的

class Array
def only_duplicates
duplicates = []
self.each {|each| duplicates << each if self.count(each) > 1}
duplicates.uniq
end
end




puts [1,2,2,4,5,1].only_duplicates.inspect
==> [1, 2]




require 'benchmark'

module Enumerable
def map_with_index
index = -1
(block_given? && self.class == Range || self.class == Array) ? map { |x| index += 1; yield(x, index) } : self
end
end


class Array

def find_dups
inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select { |k,v| v > 1 }.collect { |x| x.first }
end


def find_dups2
uniq.select{ |e| (self-[e]).size < self.size - 1 }
end

def find_ndups # also returns the number of items
uniq.map { |v| diff = (self.size - (self-[v]).size); (diff > 1) ? [v, diff] : nil}.compact
end


# cf. http://www.ruby-forum.com/topic/122008
def dups_indices
(0...self.size).to_a - self.uniq.map{ |x| index(x) }
end

def dup_indices(obj)
i = -1
ret = map { |x| i += 1; x == obj ? i : nil }.compact
#ret = map_with_index { |x,i| x == obj ? i : nil }.compact
ret.shift
ret
end

def delete_dups(obj)
indices = dup_indices(obj)
return self if indices.empty?
indices.reverse.each { |i| self.delete_at(i) }
self
end

end


array = [1,3,5,5,6,7,9,10,14,18,22,22,4,4,4,3,6]

dups = nil


Benchmark.bm(14) do |t|

t.report('find_dups:') do
dups = array.find_dups
end

end

p dups #=> [5, 22, 6, 3, 4]


p %w(a b a c c d).dups_indices
p %w(a b a c c d).dup_indices('c')
p %w(a b a c c d).delete_dups('a')




class Array

def find_dups
uniq.map {|v| (self - [v]).size < (self.size - 1) ? v : nil}.compact
end

end



def mostused(ahash)
original_size = ahash.size
sizes = {}
ahash.uniq.map { |x| sizes[x] = original_size - ((ahash - [x]).size)}
sizes.sort_by {|k,v| v}.pop
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值