0
a1 = [1, 2, 2, 1, 4]
a2 = [1, 2, 3]

Expected output:

[1, 2, 2, 1]

These are the four elements in a1 that are in a2.

a1 & a2 gives me only uniq elements [1, 2] but i need non-uniq elements.

Is there a better way than doing the following, which i think is not efficient:

a1.select{|ele| a2.include?(ele)}
0

3 Answers 3

4
a1 - (a1 - a2)
# => [1, 2, 2, 1]
Sign up to request clarification or add additional context in comments.

Comments

1

I would add my ¢2. If you are likely to make an operation a few times on huge arrays, @sawa’s method is definitely your choice:

require 'benchmark'

n = 1_000
a1 = 1_000.times.map { rand(1..100) }
a2 = 1_000.times.map { rand(5..95) }
Benchmark.bm do |x|
  x.report {
    n.times do
      a1 - (a1 - a2) 
    end
  }
  x.report {
    n.times do
      a1.keep_if { |xx| a2.include? xx }
    end
  }
end

results in:

#     user     system      total        real
# 0.340000   0.000000   0.340000 (  0.424604)
# 5.590000   0.010000   5.600000 (  6.438095)

But if there are lots of subtractions on small arrays:

- n = 1_000
- a1 = 1_000.times.map { rand(1..100) }
- a2 = 1_000.times.map { rand(5..95) }
+ n = 100_000
+ a1 = 10.times.map { rand(1..100) }
+ a2 = 10.times.map { rand(5..95) }

the opposite looks more appropriate:

#     user     system      total        real
# 0.550000   0.010000   0.560000 (  0.551997)
# 0.150000   0.000000   0.150000 (  0.151695)

Comments

0

This is an option

a1.keep_if { |x| a2.include? x }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.