Advertisement
jules0707

Outcast.java

Jan 7th, 2021
1,159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import edu.princeton.cs.algs4.In;
  2. import edu.princeton.cs.algs4.StdOut;
  3.  
  4. public class Outcast {
  5.  
  6.     private final WordNet wn;
  7.  
  8.     // constructor takes a WordNet object
  9.     public Outcast(WordNet wordnet) {
  10.         this.wn = wordnet;
  11.     }
  12.  
  13.     // given an array of WordNet nouns, return an outcast
  14.     public String outcast(String[] nouns) {
  15.         int n = nouns.length;
  16.         int[] distances = new int[n];
  17.         for (int i = 0; i < nouns.length; i++) {
  18.             for (int j = 0; j < n; j++) {
  19.                 distances[i] += wn.distance(nouns[i], nouns[j]);
  20.             }
  21.         }
  22.         // max distance search
  23.         int max = -1;
  24.         int id = -1;
  25.         for (int i = 0; i < n; i++) {
  26.             if (max < distances[i]) {
  27.                 max = distances[i];
  28.                 id = i;
  29.             }
  30.         }
  31.         return nouns[id];
  32.     }
  33.  
  34.     public static void main(String[] args) {
  35.         WordNet wordnet = new WordNet(args[0], args[1]);
  36.         Outcast outcast = new Outcast(wordnet);
  37.         for (int t = 2; t < args.length; t++) {
  38.             In in = new In(args[t]);
  39.             String[] nouns = in.readAllStrings();
  40.             StdOut.println(args[t] + ": " + outcast.outcast(nouns));
  41.         }
  42.     }
  43. }
  44.  
  45.  
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement