@Override
 public int corpusDocFrequencyByTerm(String term) {
   String indexFile = _options._indexPrefix + "/merge.txt";
   try {
     BufferedReader reader = new BufferedReader(new FileReader(indexFile));
     String line;
     while ((line = reader.readLine()) != null) {
       int termDocFren = 0;
       String title = "";
       String data = "";
       Scanner s = new Scanner(line).useDelimiter("\t");
       while (s.hasNext()) {
         title = s.next();
         data = s.next();
       }
       if (title.equals(term)) {
         String[] docs = data.split("\\|");
         termDocFren = docs.length;
       }
       reader.close();
       return termDocFren;
     }
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return 0;
 }
Пример #2
0
  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int numNetworks = scanner.nextInt();

    for (int i = 0; i < numNetworks; i++) {

      HashMap<String, HashSet<String>> network = new HashMap<>();

      // Add users
      int numPeople = scanner.nextInt();
      for (int j = 0; j < numPeople; j++) {
        network.put(scanner.next(), new HashSet<String>());
      }

      // Build Friend Connections
      int numConnections = scanner.nextInt();
      for (int j = 0; j < numConnections; j++) {
        String friend1 = scanner.next();
        String friend2 = scanner.next();
        network.get(friend1).add(friend2);
        network.get(friend2).add(friend1);
      }

      // Get Rivals and calculate coolness
      int numRivals = scanner.nextInt();
      LinkedHashMap<String, Integer> rivals = new LinkedHashMap<String, Integer>();
      for (int j = 0; j < numRivals; j++) {
        String rival = scanner.next();
        if (!network.containsKey(rival)) {
          rivals.put(rival, 0);
          continue;
        }
        boolean isCooler = false;
        for (int k = 1; k <= network.size() && !isCooler; k++) {
          visited.add(rival);
          int rivalCoolness = getCoolness(network, rival, k);
          visited.clear();
          visited.add("You");
          int yourCoolness = getCoolness(network, "You", k);
          visited.clear();
          if (yourCoolness > rivalCoolness) {
            rivals.put(rival, k);
            isCooler = true;
          }
        }
        if (!isCooler) {
          rivals.put(rival, -1);
        }
      }

      System.out.println("Social Network " + (i + 1) + ":");
      for (Map.Entry<String, Integer> e : rivals.entrySet()) {
        if (e.getValue() == -1) System.out.println(e.getKey() + " is just too cool");
        else System.out.println(e.getKey() + " " + e.getValue());
      }
      System.out.println();
    }
  }
Пример #3
0
  public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = new Scanner(new FileReader("Lab3_input.txt"));
    PrintWriter outFile = new PrintWriter("Lab3_Exercise_output.txt");

    // Declare variables
    String lastName, firstName;
    double salary, pctRaise, salaryFinal;

    // set up while loop
    while (inFile.hasNext()) // condition checks to see if there is anything in the input file
    {
      // Read information from input file
      lastName = inFile.next();
      firstName = inFile.next();
      salary = inFile.nextDouble();
      pctRaise = inFile.nextDouble();

      // Calculate final salary
      salaryFinal = salary + (salary * pctRaise / 100);

      // Write file
      outFile.printf("%s %s %.2f%n", lastName, firstName, salaryFinal);
    }

    // Close input/output methods
    outFile.close();
    inFile.close();
  }
Пример #4
0
 public Graph(String s) {
   nodes = new Node[MAX_NODES];
   input = new Scanner(s);
   System.out.println("#Create graph: ");
   while (input.hasNext()) {
     char from, to;
     int cost;
     from = input.next().charAt(0);
     to = input.next().charAt(0);
     cost = input.nextInt();
     int fromIndex = from - 'A';
     int toIndex = to - 'A';
     // Create nodes if data is new; no checking for now.
     if (nodes[fromIndex] == null) {
       nodes[fromIndex] = new Node(from);
     }
     if (nodes[toIndex] == null) {
       nodes[toIndex] = new Node(to);
     }
     // Create edge, add edge to list of edges for the "from" node
     edges[edgeIndex] = new Edge(nodes[fromIndex], nodes[toIndex], cost);
     nodes[fromIndex].addEdge(edges[edgeIndex]);
     Edge e = edges[edgeIndex];
     System.out.println(
         "edges[" + edgeIndex + "]: " + e.from.data + " -> " + e.to.data + "; cost: " + e.cost);
     edgeIndex++;
   }
 }
