Created
December 29, 2019 10:48
Star
You must be signed in to star a gist
The Dollar Game (javascript)
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
function giveAndTake(humans, relations){ | |
let moves = [] | |
function inDebt(){ | |
return Object.keys(humans).filter( person => humans[person] < 0 ).length > 0 | |
} | |
while( inDebt() ){ | |
// Find the poorest person among all | |
let minAmount = Math.min(...Object.keys(humans).map( wallet => humans[wallet])) | |
let targetName = Object.keys(humans).find( wallet => humans[wallet] === minAmount ) | |
// Find his/her friends | |
let targetFriends = [] | |
relations.forEach( link => { | |
if(link.indexOf(targetName) !== -1){ | |
targetFriends = [...targetFriends, ...link.filter( name => name !== targetName)] | |
} | |
}) | |
// Take $1 from each of his/her friends | |
targetFriends.forEach( name => { | |
humans[name] -= 1 | |
humans[targetName] += 1 | |
}) | |
// Commit every move | |
moves.push([targetName, 1]) | |
// > Bonus: Uncomment the following lines to see | |
// > who and how many times they should take from their friends | |
// > Note: Also comment out line 29 | |
// | |
// let targetIndex = moves.findIndex( move => move[0] === targetName ) | |
// if(targetIndex === -1){ | |
// moves.push([targetName, 1]) | |
// } else { | |
// ++moves[targetIndex][1] | |
// } | |
} | |
console.log(moves) | |
return moves | |
} | |
const test1 = { | |
people: { | |
Adam: 0, | |
Bob: 2, | |
Carol: -2, | |
Donna: 3, | |
Eddie: -2 | |
}, | |
friendships: [ | |
['Adam', 'Donna'], | |
['Adam', 'Carol'], | |
['Bob', 'Carol'], | |
['Carol', 'Eddie'], | |
['Donna', 'Eddie'] | |
] | |
} | |
const test2 = { | |
people: { | |
Adam: 1, | |
Bob: -1, | |
Carol: -2, | |
Donna: 2, | |
Eddie: 3 | |
}, | |
friendships: [ | |
['Adam', 'Eddie'], | |
['Adam', 'Carol'], | |
['Bob', 'Carol'], | |
['Carol', 'Eddie'], | |
['Donna', 'Eddie'] | |
] | |
} | |
const test3 = { | |
people: { | |
Adam: -4, | |
Bob: 1, | |
Carol: 2, | |
Donna: 2, | |
Eddie: 0 | |
}, | |
friendships: [ | |
['Adam', 'Donna'], | |
['Adam', 'Carol'], | |
['Bob', 'Carol'], | |
['Carol', 'Eddie'], | |
['Donna', 'Eddie'] | |
] | |
} | |
giveAndTake(test3.people, test3.friendships) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment