Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active December 14, 2015 21:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeffreyiacono/5148712 to your computer and use it in GitHub Desktop.
Foreman divides up units of work evenly amongst workers
class Foreman
attr_accessor :units_of_work, :workers_count
def initialize attrs = {}
@units_of_work = attrs[:units_of_work]
@workers_count = attrs[:workers_count]
end
def fair_shares
even_shares = Array.new(@workers_count) { @units_of_work / @workers_count }
if (remainder = (@units_of_work - even_shares.reduce(:+))) != 0
0.upto(remainder - 1).each { |i| even_shares[i] += 1 }
end
even_shares
end
end
describe Foreman do
describe "#fair_shares" do
context "when dealing with evenly splittable amounts of work / worker" do
let(:units_of_work) { 10 }
let(:workers_count) { 2 }
let(:foreman) { described_class.new units_of_work: units_of_work, workers_count: workers_count }
it "returns an array of evenly split work units" do
foreman.fair_shares.should == [5, 5]
end
it "returns an array of work shares that sum to the total amount required" do
foreman.fair_shares.reduce(:+).should == units_of_work
end
end
context "when dealing with non-evenly splittable amounts of work / worker" do
let(:units_of_work) { 11 }
let(:workers_count) { 2 }
let(:foreman) { described_class.new units_of_work: units_of_work, workers_count: workers_count }
it "returns an array of evenly split work units, filling in the differences as evenly as possible" do
foreman.fair_shares.should == [6, 5]
end
it "returns an array of work shares that sum to the total amount required" do
foreman.fair_shares.reduce(:+).should == units_of_work
end
end
context "when dealing with an even more complete, non-evenly splittable amounts of work / worker" do
let(:units_of_work) { 19 }
let(:workers_count) { 7 }
let(:foreman) { described_class.new units_of_work: units_of_work, workers_count: workers_count }
it "returns an array of evenly split work units, filling in the differences as evenly as possible" do
foreman.fair_shares.should == [3, 3, 3, 3, 3, 2, 2]
end
it "returns an array of work shares that sum to the total amount required" do
foreman.fair_shares.reduce(:+).should == units_of_work
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment