Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: StableMatching Algorithm #1446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Faareh-Ahmed wants to merge 1 commit into TheAlgorithms:master
base: master
Choose a base branch
Loading
from Faareh-Ahmed:Faareh-Ahmed-patch-1
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Backtracking/StableMatching.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// This is the Stable Matching Gale Shapley Algorithm
// Gale Shapley describes the method of Stable One to One matching

function initFreeMen() {
for (let man in preferredRankingMen) {
freeMen.push(man);
}
}

function stableMatch() {
while (freeMen.length > 0) {
for (let man of freeMen) {
startMatching(man);
}
}
}

function startMatching(man) {
for (let woman of preferredRankingMen[man]) {
const takenMatch = temporaryEngagement.find((couple) => woman === couple[1]);

if (!takenMatch) {
temporaryEngagement.push([man, woman]);
freeMen = freeMen.filter((m) => m !== man);
break;
} else {
const currentGuy = takenMatch[0];
const currentGuyIndex = preferredRankingWomen[woman].indexOf(currentGuy);
const potentialGuyIndex = preferredRankingWomen[woman].indexOf(man);

if (currentGuyIndex > potentialGuyIndex) {
freeMen = freeMen.filter((m) => m !== man);
freeMen.push(currentGuy);
takenMatch[0] = man;
break;
}
}
}
}

const preferredRankingMen = {
'Alice': ['Frank', 'Eva', 'Dave'],
'Bob': ['Frank', 'Dave', 'Eva'],
'Carol': ['Dave', 'Eva', 'Frank']
};

const preferredRankingWomen = {
'Dave': ['Carol', 'Alice', 'Bob'],
'Eva': ['Alice', 'Bob', 'Carol'],
'Frank': ['Carol', 'Alice', 'Bob']
};

// This will store all the paired men and women
// until the loop ends
// This array will store the current engagements in the format [man, woman]
const temporaryEngagement = [];

// This will store all the men who are yet
// to be paired and are still single
// Initially, all the men are considered free and added to this array.
let freeMen = [];

initFreeMen();
stableMatch();
console.log("Final Matching:", temporaryEngagement);

AltStyle によって変換されたページ (->オリジナル) /