teaching machines

CS 145 Lecture 26 – Arrays as Maps

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

Agenda

TODO

Code

FairDie.java

package lecture1031;

import java.util.Arrays;
import java.util.Random;

public class FairDie {
  public static void main(String[] args) {
    Random g = new Random();
    int[] pipCounts = new int[6];
    
    for (int i = 0; i < 500000000; ++i) {
      int roll = g.nextInt(6) + 1;
      ++pipCounts[roll - 1];
    }
    
    System.out.println(Arrays.toString(pipCounts));
  }
}

LetterFrequency.java

package lecture1031;

import java.util.Scanner;

public class LetterFrequency {
  public static void main(String[] args) {
    int[] frequencies = new int[26];
    
    Scanner in = new Scanner(System.in);
    in.useDelimiter("[^A-Za-z]+");
    
    while (in.hasNext()) {
      String word = in.next().toLowerCase();
      for (int i = 0; i < word.length(); ++i) {
        char c = word.charAt(i);
        ++frequencies[c - 'a'];
      }
    }
    
    for (int i = 0; i < frequencies.length; ++i) {
      System.out.println((char) ('a' + i) + ": " + frequencies[i]);
    }
    
    in.close();
  }
}

Haiku

Our days are numbered
Day i didn’t seem like much
But i grew each day