# This program is suppose to find all duplicates number of array ‘a’

below . For example in array ‘a’ below , the output should show only
[2,2] and [3,3,3] because there are two number 2 and there are three
number 3 in array ‘a’. The problem is my program show [1], [45], [6] and
[1],[45],[6] should not be in the output.

a=[1,2,3,45,2,3,6,3]

n = a.length
u = n - 1
new_array = []
0…u.times do |number|
xo = []
new_array << xo
x = number + 1
x…n.times do |num|

``````if (a[number] == a[num])
xo << a[number]

end
``````

end

end

p new_array

#This second part is to eliminate the repeating array containing the
duplicate number. I failed at this too.

pp = new_array.length
ppp = pp - 1
0…ppp.times do |number|
y = number + 1
y…pp.times do |num|
u7 = new_array[number]
u8 = new_array[num]
if u7 == u8
new_array.delete_at(num)
end
end
end

p new_array

Take a look at this:

a = [1,2,3,45,2,3,6,3]

counts = Hash.new(0)
#If a non-existent key is looked up in the hash,
#the key is created and assigned the value 0,
#then 0 is returned.

a.each do |num|
counts[num] += 1
end

p counts #=>{1=>1, 2=>2, 3=>3, 45=>1, 6=>1}

p [3] * 2 #=>[3, 3]

results = []

counts.each do |num, count|
results << ([num] * count if count > 1
end

p results #=>[[2, 2], [3, 3, 3]]

Note that the above code only traverses the array once to gather all
the duplicates.

reject numbers where scan that number surrounded by “[”, “space”, “,” or
“]” count is less than 2 and then remove duplicates

a = [1, 2, 3, 45, 2, 3, 6, 3]
a.reject! { |n| a.to_s.scan(/[\s[]#{n}[,]]/).count < 2 }.uniq!
p a
=> [2, 3]

a = [1, 2, 3, 45, 2, 3, 6, 3]
a.uniq!
p a
=> [1, 45, 2, 6, 3]

my solution:

a = [1, 2, 3, 45, 2, 3, 6, 3]

hash = Hash.new { |h, k| h[k] = 0 }

a.each { |x| hash[x] += 1 }

selected_keys = hash.keys.select { |k| h[k] > 1 }

selected_keys.map do |key|
Array.new hash[key], key
end

here my solution without using hash at all

==================================
string = [1,2,3,2,3,4,2,1]

arraya = []
arraya << string[0]

i = 1
while i <= string.length
if arraya[0] == string[i]
arraya << string[i]

else
arraya = []
arraya << string[i]
end
i += 1
end

puts

i=0
while i < arrayAnswer.size - 1
j=i+1
end
j+=1
end
i+=1
end

THANK everyone for the support and answer. really love it. by the way, i
love ruby and programming!!!

anyone into car tuning and turbo? lol

string = [1,2,3,1,2,1,3,4,2,1,3]

i=0
array=[]
while i < string.size - 1
j=i+1
count = 1
while j < string.size
if string[i] == string[j]
count = count + 1
string[j]= nil
end
j+=1
end
array<<[string[i], count]
i+=1
end
p array

i=0
arraya=[]
while i < array.size
if array[i][0] != nil
arraya << array[i]
end
i+=1
end
p arraya

#comment: this is the best version. i actually understand array, string,
#and hash really well now. lol