使用嵌套的每个循环在数组中查找重复出现的元素

时间:2016-03-26 21:48:49

标签: ruby each

我初始化一个具有重复元素的数组,然后我尝试通过嵌套的每个循环找到那个元素。

array=(1..100).to_a
array.insert(5, 100)

array.each do |x|
  m = x
  array.delete(x)
  array.each do |y|
    if m == y
      puts m
    end
  end
end

任何人都知道为什么这不起作用?

3 个答案:

答案 0 :(得分:1)

问题是由迭代该数组时修改数组(# -*- coding: utf-8 -*- from math import * import numpy as np from matplotlib import pyplot as plt from matplotlib import animation def Plongeon(): h = input("height = ") h = float(h) m = input(" mass = ") m = float(m) global g g = 9.8 g = float(g) global Tc #calculate air time, Tc Tc = sqrt(2*h/g) Tc = round(Tc,2) print Tc # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(-2, h+1)) #ymax : initial height+1 line, = ax.plot([], [], ' o', lw=2) Tc = int(Tc+1) #make Tc an integer to be used later in def get_y() xs = [1] # the vertical position is fixed on x-axis ys = [h, h] # initialization function: plot the background of each frame def init(): line.set_data([], []) return line, # animation function. This is called sequentially def animate(y): ys[-1] = y line.set_data(xs, ys) return line, def get_y(): for step in range(Tc): t = step / 100.0 y = -0.5*g*t**2 + h # the equation of diver's displacement on y axis yield y # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100) plt.show() Plongeon() )引起的。

在第一次迭代中,迭代器"指向"到数组中的第一个元素。由于删除了第一个元素,因此第二个元素成为第一个元素。在下一次迭代中,迭代器指向数组中的第二个元素 - 第一个迭代中的第三个元素。您跳过第一次迭代中第二个元素并移到前面。

如您所见,您不会检查每个元素而只检查每一个元素。

首先对数组进行排序可能会更有效,然后只检查每个连续元素是否相等:

delete

答案 1 :(得分:0)

Array#delete删除数组中的所有相同对象,而不仅仅是第一个。

ar = [1,2,1]
ar.delete(1)
p ar  #=> [2]

答案 2 :(得分:0)

这是查找第一个重复元素的有效方法。

require 'set'
s = Set.new
[1,3,2,5,3,4,7].find { |e| !s.add?(e) }
  #=> 3

方法Set#add?尝试将其参数添加到集合中。如果成功,则返回参数; else(该集合已包含其参数)返回nil。由于集合是隐藏的哈希,查找非常快。