Skip to content

Instantly share code, notes, and snippets.

@seaneshbaugh
Last active December 20, 2015 23:18
Show Gist options
  • Save seaneshbaugh/6211038 to your computer and use it in GitHub Desktop.
Save seaneshbaugh/6211038 to your computer and use it in GitHub Desktop.
"Overlap" of two arrays
require 'minitest/autorun'
class Array
def max_overlap(a)
clone = self.clone
a.each do |n|
if clone.index(n)
clone.delete_at(clone.index(n))
end
end
(a + clone).sort
end
def min_overlap(a)
self_uniq = self.uniq
a_uniq = a.uniq
r = []
self_uniq.each do |n|
count = [self.count(n), a.count(n)].min
if count == 0
count = [self.count(n), a.count(n)].max
end
count.times do
r << n
end
a_uniq.delete(n)
end
a_uniq.each do |n|
count = [self.count(n), a.count(n)].min
if count == 0
count = [self.count(n), a.count(n)].max
end
count.times do
r << n
end
end
r.sort
end
end
describe Array do
before do
@x = [2, 3, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8]
@y = [2, 2, 3, 8, 8, 11]
end
describe '#max_overlap' do
it 'should find the maximum overlap of two arrays' do
@x.max_overlap(@y).must_equal [2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8, 11]
end
it 'should be the same either way' do
@x.max_overlap(@y).must_equal @y.max_overlap(@x)
end
end
describe '#min_overlap' do
it 'should find the minimum overlap of two arrays' do
@x.min_overlap(@y).must_equal [2, 3, 4, 5, 5, 6, 6, 7, 8, 8, 11]
end
it 'should be the same either way' do
@x.min_overlap(@y).must_equal @y.min_overlap(@x)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment