import java.util.Scanner;
import java.io.*;
public class CarDealer  {
  /** 11/21/2018
    * This class answers question VI on Sample Exam 2.
    */
  public static void main(String[] args) throws IOException{
    final int SIZE = 10;
    String[] names = new String[SIZE];
    int[] numCars = new int[SIZE];
    readData(names, numCars);
    printArray(numCars);
    int totalCars = sumArr(numCars);
    System.out.println("Total number of cars sold: " + totalCars);
    mostCars(names, numCars);
    if (hasDuplicates(numCars))
      System.out.println("Yes, there is more than one with same amount.");
    else
      System.out.println("All values are unique.");
  }
  // methods
  /* readData reads data from a file into two parallel arrays.
   * @param names 
   * @param numCars
   */
  public static void readData(String[] names, int[] numCars) throws IOException {
    Scanner infile = new Scanner(new File("salespeople.txt"));
    int idx=0;
    while (infile.hasNext() && idx<names.length) {
       names[idx] = infile.next();
       numCars[idx++] = infile.nextInt();
    }
    infile.close();
  }
  /* sumArr sums values in an integer array
   * @param arr 
   * @return total of all values in the array
   */
  public static int sumArr(int[] arr) {
    int sum=0;
    for (int i=0; i<arr.length; i++)
       sum+=arr[i];
    return sum;
  }
  /** mostCars
    * @param names
    * @param numCars
    */
  public static void mostCars(String[] names, int[] numCars) {
    // need 2 loops because you have to find max before saying who is equal to max
    int max = numCars[0];
    for (int i=1; i<numCars.length; i++)
      if (max < numCars[i])
         max = numCars[i];
    for (int i=0; i<numCars.length; i++)
      if (numCars[i] == max) 
          System.out.println(names[i] + " sold " + max);
  }
  public static void findMax(String[] names, int[] numCars) {
    // instead of 2 loops you can use 2 methods
    int max = numCars[0];
    for (int i=1; i<numCars.length; i++)
      if (max < numCars[i])
         max = numCars[i];
    // now call linear search
    linearSearch(names, numCars, max);
    }
    public static void linearSearch(String[] names, int[] numCars, int key) {
    for (int i=0; i<numCars.length; i++)
      if (numCars[i] == key) 
          System.out.println(names[i] + " sold " + numCars[i]);
    }
    public static boolean hasDuplicates(int[] numCars) {
      for (int i=0; i<numCars.length-1; i++)
        for (int j=i+1; j<numCars.length; j++)
           if (numCars[i]==numCars[j])
               return true;
      return false;
    }
    public static void printArray(int[] arr) throws IOException {
      PrintWriter outfile = new PrintWriter("carDealerOutput.txt");
      for (int i=0; i<arr.length; i++)
        outfile.println(arr[i]);
      outfile.close();
    } 
}