Let's say you have a hashmap of sub-systems that a spaceship is currently directing power to and a second hash of sub-systems where the power should now be directed to.
Create a function that returns a hash of where the spaceship should move the power from and where it should go so that the power can be taken from the current values to the desired ones.
Example:
Current: {engines:500, cannons:150, communications:250, life_support:200, guidance:200}
Desired: {engines:450, entertainment:400, guidance:200, life_support:250}
This should produce:
{
engines: {entertainment: 50},
cannons: {entertainment: 150},
communications: {entertainment: 200, life_support: 50}
}
Assumptions: The sum of the values of the current and the desired hashes is the same.
This is the code I wrote that completes the task:
current = {engines:500, cannons:150, communications:250, life_support:200, guidance:200}
desired = {engines:450, entertainment:400, guidance:200, life_support:250}
def direct_power(current, desired)
additions = {}
subtractions = {}
current.each do |ticker, value|
movement = (desired[ticker].nil? ? 0 : desired[ticker]) - value
movement < 0 ? subtractions[ticker] = movement : additions[ticker] = movement
end
desired.each do |desired_ticker, desired_value|
additions[desired_ticker] = desired_value if current[desired_ticker].nil?
end
additions = Hash[additions.sort_by{|k, v| v}.reverse]
subtractions = Hash[subtractions.sort_by{|k, v| v}.reverse]
transactions = {}
subtractions.each do |ticker, value|
additions.each do |add_ticker, add_value|
next if add_value.zero? || value.zero?
transactions[ticker] = {} if transactions[ticker].nil?
if value.abs() < additions[add_ticker]
transactions[ticker][add_ticker] = value.abs()
additions[add_ticker] = additions[add_ticker] + value
value = 0
elsif value.abs() == additions[add_ticker]
transactions[ticker][add_ticker] = additions[add_ticker]
additions[add_ticker] = 0
value = 0
else
transactions[ticker][add_ticker] = additions[add_ticker]
value = additions[add_ticker] + value
additions[add_ticker] = 0
end
end
end
end
direct_power(current, desired)
I think this is currently running N squared, Do you think this be improved in terms of performance, readability and storage, if so how?