import java.util.*; public class Marriage { // If menPrefs[i][j] = k, then Ms. k, is ranked j-th in the Mr. i's list. static int[][] menPrefs; // If womenPrefs[i][j] = k, then Mr. k, is ranked j-th in the Ms. i's list. static int[][] womenPrefs; // wife[i] = Mr. i's wife. Similarly, husband[j] = Ms. j's husband. // These arrays are filled by the algorithm. static int[] wife, husband; public static void main (String[] argv) { try { if ( (argv == null) || (argv.length != 2) ) { System.out.println ("Usage: Marriage "); System.exit(1); } int numTrials = Integer.parseInt (argv[0]); int numCouples = Integer.parseInt (argv[1]); double avgTimeTaken = performTrials (numTrials, numCouples); double theoretical = theoreticalTime (numCouples); System.out.println ("Actual=" + avgTimeTaken + " theoretical=" + theoretical + " ratio=" + (avgTimeTaken/theoretical)); } catch (Exception e) { e.printStackTrace(); } } static double theoreticalTime (int n) { return n*n; } static double performTrials (int numTrials, int numCouples) { // An array that holds the order 0, 1, ..., n-1. // This is just used as input to create a random permutation. int[] incrOrder = new int [numCouples]; for (int i=0; i it's splitsville for Ms. k. int x = husband[k]; husband[k] = i; wife[i] = k; // Poor Mr. x goes back to the bachelor list. UnmarriedMen.add (new Integer (x)); break; } // Else, continue search. } // end-for. // Now Mr. i has a spouse, but may get kicked back to bachelorhood. } // endwhile. // Now we're done. } // This method checks to see which of potential mates i and j are better // for person k. static boolean isPreferable (int[][] prefs, int k, int i, int j) { // Obtain ranks of i and j. int rank_i = rank (prefs[k], i); int rank_j = rank (prefs[k], j); // Compare. if (rank_i < rank_j) return true; else return false; } // Where does person i fall in the preference order given? static int rank (int[] prefs, int i) { // Look in array for rank. // NOTE: we can implement this much more efficiently with a pre-computed rank array. for (int j=0; j