Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by danie on 3/4/2017.
- */
- import java.io.*;
- import java.util.*;
- public class StableMarriage {
- public static void main(String args[]) throws FileNotFoundException{
- File f = new File("C:\\Users\\danie\\Downloads\\Marriage.txt");
- Scanner s = new Scanner(f);
- ArrayList<ArrayList<Integer>> men = new ArrayList<>();
- ArrayList<ArrayList<Integer>> women = new ArrayList<>();
- TreeMap<Integer,Integer> matches = new TreeMap<>();
- int count = 0;
- while(s.hasNextLine()) {
- String line = s.nextLine();
- Scanner sl = new Scanner(line);
- ArrayList<Integer> person = new ArrayList<>();
- for (int i = 0; i < 2; i++) if (sl.hasNext()) sl.next();
- while (sl.hasNext()) {
- person.add(Integer.parseInt(sl.next()) - 1);
- }
- if (line.toLowerCase().startsWith("man")) {
- men.add(person);
- matches.put(count, -1);
- count++;
- }
- if (line.toLowerCase().startsWith("woman")) {
- women.add(person);
- }
- }
- System.out.println("Input (person = value+1, example: 3,1,2,0 = 4,2,3,1):");
- System.out.println(men.toString());
- System.out.println(women.toString());
- while(matches.containsValue(-1)){
- int guy = 0;
- for(int i = 0; i<men.size();i++){
- if(matches.get(i)==-1) {
- guy = i;
- i = men.size() + 1;
- }
- }
- int w = men.get(guy).get(0);
- for(int i = 0;i<men.size();i++){
- if(matches.get(i)==w)matches.put(i,-1);
- }
- matches.put(guy,w);
- for (int i = women.get(w).indexOf(new Integer(guy)) + 1; i < women.get(w).size(); i++) {
- int other = women.get(w).get(i);
- men.get(other).remove(new Integer(w));
- women.get(w).remove(new Integer(other));
- }
- }
- System.out.printf("\nMatches:\n");
- for(int guy : matches.keySet()){
- System.out.println("Man " + (guy+1) +" and " + "Woman " + (matches.get(guy) +1));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment