Arrays 如何在不使用“uniq”方法的情况下查找数组中的重复项
我正在做一个挑战,创建一个在数组中查找重复值的方法,并打印出一个没有重复值的新数组。Ruby有一个内置的Arrays 如何在不使用“uniq”方法的情况下查找数组中的重复项,arrays,ruby,Arrays,Ruby,我正在做一个挑战,创建一个在数组中查找重复值的方法,并打印出一个没有重复值的新数组。Ruby有一个内置的uniq方法;但是,我不允许使用它 在我看来,这应该是可行的: def uniques(array) tempPos = 0 arrayPos = 0 duplicate = true result = [] # array the result will be "pushed" too for arrayPos in 0..array.length for te
uniq
方法;但是,我不允许使用它
在我看来,这应该是可行的:
def uniques(array)
tempPos = 0
arrayPos = 0
duplicate = true
result = [] # array the result will be "pushed" too
for arrayPos in 0..array.length
for tempPos in 0..array.length
# If the values at the indexes are the same. But the indexes are not the same.
# we have a duplicate
if array[arrayPos] == array[tempPos] && arrayPos != tempPos
duplicate = true
else
duplicate = false
end
if duplicate == false
result[arrayPos] = array[arrayPos]
end
end
puts duplicate
end
puts result.inspect
end
输出:
uniq *this is the short hand user input to run the method*
false
false
false
false
false
false
[1, 2, 1, 4, 5, nil]
我一定是做错了什么。你可以使用
集合吗
require 'set'
array = [1, 2, 3, 3, 3, 4]
Set.new(array).to_a
#=> [1, 2, 3, 4]
另一种方法是迭代数组中的每一对:
array.each_cons(2).with_object([array.first]) do |pair, result|
result << pair.last unless pair.first == pair.last
end
#=> [1, 2, 3, 4]
array.each_cons(2).带有_对象([array.first])的do|pair,result|
结果[1,2,3,4]
您的逻辑运行良好,尽管如上所述,集合将运行得更好。您还可以对元素进行排序,然后找到与集
不起作用的相同值的相邻对,但运行时会比当前解决方案稍好一些:
要完善您当前拥有的内容,请执行以下操作:
def uniques(array)
result = [] # array the result will be "pushed" too
for arrayPos in 0...array.length
duplicate = false
for tempPos in 0...result.length
# if the values at the indexes are the same... but the indexes are not the same...
# we have a duplicate
duplicate ||= (array[arrayPos] == result[tempPos])
end
if !duplicate
result << array[arrayPos]
end
end
puts result
end
def uniques(数组)
结果=[]#数组结果也将被“推送”
对于0…array.length中的arrayPos
重复=错误
对于0…result.length中的tempPos
#如果索引处的值相同。。。但是索引不一样。。。
#我们有一个副本
重复| |=(数组[arrayPos]==结果[tempPos])
结束
如果!复制品
结果。还有一个。假设:
arr = [3,5,1,3,4,1,1]
构造:
h = arr.group_by(&:itself)
#=> {3=>[3, 3], 5=>[5], 1=>[1, 1, 1], 4=>[4]}
副本如下所示:
h.select { |_,v| v.size > 1 }.keys
#=> [3, 1]
h.keys
#=> [3, 5, 1, 4]
无重复项的数组由下式给出:
h.select { |_,v| v.size > 1 }.keys
#=> [3, 1]
h.keys
#=> [3, 5, 1, 4]
实现这一点的一个相当简单的方法是利用array.include
new = []
arr.each { |x| new << x unless new.include?(x)}
puts new
new=[]
arr.each{| x | new复制数组简易方法
arr1 = [1,3,4,5,6,6,6,1]
arry = Array.new(arr1)
puts arry
使用OR运算符轻松查找uniq阵列
arr1 = [1,3,4,5,6,6,6,1]
arr2 = Array.new # creating new array
arry = arr1 | arr2 # compare two array using OR operator
puts arry
挑战并没有说我不能使用“set”……但他们希望在不使用有助于解决问题的内置方法的情况下对其进行编程。”……不使用有助于解决问题的内置方法”在我看来,这似乎是一个矛盾的说法。你肯定要使用内置的方法,但如果你找到一个有用的方法,我想你就不能使用它了。:-)我测试了你的代码,但它不起作用?我确实看到了如何使它更简洁。我也知道这不是一个实现功能的好方法-只是练习而已:)数组不一定是可排序。完全是我的大脑放屁。使用你的风格更新了代码。好吧,你的新代码可以工作…我的一个问题;为什么我当前的代码不能工作?这很可能与你如何错误地将结果添加到数组有关。尝试做结果作为一个想法:排序依据(&:object\u id)
然后将每个值与前一个值进行比较以消除重复?