项目作者: alextanhongpin

项目描述 :
Solving the Stable Marriage/Matching Problem with the Gale–Shapley algorithm
高级语言: Jupyter Notebook
项目地址: git://github.com/alextanhongpin/stable-marriage-problem.git
创建时间: 2018-01-24T15:51:59Z
项目社区:https://github.com/alextanhongpin/stable-marriage-problem

开源协议:

下载


Stable Marriage/Matching Problem

Reference to wiki link here.

Algorithm

Pseudocode:

  1. function stableMatching {
  2. Initialize all m M and w W to free
  3. while free man m who still has a woman w to propose to {
  4. w = first woman on ms list to whom m has not yet proposed
  5. if w is free
  6. (m, w) become engaged
  7. else some pair (m', w) already exists
  8. if w prefers m to m'
  9. m' becomes free
  10. (m, w) become engaged
  11. else
  12. (m', w) remain engaged
  13. }
  14. }

Implementation in JavaScript:

  1. // Solution 1: "{"Y":"A","A":"Y","Z":"B","B":"Z","X":"C","C":"X"}"
  2. // const menPreferences = {
  3. // A: 'YXZ',
  4. // B: 'ZYX',
  5. // C: 'XZY'
  6. // }
  7. // const womenPreferences = {
  8. // X: 'BAC',
  9. // Y: 'CBA',
  10. // Z: 'ACB'
  11. // }
  12. // Solution 2: "{"0":"7","1":"5","2":"4","3":"6","4":"2","5":"1","6":"3","7":"0"}"
  13. const engaged = {}
  14. // const menPreferences = {
  15. // 0: '7564',
  16. // 1: '5467',
  17. // 2: '4567',
  18. // 3: '4567'
  19. // }
  20. // const womenPreferences = {
  21. // 4: '0123',
  22. // 5: '0123',
  23. // 6: '0123',
  24. // 7: '0123'
  25. // }
  26. // Solution 3: "{"X":"A","A":"X","Y":"B","B":"Y","Z":"C","C":"Z"}"
  27. const menPreferences = {
  28. A: 'XYZ',
  29. B: 'YXZ',
  30. C: 'XYZ'
  31. }
  32. const womenPreferences = {
  33. X: 'BAC',
  34. Y: 'ABC',
  35. Z: 'ABC'
  36. }
  37. const bachelors = Object.entries(menPreferences)
  38. .map(([man, preferences]) => [man, preferences.split('')])
  39. while (bachelors.length) {
  40. const [man, preferences] = bachelors.shift()
  41. const woman = preferences.shift()
  42. if (!engaged[woman]) {
  43. engaged[woman] = man
  44. engaged[man] = woman
  45. } else {
  46. const currentMan = engaged[woman]
  47. const womanPreferences = womenPreferences[woman]
  48. // Smaller index value is more preferable.
  49. if (womanPreferences.indexOf(man) < womanPreferences.indexOf(currentMan)) {
  50. engaged[woman] = man
  51. engaged[man] = woman
  52. delete engaged[currentMan]
  53. } else {
  54. // Reject.
  55. console.log('man is rejected', man)
  56. bachelors.unshift([man, preferences])
  57. }
  58. }
  59. }
  60. console.log(engaged)