Пример #5
0
  public static void main(String[] args) throws IOException {

    // Instantiate Objects
    FileReader fr = new FileReader("Accounts.txt");
    PrintWriter pw = new PrintWriter("CurrentAccounts.txt");
    Scanner console = new Scanner(fr);

    // Pull information from Accounts.txt into Strings
    String fullName = console.next();
    String lastName = fullName.substring(0, 9);
    String firstName = fullName.substring(10, 17);
    String accountBalance = console.next();
    String sWholeValue = accountBalance.substring(0, 4);
    String sDecimalValue = accountBalance.substring(5, 8);

    // Convert accountBalance from one string variable into two integer variables
    int wholeValue = Integer.parseInt(sWholeValue);
    int decimalValue = Integer.parseInt(sDecimalValue);

    // Write
    pw.printf("%15s %14s%06d%06d", firstName, lastName, wholeValue, decimalValue);

    // Close Streams
    fr.close();
    pw.close();
  }
  public static void main(String[] args) throws Exception {

    // final Logger log = Logger.getLogger(sample.class.getCanonicalName());
    JobData jd = new JobData();

    Scanner input = new Scanner(System.in);
    try {
      System.out.print("What is your user name? ");
      jd.setUsername(input.next());
      System.out.print("What is your password? ");
      jd.setPassword(input.next());
    } catch (Exception e) {
      // log.log(Level. SEVERE, "The system encountered an exception while attempting to login");
    } finally {
      input.close();
    }

    jd.setJob("TestREST");
    jd.setServer("http://10.94.0.137");
    jd.setPort("8006");

    URL url = new URL("http://10.94.0.137:8006/api/xml");
    Document dom = new SAXReader().read(url);

    for (Element job : (List<Element>) dom.getRootElement().elements("job")) {
      System.out.println(
          String.format(
              "Job %s with URL %s has status %s",
              job.elementText("name"), job.elementText("url"), job.elementText("color")));
    }
  }
Пример #7
0
 public boolean ok(String out, String reference) {
   // log.fine("out1: " + a);
   // log.fine("out2: " + b);
   Scanner sa = new Scanner(out);
   Scanner sb = new Scanner(reference);
   while (sa.hasNext() && sb.hasNext()) {
     if (sa.hasNextDouble() || sb.hasNextDouble()) {
       if (!sa.hasNextDouble() || !sb.hasNextDouble()) return true;
       double da = sa.nextDouble();
       double db = sb.nextDouble();
       double d_abs = Math.abs(da - db);
       double d_rel = d_abs / Math.abs(db);
       if (!(d_abs < EPS || d_rel < EPS)) {
         log.fine("NOK, " + da + " too far from " + db);
         return false;
       }
     } else {
       String xa = sa.next();
       String xb = sb.next();
       if (!xa.equals(xb)) {
         log.fine("NOK, " + xa + " != " + xb);
         return false;
       }
     }
   }
   if (sa.hasNext() || sb.hasNext()) {
     log.fine("NOK: different number of tokens.");
     return false;
   }
   return true;
 }
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (true) {
			int n = sc.nextInt();
			if (n == 0)
				break;
			Train[] trains = new Train[n];
			for (int i = 0; i < n; i++) {
				String depstr = sc.next();
				String[] depstrs = depstr.split(":");
				int dep = Integer.parseInt(depstrs[0]) * 3600
						+ Integer.parseInt(depstrs[1]) * 60
						+ Integer.parseInt(depstrs[2]);
				String arrstr = sc.next();
				String[] arrstrs = arrstr.split(":");
				int arr = Integer.parseInt(arrstrs[0]) * 3600
						+ Integer.parseInt(arrstrs[1]) * 60
						+ Integer.parseInt(arrstrs[2]);
				trains[i] = new Train(dep, arr);
			}
			int maxtrain = 0;
			int nowtrain = 0;
			for (int i = 0; i < 24*60*60; i++) {
				for(int j=0;j<n;j++){
					if(i==trains[j].dep)
						nowtrain++;
					if(i==trains[j].arr)
						nowtrain--;
				}
				maxtrain = Math.max(maxtrain, nowtrain);
			}
			System.out.println(maxtrain);
		}
		sc.close();
	}
Пример #9
0
  /**
   * The read admin list reads in admin objects from a readfile
   *
   * @return
   * @throws FileNotFoundException
   */
  public LinkedList<Admin> readAdminList() throws FileNotFoundException {
    FileInputStream fstream = new FileInputStream("adminList.csv");
    LinkedList<Admin> adminList = new LinkedList<Admin>();
    Scanner input = new Scanner(fstream);
    input.useDelimiter(",");

    try {
      // reads file
      while (input.hasNext()) {
        String firstName = input.next();
        String lastName = input.next();
        String userName = input.next();
        String password = input.next();
        String email = input.next();
        String office = input.next();
        String phoneNumber = input.nextLine();

        // creates admin
        Admin newAdmin =
            new Admin(userName, password, email, firstName, lastName, office, phoneNumber);

        adminList.add(newAdmin);
      }
      fstream.close();
    } catch (Exception e) {
      adminList = null;
    }

    Collections.sort(adminList);

    return adminList;
  }
 public static void main(String[] args) {
   Scanner inp = new Scanner(System.in);
   int n = inp.nextInt();
   String[] store = new String[n];
   for (int i = 0; i < n; i++) store[i] = inp.next();
   int[] cnt = new int[n];
   Arrays.fill(cnt, 0);
   String str = inp.next();
   for (int j = 0; j < n; j++) {
     int l1 = store[j].length();
     for (int k = 0; k <= (str.length() - l1); k++) {
       if (str.substring(k, k + l1).equals(store[j])) {
         cnt[j] = cnt[j] + 1;
       }
     }
   }
   int y = 0;
   for (int m = 0; m < n; m++) {
     y = Math.max(y, cnt[m]);
   }
   System.out.println(y);
   for (int h = 0; h < n; h++) {
     if (cnt[h] == y) System.out.println(store[h]);
   }
 }
Пример #11
0
  /**
   * reads faculty list file
   *
   * @return LinkedList<Faculty>
   * @throws FileNotFoundException
   */
  public LinkedList<Faculty> readFacultyList() throws FileNotFoundException {
    FileInputStream fstream = new FileInputStream("facultyList.csv");
    LinkedList<Faculty> facultyList = new LinkedList<Faculty>();
    Scanner input = new Scanner(fstream);
    input.useDelimiter(",");

    try {
      // reads file
      while (input.hasNext()) {
        String firstName = input.next();
        String lastName = input.next();
        String userName = input.next();
        String password = input.next();
        String email = input.next();
        String office = input.next();
        String phoneNumber = input.nextLine();
        // creates faculty member
        Faculty newFaculty =
            new Faculty(userName, password, email, firstName, lastName, office, phoneNumber);

        facultyList.add(newFaculty);
      }
      fstream.close();
    } catch (Exception e) {
      facultyList = null;
    }

    Collections.sort(facultyList);

    return facultyList;
  }
Пример #12
0
  public static void main(String[] args) throws FileNotFoundException {

    /* Loads the word list and stores its length */
    String ext = "/afs/cats/courses/cmps109-db/cmps012a-pa1/wordList.txt";
    Scanner in = new Scanner(new FileInputStream(ext));
    int listSize = in.nextInt(); // length of the word list

    /* Randomly selects word from the word list */
    Random rand = new Random();
    int n = rand.nextInt(listSize) + 1;
    for (int i = 1; i < n; i++) in.next();
    String word = in.next();

    /* Displays to the user the number of letters in the word */
    System.out.println("Your word is " + word.length() + " letters long.");

    /* Recursive method that plays the game. TRUE return indicates win */
    if (play(word)) {

      System.out.println("You win! The word was " + word + ".");

    } else { // Display for if the user loses

      System.out.println("You lose. The word was " + word + ".");
    }
  }
Пример #13
0
  /*
  Method: parseInputLine - text parser
  Purpose: parse the line of text and returns a TreeNode
  Parameters:
      String line   the line of text being parsed
  Returns:
      Entry - the Object parsed from the text line
  */
  private TreeNode parseInputLine(String line) {
    if (line.equals("")) {
      // returns a null object if the line is empty
      // only null entry source in code
      return null;
    }

    // a new empty TreeNode object
    TreeNode returnNode = new TreeNode(ENTRY); // is an entry
    // Scanner to scan the line of text
    Scanner lineScanner = new Scanner(line);
    lineScanner.useDelimiter("/");

    // sets the entry's word
    returnNode.setMyString(lineScanner.next());

    while (lineScanner.hasNext()) {
      // the next word in the line
      String nextWord = lineScanner.next();
      // end of line and 'a//b/c' blank words
      if (!(nextWord == null) && !(nextWord.equals(""))) {
        // adds each word in alphabet order to the
        // synonym linkedList
        returnNode.addSynonymInOrder(nextWord);
        // might not have any synonyms
      }
    }
    // returns the finished entry object
    return returnNode;
  }
Пример #14
0
  private static String checkString(Func function, Scanner input, boolean newAccount, UserID uid) {

    String str = "";
    boolean valid = false;
    while (!valid) {
      if (function == Func.USERNAME) {

        if (newAccount) {
          System.out.println("Please enter your new username: "******"Please enter your user name");
        }
        str = input.next();
        valid = checkUserName(str, newAccount);
      } else if (function == Func.PASSWORD) {
        System.out.println("Please enter your password: "******"Please enter your first name: ");
        str = input.next();
        valid = str.length() > 2;
      }

      if (!valid && !newAccount) return null;
    }

    return !valid ? null : str;
  }
Пример #15
0
 public static void main(String[] args) throws IOException {
   Scanner s = new Scanner(new File("gift1.in"));
   PrintWriter out = new PrintWriter(new FileWriter("gift1.out"));
   int people = s.nextInt();
   HashMap<String, Integer> moneyGiven = new HashMap<String, Integer>();
   HashMap<String, Integer> moneyReceived = new HashMap<String, Integer>();
   String[] names = new String[people];
   for (int x = 0; x < people; x++) {
     String name = s.next();
     names[x] = name;
     moneyGiven.put(name, 0);
     moneyReceived.put(name, 0);
   }
   for (int x = 0; x < people; x++) {
     String person = s.next();
     int give = s.nextInt();
     int receivers = s.nextInt();
     if (receivers == 0) continue;
     give = give - give % receivers;
     moneyGiven.put(person, give);
     for (int y = 0; y < receivers; y++) {
       String name = s.next();
       moneyReceived.put(name, give / receivers + moneyReceived.get(name));
     }
   }
   for (int x = 0; x < people; x++) {
     out.println(names[x] + " " + (moneyReceived.get(names[x]) - moneyGiven.get(names[x])));
   }
   out.close();
 }
Пример #16
0
  private void solve() {
    Scanner sc = new Scanner(System.in);
    char[] PAPER = sc.next().toCharArray();
    char[][] ROAD = new char[2][];
    ROAD[0] = sc.next().toCharArray();
    ROAD[1] = sc.next().toCharArray();

    int n = PAPER.length;
    int m = ROAD[0].length;
    int[][] DT = new int[n + 1][2];

    DT[0][0] = 1;
    DT[0][1] = 1;

    for (int j = 0; j < m; j++) {
      for (int i = n - 1; i >= 0; i--) {
        for (int t = 0; t < 2; t++) {
          if (PAPER[i] == ROAD[t][j]) {
            DT[i + 1][t] += DT[i][1 - t];
          }
        }
      }
    }

    System.out.println(DT[n][0] + DT[n][1]);
  }
  public void init() {
    Scanner scan = new Scanner(System.in);
    n = scan.nextInt();
    m = scan.nextInt();
    for (int i = 0; i < n; i++) {
      String input = scan.next();
      record.add(input);
    }

    for (int i = 0; i < m; i++) {
      String input = scan.next();
      char[] charArray = input.toCharArray();
      boolean isValid = false;
      for (int j = 0; j < charArray.length; j++) {
        char c = charArray[j];
        for (char d = 'a'; d <= 'c'; d = (char) (d + 1)) {
          if (d == c) continue;
          charArray[j] = d;
          if (record.contains(new String(charArray))) {
            isValid = true;
            break;
          }
        }
        charArray[j] = c;
        if (isValid) break;
      }
      if (isValid) System.out.println("YES");
      else System.out.println("NO");
    }
    scan.close();
  }
Пример #18
0
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int year = 0;
    String gender = "";
    boolean boo = true;
    while (boo) {
      try {
        System.out.print("Enter year(must be 1880 or later): ");
        year = input.nextInt();
        if (year > 1879) {
          boo = false;
        }
      } catch (InputMismatchException e) {
        System.out.println("Wrong input. Try again.");
        input.nextLine();
      }
    }
    boo = true;
    while (boo) {
      try {
        System.out.print("Enter gender(M or F): ");
        gender = input.next();
        if (gender.equals("M") || gender.equals("F")) {
          boo = false;
        }
      } catch (InputMismatchException e) {
        System.out.println("Wrong input. Try again.");
        input.nextLine();
      }
    }
    boo = true;
    System.out.print("Enter name: ");
    String name = input.next();
    File file = new File("babynamesranking" + year + ".txt");
    if (!file.exists()) {
      System.out.println("File does not exist or there is no data for that year.");
      System.exit(1);
    }
    int rank = 0;
    try (Scanner input2 = new Scanner(file)) {
      while (input2.hasNextLine()) {
        int ranking = input2.nextInt();
        String maleName = input2.next();
        String femaleName = input2.next();
        if (maleName.equals(name) || femaleName.equals(name)) {
          rank = ranking;
        }
      }
      input2.close();

    } catch (Exception e) {
      System.out.println("Error");
    }
    if (rank == 0) {
      System.out.println("The name is not ranked in this year.");
    } else System.out.println(name + " is ranked " + "#" + rank + " in year " + year);
  }
Пример #19
0
  public static void main(String[] args) {
    Scanner scans = new Scanner(System.in);
    int test = 1;
    while (true) {
      int V = scans.nextInt();
      int E = scans.nextInt();
      int Q = scans.nextInt();

      if (V == 0 && E == 0 && Q == 0) break;
      scans.nextLine();
      if (test > 1) System.out.println("");

      double[] p = new double[V];
      double[] q = new double[V];
      TreeMap<String, Integer> names = new TreeMap<String, Integer>();

      for (int i = 0; i < V; i++) {
        String n = scans.next();
        p[i] = scans.nextDouble();
        q[i] = scans.nextDouble();
        scans.nextLine();
        names.put(n, i);
      }

      long[][] APSP = new long[V][V];
      for (int i = 0; i < V; i++) Arrays.fill(APSP[i], INF);

      for (int i = 0; i < E; i++) {
        String one = scans.next();
        String two = scans.next();
        scans.nextLine();
        int onei = names.get(one);
        int twoi = names.get(two);
        APSP[onei][twoi] =
            gcDistance(
                p[onei], q[onei], // 3D version
                p[twoi], q[twoi], 6378);
      }

      for (int k = 0; k < V; k++)
        for (int i = 0; i < V; i++)
          for (int j = 0; j < V; j++) APSP[i][j] = Math.min(APSP[i][j], APSP[i][k] + APSP[k][j]);

      System.out.println("Case #" + test);
      for (int i = 0; i < Q; i++) {
        String one = scans.next();
        String two = scans.next();
        scans.nextLine();
        int onei = names.get(one);
        int twoi = names.get(two);
        if (APSP[onei][twoi] != INF) System.out.println((APSP[onei][twoi]) + " km");
        else System.out.println("no route exists");
      }
      test++;
    }
  }
Пример #20
0
 // Reads name popularity rank data from text file into HashMap
 public void readRankData(Scanner input) {
   while (input.hasNextLine()) {
     String dataLine = input.nextLine();
     Person entry = new Person(dataLine);
     Scanner tokens = new Scanner(dataLine);
     String nameGender = tokens.next();
     nameGender += tokens.next();
     persons.put(nameGender, entry);
   }
 }
Пример #21
0
  public void remove() throws SQLException {
    Scanner sc = new Scanner(System.in);
    String id = sc.next();
    Dao<Account, String> accountDao = connect();

    accountDao.delete(accountDao.queryForId(id));
    System.out.println("Enter some string to continue");
    sc.next();
    connectionSource.close();
  }
