teaching machines

CS 145 Lecture 24 – Hello, Arrays

October 27, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

Program This

You, being a degree-seeking human, have an insatiable appetite for trivia. You wonder how many birthdays are in the room. Does each person have a unique birthday? Was everybody born on just one day? Or is the answer somewhere in the middle?

How would you find the answer to your question? Write pseudocode of how you might program a person to find your answer. Is your algorithm concrete enough that someone could implement it without you having to explain anything?

Code

BirthdayBash.java

package lecture1027;

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

public class BirthdayBash {
  public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(new File("/Users/johnch/Desktop/bdays.csv"));
  
//    int jan1 = 0;
//    int jan2 = 0;
//    int jan3 = 0;
    int[] counts = new int[366];
    
    while (in.hasNextInt()) {
      int month = in.nextInt();
      int day = in.nextInt();
      int doy = getDoy(month, day);
      ++counts[doy - 1];
//      if (month == 1 && day == 1) {
//        ++jan1;
//      } else if (month == 1 && day == 2) {
//        ++jan2;
//      } else if (month == 1 && day == 3) {
//        ++jan3;
//      } else {
//        System.out.println("This is terrible.");
//      }
    }
    
//    if (jan1 > 1) {
//      System.out.println("Repeat on January 1");
//    }
//    
//    if (jan2 > 1) {
//      System.out.println("Repeat on January 2");
//    }
//    
//    if (jan3 > 1) {
//      System.out.println("Repeat on January 3");
//    }
    
    int nSharedDays = 0;
    int nPeopleWhoShare = 0;
    for (int i = 0; i < counts.length; ++i) {
      if (counts[i] > 1) {
        ++nSharedDays;
        nPeopleWhoShare += counts[i];
      }
    }
    System.out.println(nSharedDays);
    System.out.println(nPeopleWhoShare);
  
    in.close();
  }
  
  public static int getDoy(int month, int day) {
//    int[] daysInMonths = new int[12];
//    daysInMonths[0] = 31;
//    daysInMonths[1] = 29;
    int[] daysInMonths = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int doy = day;
    for (int m = 1; m < month; ++m) {
      doy += daysInMonths[m - 1];
    }
    return doy;
  }
}

Haiku

on efficiency in parenting:
Efficient birthday
I blew out my candles quick
The menorah helped