Skip to content

Instantly share code, notes, and snippets.

@atainton
Last active November 21, 2022 12:12
Show Gist options
  • Save atainton/3013ffac95b51cf474a5a748a5eb8fda to your computer and use it in GitHub Desktop.
Save atainton/3013ffac95b51cf474a5a748a5eb8fda to your computer and use it in GitHub Desktop.
SimplePay Bidding class
class Agent
# This will already be implemented and is not part of this exercise
def initialize; end
# This will return the amount (integer) by which the agent wants to increase its bid
# (i.e. how much they want to add onto their bid as it stands so far)
# This will already be implemented and is not part of this exercise
def get_bid_increase; end
end
class Bidding
attr_accessor :queue, :highest_bid
def initialize(agents)
@agents = agents
@queue = agents.map { |agent| {
agent: agent,
current_bid: nil
}
}
@highest_bid = 0
end
def run
if queue.empty?
raise Exception.new "There are not agents who ware part of this bid"
end
while open_bids?
agent_obj = queue[0]
process_agent_bid(agent_obj)
end
end
# there will be no open bid if the average of all bids are equal to the highest bid
def open_bids?
queue.inject(0){ |sum, agt|
value = agt[:current_bid].nil? ? -1 : agt[:current_bid]
sum + value
}.to_f / queue.size != highest_bid
end
private
def process_agent_bid(agent_obj)
if agent_obj[:current_bid].nil? || agent_obj[:current_bid] <= highest_bid
bid = agent_obj[:agent].get_bid_increase()
if bid < highest_bid
withdraw_agent_from_queue(agent_obj)
else
if bid > highest_bid
highest_bid = bid
end
move_agent_in_queue(agent_obj)
end
end
end
# remove agent from queue, they will not be able to participate once removed
def withdraw_agent_from_queue(agent)
queue.delete(agent)
end
# move agent to the back of the queue once bid has been accepted
def move_agent_in_queue(agent)
queue.delete(agent)
queue << agent
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment