# teaching machines

## CS 145 Lecture 26 – Arrays as Maps

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

### Agenda

• what ?s
• arrays as maps
• fair die
• letter frequencies

### TODO

• Start homework 5. Due before November 14.
• For 2 extra credit quarter sheet participation points, map out a Choose Your Own Adventure book (as described in the homework 5 specification, e.g. “2|3|5,6,7|p|||”). Share the book String and a graph of the book on Piazza. You can turn the DOT output into a graph by installing Graphviz or using an online interpreter.
• If you don’t see the homework 5 SpecChecker, then you have not synced and pulled to update your Bitbucket repository.

### 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