Created
August 31, 2018 05:37
-
-
Save jimnist/209d2f13f58640ad37d15e9a47181e6e to your computer and use it in GitHub Desktop.
subset coding exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
source 'https://rubygems.org' | |
gem 'rspec' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# do all the needles exist in the haystack? | |
# allowing for multiple instances of elements in the needles where needles | |
# and haystacks are arrays of comparable objects | |
def subset?(needles, haystack) | |
return false unless needles.length > 0 && haystack.length > 0 | |
haystacks = counter(haystack) | |
counter(needles).each_pair do |key, value| | |
return false unless haystacks.key?(key) && haystacks[key] >= value | |
end | |
true | |
end | |
# returns a hash with the original array elements as keys and the count of | |
# those elements in the array as values | |
def counter(elements) | |
counts = {} | |
elements.each do |e| | |
counts[e] = counts.include?(e) ? counts[e] + 1 : 1 | |
end | |
counts | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require_relative '../subset' | |
describe 'subset?' do | |
let(:a) { ['l','m','n','o'] } | |
let(:b) { ['n','o'] } | |
let(:c) { [] } | |
let(:d) { ['a','b','b','z'] } | |
let(:e) { ['a','b','b','z','z'] } | |
context 'there are more elements in needles than haystack' do | |
subject { subset?(a,b) } | |
it { is_expected.to be false } | |
end | |
context 'needles is an empty collection' do | |
subject { subset?(c,b) } | |
it { is_expected.to be false } | |
end | |
context 'haystack is an empty collection' do | |
subject { subset?(a,c) } | |
it { is_expected.to be false } | |
end | |
context 'needles are not in haystack' do | |
subject { subset?(a,c) } | |
it { is_expected.to be false } | |
end | |
context 'needles are in haystack' do | |
subject { subset?(b,a) } | |
it { is_expected.to be true } | |
end | |
context 'needles are in haystack, with multiple instances of some needles' do | |
subject { subset?(d,e) } | |
it { is_expected.to be true } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment