Compare values of an array

2

I have an array and in this array I have some dates, and I need to print the dates that are repeated. In order to get this data I created a for the size of the array, and within that for I made another loop in case one is also to be able to compare the dates, and within that second I make the comparison if the dates are the same, and if I show.

But when I display there is a problem because all the rows in the array are displayed, and also if there is a repeated date it prints the date the number of times it repeats each time it finds it. I know it's confusing, I'll post the output.

The dates that are repeated are 1981-04-11 3x, 1954-03-04 2x, and where they were found, repeats as well.

Code output example

HERMES 1981-04-11
HERMES 1981-04-11
HERMES 1981-04-11
MARCIO 1954-03-04
MARCIO 1954-03-04
LILIAN 1970-04-19
KLEBER 1967-12-14
RAIMUNDO 1981-04-11
RAIMUNDO 1981-04-11
RAIMUNDO 1981-04-11
FRANCISCO 1924-03-28
RUI 0002-11-30
MARIA 1954-03-04
MARIA 1954-03-04
MANOEL 1968-03-24
JOANNA 1981-04-11
JOANNA 1981-04-11
JOANNA 1981-04-11

How is the code. csv is the name of the array:

for num in 0..9

    for num1 in 0..9
      dataAtual = csv[num][1]
      xatual = csv[num1][1]

      if dataAtual == xatual
        datas["nome"] = csv[num][0]
        datas["data"] = csv[num][1]
        puts datas["nome"] + " " +datas["data"]
      end
    end

  end
    
asked by anonymous 05.07.2015 / 08:28

3 answers

0
require 'set'

# transforma em um array de uma dimensão
csv_temp = csv.flatten

# pega apenas as posições que possuem a data
csv_temp = (1..csv_temp.size).step(2).map { |x| csv_temp[x] }

# cria uma coleçao do tipo Set, que não aceita valores repetidos
repeated_dates = Set.new

csv_temp.each do |date|
  # adiciona a data para a coleção de datas repetidas
  # se houver mais de uma no array
  repeated_dates.add(date) if csv_temp.count(date) > 1
end

repeated_dates.each { |date| puts date }                           
    
16.10.2016 / 19:16
1

I do not know if I understood your problem correctly but take a look at this link That answering a problem similar to the more elegant would be

ary = ["A", "B", "C", "B", "A"]
ary.select{ |e| ary.count(e) > 1 }.uniq
    
04.01.2016 / 22:16
0

I did not realize the output you want, but I think the problem is that the code compares the date of each objective with the date of the same object. That is, the date of [LILIAN, 1970-04-19] will be compared to the date of [LILIAN, 1970-04-19], will soon print LILIAN 1970-04-19.

Again, I do not know what output you want, but maybe this will solve:

for num in 0..9

  for num1 in 0..9
    **next if num1 == num**
    dataAtual = csv[num][1]
    xatual = csv[num1][1]

    if dataAtual == xatual
      datas["nome"] = csv[num][0]
      datas["data"] = csv[num][1]
      puts datas["nome"] + " " +datas["data"]
    end
  end

end
    
05.07.2015 / 18:47