import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileNotFoundException;

class CountInRange implements Runnable {
  int start, end;
  int finalCount;
  List<String> toCount;
  String searchFor;
  public CountInRange(List<String> s, String searchFor, int start, int end) {
    this.toCount = s;
    this.searchFor = searchFor;
    this.start = start;
    this.end = end;
    this.finalCount = 0;
  }
  public void run() {
    int count = 0;
    for(int i = start; i < end; i += 1) {
      if(this.toCount.get(i).equals(searchFor)) { count += 1; }
    }
    this.finalCount = count;
  }
  public int getFinalCount() {
    return this.finalCount;
  }
}
public class Threads {
  public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    Scanner sc = new Scanner(new File("really-big.txt"));
    List<String> words = new ArrayList<String>();
    while (sc.hasNext()) {
      words.add(sc.next());
    }

    Scanner input = new Scanner(System.in);

    System.out.println("Ready for input (<threads> <searchword>)");
    while(true) {
      System.out.print("> ");
      String next = input.nextLine();
      String[] parts = next.split("\\s+");
      
      int numberOfThreads = Integer.parseInt(parts[0]);
      String searchFor = parts[1];

      long start = System.currentTimeMillis();
      if(numberOfThreads == 1) {
        CountInRange counter = new CountInRange(words, searchFor, 0, words.size());
        Thread thread = new Thread(counter);
        thread.start();
        thread.join();
        System.out.println("Total words matching: " + counter.getFinalCount());
      }
      else if(numberOfThreads == 2) {
        int halfway = words.size() / 2;
        CountInRange counter1 = new CountInRange(words, searchFor, 0, halfway);
        CountInRange counter2 = new CountInRange(words, searchFor, halfway, words.size());
        Thread thread1 = new Thread(counter1);
        Thread thread2 = new Thread(counter2);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("Total words matching (1): " + counter1.getFinalCount());
        System.out.println("Total words matching (2): " + counter2.getFinalCount());
        System.out.println("Total: " + (counter1.getFinalCount() + counter2.getFinalCount()));
      }

      System.out.println("Total time (ms): " + (System.currentTimeMillis() - start));
    }
  }
}
