Skip to content

Gale-Shapley implementation in Rust #715

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ This file lists everyone, who contributed to this repo and wanted to show up her
- Akash Dhiman
- Vincent Zalzal
- Jonathan D B Van Schenck
- Ishaan Verma
136 changes: 136 additions & 0 deletions contents/stable_marriage_problem/code/rust/stable_marriage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#[derive(Eq, PartialEq, PartialOrd)]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All these are not needed.

struct Person {
name: char, // a single character denoting the person e.g 'A', 'B', 'F'
index: usize, // index in men/women vecotr
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is typo here. It should be vector.

preference: Vec<usize>,
pref_index: usize,
candidates: Vec<usize>, // all those men/women who have proposed to self
partner: Option<usize>
}

impl Person {
fn propose_to_next(&mut self, women: &mut Vec<Person>) {
/* propose to next most preferred person */
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would use // for normal comments and /// for doc strings.


if self.pref_index >= self.preference.len() {
()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use return here as it is way cleaner than ().

}

let person = self.preference[self.pref_index];
// add self to the preferred woman's candidates
women[person].candidates.push(self.index);

self.pref_index += 1;

}

fn pick_preferred(&mut self, men: &mut Vec<Person>) {
/* pick the highest preferred man among candidates */

for person in &self.preference {
if Some(*person) == self.partner {
break
} else if self.candidates.contains(&person) {
match self.partner {
Some(ind) => {
// If self currently has a partner, set self's partner's partner to None
men[ind].partner = None;
},
None => {
self.partner = Some(*person);
men[*person].partner = Some(self.index);
}
}
break
}
}
}

}

fn init_person(name: char, index: usize, pref: Vec<usize>) -> Person {
let person = Person {
name: name,
index: index,
preference: pref,
pref_index: 0,
candidates: Vec::new(),
partner: None
};
person
}

fn main() {
let mut men = vec![
init_person('A', 0, vec![1, 0, 3, 2]),
init_person('B', 1, vec![3, 0, 2, 1]),
init_person('C', 2, vec![2, 3, 1, 0]),
init_person('D', 3, vec![1, 2, 0, 3])
];

let mut women = vec![
init_person('E', 0, vec![3, 2, 0, 1]),
init_person('F', 1, vec![0, 2, 1, 3]),
init_person('G', 2, vec![0, 1, 2, 3]),
init_person('H', 3, vec![2, 0, 1, 3])
];

println!("Men: ");
for man in &men {
println!("\t{}, preference = {:?}", man.name, {
let mut vect: Vec<char> = Vec::new();
for man in &man.preference {
vect.push(women[*man].name);
}
vect
});
}

println!("Women: ");
for woman in &women {
println!("\t{}, preference = {:?}", woman.name, {
let mut vect: Vec<char> = Vec::new();
for woman in &woman.preference {
vect.push(men[*woman].name);
}
vect
});
}


/* Resolve */
let mut cont = true;
while cont {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use a named break here:

    ...
    'resolve: loop {
        ...
        for man in &men {
            if man.partner.is_none() {
                break 'resolve;
            }
        }
    }
    ...

// Each man proposes to his highest preference
for man in &mut men {
if man.partner.is_none() {
man.propose_to_next(&mut women);
}
}

// Each woman picks here highest preference
for woman in &mut women {
woman.pick_preferred(&mut men);
}

// If there is a single man who does not have a partner, continue resolving
cont = false;
for man in &men {
if man.partner.is_none() {
cont = true;
break;
}
}
}

println!("\nStable Matching: ");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only personal preference but i would rather write

print!("\n");
print!("Stable Matching: \n");

than println!("\nStable Matching: ");

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think rust recommends to use just a println!() invocation without parameters. I think clippy even has a lint for that.

so:

println!();
println!("Stable Matching: ");

for man in &men {
match man.partner {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can do a simple unwrap here as all man must have a partner at this point.

Some(p) => {
println!("\t{} + {}", man.name, women[p].name);
},
None => ()
}
}

}
2 changes: 2 additions & 0 deletions contents/stable_marriage_problem/stable_marriage_problem.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ Here is a video describing the stable marriage problem:
[import, lang:"php"](code/php/stable_marriage.php)
{% sample lang="scala" %}
[import, lang:"scala"](code/scala/stable_marriage.scala)
{% sample lang="rust" %}
[import, lang:"rust"](code/rust/stable_marriage.rs)
{% endmethod %}

<script>
Expand Down