daniel_lawson9999

Stable Marriage Algorithm

Mar 8th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.36 KB | None | 0 0
  1. /**
  2.  * Created by danie on 3/4/2017.
  3.  */
  4. import java.io.*;
  5. import java.util.*;
  6. public class StableMarriage {
  7.     public static void main(String args[]) throws FileNotFoundException{
  8.         File f = new File("C:\\Users\\danie\\Downloads\\Marriage.txt");
  9.         Scanner s = new Scanner(f);
  10.         ArrayList<ArrayList<Integer>> men = new ArrayList<>();
  11.         ArrayList<ArrayList<Integer>> women = new ArrayList<>();
  12.         TreeMap<Integer,Integer> matches = new TreeMap<>();
  13.         int count = 0;
  14.         while(s.hasNextLine()) {
  15.             String line = s.nextLine();
  16.             Scanner sl = new Scanner(line);
  17.             ArrayList<Integer> person = new ArrayList<>();
  18.             for (int i = 0; i < 2; i++) if (sl.hasNext()) sl.next();
  19.             while (sl.hasNext()) {
  20.                 person.add(Integer.parseInt(sl.next()) - 1);
  21.             }
  22.             if (line.toLowerCase().startsWith("man")) {
  23.                 men.add(person);
  24.                 matches.put(count, -1);
  25.                 count++;
  26.             }
  27.             if (line.toLowerCase().startsWith("woman")) {
  28.                 women.add(person);
  29.             }
  30.         }
  31.         System.out.println("Input (person = value+1, example: 3,1,2,0 = 4,2,3,1):");
  32.         System.out.println(men.toString());
  33.         System.out.println(women.toString());
  34.             while(matches.containsValue(-1)){
  35.                 int guy = 0;
  36.                 for(int i = 0; i<men.size();i++){
  37.                     if(matches.get(i)==-1) {
  38.                         guy = i;
  39.                         i = men.size() + 1;
  40.                     }
  41.                 }
  42.                 int w = men.get(guy).get(0);
  43.                 for(int i = 0;i<men.size();i++){
  44.                     if(matches.get(i)==w)matches.put(i,-1);
  45.                 }
  46.                 matches.put(guy,w);
  47.                     for (int i = women.get(w).indexOf(new Integer(guy)) + 1; i < women.get(w).size(); i++) {
  48.                         int other = women.get(w).get(i);
  49.                         men.get(other).remove(new Integer(w));
  50.                         women.get(w).remove(new Integer(other));
  51.                     }
  52.             }
  53.             System.out.printf("\nMatches:\n");
  54.             for(int guy : matches.keySet()){
  55.                 System.out.println("Man " + (guy+1) +" and " + "Woman " + (matches.get(guy) +1));
  56.             }
  57.  
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment