Skip to content

Instantly share code, notes, and snippets.

@aiibe
Created December 29, 2019 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aiibe/91b8de9c9fde97cdb6298038826c2784 to your computer and use it in GitHub Desktop.
Save aiibe/91b8de9c9fde97cdb6298038826c2784 to your computer and use it in GitHub Desktop.
The Dollar Game (javascript)
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