- 论坛徽章:
- 0
|
ruby array中找出重复元素
Ruby代码- 1.#上文的inject现在用上了
- 2.module Enumerable
- 3. def dups
- 4. inject({}) {|h,v| h[v]=h[v].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[v] += 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 [1,2,2,4,5,1].only_duplicates.inspect
- 2.==> [1, 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[e] += 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-[e]).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-[v]).size); (diff > 1) ? [v, diff] : 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 = [1,3,5,5,6,7,9,10,14,18,22,22,4,4,4,3,6]
- 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 #=> [5, 22, 6, 3, 4]
- 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 - [v]).size < (self.size - 1) ? v : nil}.compact
- 5. end
- 6.
- 7.end
复制代码 Ruby代码- 1.def mostused(ahash)
- 2. original_size = ahash.size
- 3. sizes = {}
- 4. ahash.uniq.map { |x| sizes[x] = original_size - ((ahash - [x]).size)}
- 5. sizes.sort_by {|k,v| v}.pop
- 6. end
复制代码 |
|