teaching machines

CS 145 Lecture 17 – Birthday problem II

April 4, 2012 by . Filed under cs145, lectures, spring 2012.

Agenda

TODO

Code

Birthday.java

package preexam2;

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

public class Birthday {
  
  public static void main(String[] args) throws FileNotFoundException {
    
    File file = new File("/home/user/bdays.txt");
    Scanner in = new Scanner(file);
    
    int[] counters = new int[366];
    
    while (in.hasNextLine()) {
      String line = in.nextLine();
      int i = monthDayToIndex(line);
      ++counters[i];
    }
    
    in.close();
    
    for (int i = 0; i < counters.length; ++i) {
      if (counters[i] > 1) {
        System.out.println("we've a repeat at " + i + "!");
        System.out.println("That is " + indexToMonthDay(i));
      }
    }
    
//    for (int m = 1; m <= 12; ++m) {
//      for (int d = 1; d <= 31; ++d) {
//        System.out.println(m + "/" + d + ": " + monthDayToIndex(m, d));
//      }
//    }
  }
  
  /**
   * 
   * @param monthDay "12,31", "1,1"
   * @return
   */
  public static int monthDayToIndex(String monthDay) {
    String[] fields = monthDay.split(",");
//    int month = (int) fields[0];
    int month = Integer.parseInt(fields[0]);
    int day = Integer.parseInt(fields[1]);
    return monthDayToIndex(month, day);
  }

  public static int monthDayToIndex(int month,
                                    int day) {
    // int[] monthCardinalities = new int[12];
    // monthCardinalities[0] = 31;
    int[] monthCardinalities = {
      31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

    int index = day - 1;

    for (int i = 0; i < month - 1; ++i) {
      index += monthCardinalities[i];
    }

    return index;
  }
  
  public static String indexToMonthDay(int index) {
    int[] monthCardinalities = {
      31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    
    int[] monthStartingIndices = new int[12];
    for (int m = 1; m < 12; ++m) {
      // Jan 1 0
      // Feb 1 31
      // March 1 60
      monthStartingIndices[m] = monthStartingIndices[m - 1] +
                                monthCardinalities[m - 1];
    }
    
    for (int m = 0; m < 12; ++m) {
      if (monthStartingIndices[m + 1] > index) {
        int day = index - monthStartingIndices[m];
        return (m + 1) + "/" + day;
      }
    }
    
    return null;
  }
}

Raffle.java

package preexam2;

import java.util.Random;
import java.util.Scanner;

public class Raffle {
  public static void main(String[] args) {
    String[] tickets = new String[15];
    Scanner in = new Scanner(System.in);
    
    System.out.println("Wanna ticket?");
    int i = 0;
    
    while (in.hasNextLine() && i < tickets.length) {
      tickets[i] = in.nextLine();
      ++i;
    }
    
    Random gen = new Random();
    System.out.println(tickets[gen.nextInt(i)]);
  }
}