Comparing values from an array

Asked

Viewed 1,157 times

2

I have an array and in this array I have some dates, and I need to print out the dates that are repeated. To obtain this data I created one that goes from the size of the array, and inside this one I made another loop in case one is also to be able to compare the dates, and inside that second is I make the comparison if the dates are equal, and if it is I display.

However when I display there is a problem, because all rows of the array are displayed, and also if there is any repeated date it prints the date the amount of times it repeats for each time it finds. I know you’re confused, I’ll post the exit.

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

Example of code output

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

3 answers

1

I don’t know if I understand your problem correctly but take a look at this one link That answers a problem similar to more elegant would be

ary = ["A", "B", "C", "B", "A"]
ary.select{ |e| ary.count(e) > 1 }.uniq

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 }                           

0

I don’t understand the output you want, but I think the problem is the fact that the code compares the date of each objective to 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], soon will print LILIAN 1970-04-19.

Again, I don’t know what output you want, but maybe this will fix it:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.