Skip to content

Instantly share code, notes, and snippets.

@phillipoertel
Last active January 2, 2016 19:29
Show Gist options
  • Save phillipoertel/8350277 to your computer and use it in GitHub Desktop.
Save phillipoertel/8350277 to your computer and use it in GitHub Desktop.
Reduce a hash with arrays as values to a maximum number of array entries.
#
# run like this:
#
# > git clone https://gist.github.com/8350277.git reducer
# > cd reducer
# > gem install rspec -v 2.14.1
# > rspec reducer.rb
#
require "rspec"
class Reducer
# Given a +hash+ of the form {user1: [1], user2: [2, 3]}, reduce the sum of all array entries
# to +limit+, reducing the largest array first. Example: if limit is 2, the above hash
# will be reduced to {user1: [1], user2: [2]}, since the sum of all array entries is 2.
#
def self.reduce_to_max_items(hash, limit)
while(hash.values.flatten.size > limit)
# find the hash key which holds the most values. example:
# if hash = {user1: [1], user2: [2, 3]}, then key is :user2, since it's array has the most items of all keys (2)
key_with_most_values = hash.max { |(k1, v1), (k2, v2)| v1.size <=> v2.size }.first
# remove the first value of that hash entry
hash[key_with_most_values].shift
end
hash.reject { |k, v| v.empty? }
end
end
describe "Reducer#reduce_to_max_items" do
def reduce(hash, limit)
Reducer.reduce_to_max_items(hash, limit)
end
context "Less or equal than 6 entries" do
it "doesn't change anything when the entries belong to 1 user" do
hash = { user1: [1,2,3,4,5,6] }
reduce(hash, 6).should == hash
end
it "doesn't change anything when the entries belong to 2 users" do
hash = { user1: [1,2,3], user2: [4,5,6] }
reduce(hash, 6).should == hash
end
end
context "More than 6 entries" do
it "reduces to 6 when the entries belong to 1 user" do
hash = { user1: [1,2,3,4,5,6,7] }
reduce(hash, 6).should == { user1: [2,3,4,5,6,7] }
end
it "reduces to 6 when the entries belong to 2 users" do
hash = { user1: [1,2,3], user2: [4,5,6,7] }
reduce(hash, 6).should == { user1: [1,2,3], user2: [5,6,7] }
end
it "removes keys which would have empty arrays" do
hash = { user1: [1], user2: [2], user3: [3] }
reduce(hash, 2).should == { user2: [2], user3: [3] }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment