凝望长空 发表于 2011-12-14 19:26

ruby array中找出重复元素

ruby array中找出重复元素











Ruby代码1.#上文的inject现在用上了
2.module Enumerable
3.def dups
4.    inject({}) {|h,v| h=h.to_i+1; h}.reject{|k,v| v==1}.keys
5.end
6.end
Ruby代码1.arr = %w{foo bar baz bar baz qux foo zub}
2.puts arr.dups.inspect
3.# => ["baz", "foo", "bar"]Ruby代码1.#替换一
2.inject(Hash.new(0)) {|h,v| h += 1; h}.reject{|k,v| v==1}.keys这个是比较好理解的



Ruby代码1.class Array
2.def only_duplicates
3.    duplicates = []
4.    self.each {|each| duplicates << each if self.count(each) > 1}
5.    duplicates.uniq
6.end
7.end
Ruby代码1.puts .only_duplicates.inspect
2.==>
Ruby代码1.require 'benchmark'   
2.
3.module Enumerable
4.   def map_with_index
5.      index = -1
6.      (block_given? && self.class == Range || self.class == Array)?map { |x| index += 1; yield(x, index) }:self
7.   end
8.end
9.
10.
11.class Array
12.
13.   def find_dups
14.      inject(Hash.new(0)) { |h,e| h += 1; h }.select { |k,v| v > 1 }.collect { |x| x.first }
15.   end
16.
17.
18.
19.
20.   def find_dups2
21.      uniq.select{ |e| (self-).size < self.size - 1 }
22.   end
23.
24.   def find_ndups   # also returns the number of items
25.      uniq.map { |v| diff = (self.size - (self-).size); (diff > 1) ? : nil}.compact
26.   end
27.
28.
29.   # cf. http://www.ruby-forum.com/topic/122008
30.   def dups_indices   
31.      (0...self.size).to_a - self.uniq.map{ |x| index(x) }
32.   end
33.
34.   def dup_indices(obj)
35.      i = -1
36.      ret = map { |x| i += 1; x == obj ? i : nil }.compact
37.      #ret = map_with_index { |x,i| x == obj ? i : nil }.compact
38.      ret.shift
39.      ret
40.   end
41.
42.   def delete_dups(obj)
43.      indices = dup_indices(obj)
44.      return self if indices.empty?
45.      indices.reverse.each { |i| self.delete_at(i) }
46.      self
47.   end
48.
49.end   
50.
51.
52.array =
53.
54.dups = nil
55.
56.
57.Benchmark.bm(14) do |t|   
58.
59. t.report('find_dups:') do
60.    dups = array.find_dups
61. end   
62.
63.end   
64.
65.p dups   #=>
66.
67.
68.p %w(a b a c c d).dups_indices
69.p %w(a b a c c d).dup_indices('c')
70.p %w(a b a c c d).delete_dups('a')Ruby代码1.class Array
2.
3.def find_dups
4.    uniq.map {|v| (self - ).size < (self.size - 1) ? v : nil}.compact
5.end
6.
7.endRuby代码1.def mostused(ahash)
2.   original_size = ahash.size
3.   sizes = {}   
4.   ahash.uniq.map { |x| sizes = original_size - ((ahash - ).size)}
5.   sizes.sort_by {|k,v| v}.pop      
6. end

gr33n 发表于 2011-12-19 18:09

牛呀!!太有才了.
页: [1]
查看完整版本: ruby array中找出重复元素