Forum: Ruby Ruby finding double entries in arrays

Ca7f32f26eae605d4d16c46fc28ff750?d=identicon&s=25 Mi Gatt (migatt)
on 2017-03-13 15:59
How can I find double entries in arrays?

The Code:

list = [1,1,2,2,3,3,4,5]

def ungerade_zahlen( odd )
  number  = 0
  odd.each do |element|
    if element % 2 == 1
      number +=1
    end
  end
  puts number
  return number
end

ungerade_zahlen(list)

I don't want to find all odd entries, only the different entries.
For example: [1,2,1,5,7,9,5,4,3] -> I want to Count 5 entries
[1,3,5,7,9]!

I would be happy if someone can help me please!
B078cb4f4fb473c7a54d1fc36d10c70e?d=identicon&s=25 Regis d'Aubarede (raubarede)
on 2017-03-13 21:00
Mi Gatt wrote in post #1185679:
> How can I find double entries in arrays?

> I don't want to find all odd entries, only the different entries.
> For example: [1,2,1,5,7,9,5,4,3] -> I want to Count 5 entries
> [1,3,5,7,9]!
>
> I would be happy if someone can help me please!

Here , Hash is use as e Set :

def uz(l)
  l.each_with_object( {} ) { |e,h| h[e]=1 if e%2==1}.keys.sort
end

p uz [1,2,1,5,7,9,5,4,3]
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2017-03-14 07:00
With the variable 'list' set as in your posting, the expression

   list.uniq

returns an array of uniq elements in list.
B078cb4f4fb473c7a54d1fc36d10c70e?d=identicon&s=25 Regis d'Aubarede (raubarede)
on 2017-03-14 15:54
Ronald Fischer wrote in post #1185682:
> With the variable 'list' set as in your posting, the expression
>
>    list.uniq
>
> returns an array of uniq elements in list.

true,  so :

def uz(l)
  l.uniq.select {|a|a%2==1}.sort
end
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.