Пример #22
0
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    try {
      s = new Scanner(new BufferedReader(new FileReader("system.properties")));
    } catch (IOException e) {
      e.printStackTrace();
    }
    s.useDelimiter("\\n|=");
    s.next();
    int n = s.nextInt();
    s.next();
    int m = s.nextInt();
    int[] stime = new int[n];
    int[] otime = new int[n];
    int k = 0;
    while (s.hasNext()) {
      s.next();
      stime[k] = s.nextInt();
      s.next();
      otime[k] = s.nextInt();
      k++;
    }

    FileWriter report = null;
    try {
      report = new FileWriter("output.log", false);
    } catch (IOException h) {

    }
    FileWriter event = null;
    try {
      event = new FileWriter("event.log", false);
    } catch (IOException g) {

    }
    Start.out = new PrintWriter(report);
    PrintWriter ev = new PrintWriter(event);
    Tree t = new Tree(n);
    TreeVisitor[] p = new TreeVisitor[n];
    String times = "";
    for (int i = 0; i < n; i++) p[i] = new TreeVisitor(n + i, m, t, stime[i], otime[i]);

    for (int i = 0; i < n; i++) p[i].start();
    for (int i = 0; i < n; i++) {
      try {
        p[i].join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    ev.println("sequence:\n");
    ev.print(Start.runtimes);
    Start.out.close();
    ev.close();
  }
 public static int initializeCentroids() throws FileNotFoundException {
   int i, k, index, numClust = 0;
   Review rv;
   String reviews = new String();
   String singleRv = new String();
   String reviewer = new String();
   String rating = new String();
   for (i = 0; i < maxClusters; i++) {
     centroids[i] = new Cluster();
     centroids_ref[i] = new Cluster();
   }
   File modelFile = new File(strModelFile);
   Scanner opnScanner = new Scanner(modelFile);
   while (opnScanner.hasNext()) {
     k = opnScanner.nextInt();
     centroids_ref[k].similarity = opnScanner.nextFloat();
     centroids_ref[k].movie_id = opnScanner.nextLong();
     centroids_ref[k].total = opnScanner.nextShort(); // Leo
     centroids_ref[k].total = attrNum + 1;
     reviews = opnScanner.next();
     Scanner revScanner = new Scanner(reviews).useDelimiter(",");
     // while(revScanner.hasNext()){ //Leo
     int attrCnt = 0;
     while (revScanner.hasNext() && attrCnt < attrNum) {
       singleRv = revScanner.next();
       index = singleRv.indexOf("_");
       // reviewer = new String(singleRv.substring(0,index)); //Leo
       reviewer = new String(String.valueOf(attrCnt));
       rating = new String(singleRv.substring(index + 1));
       rv = new Review();
       rv.rater_id = Integer.parseInt(reviewer);
       rv.rating = (byte) Integer.parseInt(rating);
       centroids_ref[k].reviews.add(rv);
       attrCnt++;
     }
   }
   // implementing naive bubble sort as maxClusters is small
   // sorting is done to assign top most cluster ids in each iteration
   for (int pass = 1; pass < maxClusters; pass++) {
     for (int u = 0; u < maxClusters - pass; u++) {
       if (centroids_ref[u].movie_id < centroids_ref[u + 1].movie_id) {
         Cluster temp = new Cluster(centroids_ref[u]);
         centroids_ref[u] = centroids_ref[u + 1];
         centroids_ref[u + 1] = temp;
       }
     }
   }
   for (int l = 0; l < maxClusters; l++) {
     if (centroids_ref[l].movie_id != -1) {
       numClust++;
     }
   }
   return numClust;
 }
 public static void main(String[] args) {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Enter the area of the circle here: ");
   double area = keyboard.nextDouble();
   System.out.println("The radius of the circle is: " + Math.sqrt(area / Math.PI));
   System.out.print("What is your fist name? ");
   String first = keyboard.next();
   System.out.print("What is your last name? ");
   String last = keyboard.next();
   System.out.println("Your full name is " + first + " " + last);
 }
Пример #25
0
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
Пример #26
0
 public static void main(String args[]) throws Exception {
   Scanner scn = new Scanner(System.in);
   youtubedl obj = new youtubedl(new URL(args[0]));
   obj.GetDownloadIndex();
   obj.displayIndex();
   System.out.print("Enter Index: ");
   String get_index = scn.next();
   System.out.print("Enter Name: ");
   String get_name = scn.next();
   obj.download(get_index, get_name);
   System.out.println();
 }
Пример #27
0
  public static void ciphers(String message, int cipher, int encrypt_decrypt) {

    // determines which function to use depending on user input
    if (cipher == 1) {
      // asks user for a key
      System.out.println("Enter a key value: ");
      int k = cin.nextInt();
      if (encrypt_decrypt == 1) {
        shift(message, k);
      } else {
        shift(message, -k);
      }
    } else if (cipher == 2) {
      // asks user for a key
      System.out.println("Enter a key value: ");
      int k = cin.nextInt();

      // asks user for 'b' value
      System.out.println("Enter a 'b' value: ");
      int b = cin.nextInt();

      if (encrypt_decrypt == 1) {
        affine(message, k, b, 1);
      } else {
        affine(message, k, b, 2);
      }
    } else if (cipher == 3) {
      // asks user for a keyword & gets rid of repeated characters
      System.out.println("Enter a keyword: ");
      String keyword = cin.next();
      keyword = keyword.toUpperCase();
      keyword =
          keyword.replaceAll(
              (String.format("(.)(?<=(?:(?=\\1).).{0,%d}(?:(?=\\1).))", keyword.length())), "");

      if (encrypt_decrypt == 1) {
        substitution(message, keyword, 1);
      } else {
        substitution(message, keyword, 2);
      }
    } else if (cipher == 4) {
      // asks user for a keyword
      System.out.println("Enter a keyword: ");
      String keyword = cin.next();
      keyword = keyword.toUpperCase();

      if (encrypt_decrypt == 1) {
        vigenere(message, keyword, 1);
      } else {
        vigenere(message, keyword, 2);
      }
    }
  }
Пример #28
0
 public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   while (s.hasNext()) {
     String preord = s.next();
     String inord = s.next();
     HashMap<Character, Integer> map = new HashMap<Character, Integer>();
     for (int i = 0; i < inord.length(); i++) map.put(inord.charAt(i), i + 1);
     map.put(' ', 200);
     Node tree = new Node(' ', new Str(preord), map, 0);
     tree.postorder();
     System.out.println();
   }
 }
  public static void main(String args[]) {

    int width = IN.nextInt();
    int height = IN.nextInt();
    IN.nextLine();
    System.err.println(width + " " + height);

    Grid tunnelMap = new Grid(width, height);

    fillTunelMap(tunnelMap);

    int exit =
        IN
            .nextInt(); // the coordinate along the X axis of the exit (not useful for this first
                        // mission, but must be read).
    System.err.println(exit);
    tunnelMap.setEndPosition(new Position(exit, height - 1));

    // game loop
    while (true) {
      Position IndiActPosition = new Position(IN.nextInt(), IN.nextInt());

      Direction entranceDirection = Enum.valueOf(Direction.class, IN.next());

      tunnelMap.getRoom(IndiActPosition).setEntrance(entranceDirection);
      tunnelMap.initializeGrid();
      tunnelMap.findPathFromStartToEnd(IndiActPosition);

      int numberOfRocks = IN.nextInt(); // the number of rocks currently in the grid.

      for (int i = 0; i < numberOfRocks; i++) {
        System.err.println();
        int XR = IN.nextInt();
        int YR = IN.nextInt();
        Position rockPosition = new Position(XR, YR);
        Direction entranceOfRock = Enum.valueOf(Direction.class, IN.next());
        tunnelMap.getRoom(rockPosition).setEntrance(entranceOfRock);
        tunnelMap.compareRockPathWithIndisPath(rockPosition);

        System.err.println("ROCK " + rockPosition + " " + entranceOfRock);
      }

      String command = tunnelMap.nextCommand();

      // One line containing the X Y coordinates of the room in which you believe Indy will be on
      // the next turn.
      System.out.println(command);
    }
  }
Пример #30
0
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   String p1 = input.next(), p2 = input.next();
   int x1 = p1.charAt(0) - 'a', y1 = p1.charAt(1) - '1';
   int x2 = p2.charAt(0) - 'a', y2 = p2.charAt(1) - '1';
   StringBuilder out = new StringBuilder();
   int count = 0;
   while (true) {
     count++;
     if (x1 < x2) {
       if (y1 < y2) {
         out.append("RU\n");
         x1++;
         y1++;
       } else if (y1 > y2) {
         out.append("RD\n");
         x1++;
         y1--;
       } else {
         out.append("R\n");
         x1++;
       }
     } else if (x1 > x2) {
       if (y1 < y2) {
         out.append("LU\n");
         x1--;
         y1++;
       } else if (y1 > y2) {
         out.append("LD\n");
         x1--;
         y1--;
       } else {
         out.append("L\n");
         x1--;
       }
     } else if (y1 > y2) {
       out.append("D\n");
       y1--;
     } else if (y1 < y2) {
       out.append("U\n");
       y1++;
     } else {
       count--;
       break;
     }
   }
   System.out.println(count + "\n" + out);
 }