teaching machines

CS 145 Lecture 28 – ArrayList and For-each Pattern

November 5, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

Blackbox

Program This

Your work for U-WE-C, a digital security firm. You are inspecting the log files on a system, but you only care about the last 10 entries in the file. How do you print just these last 10? Your file reading API lets you read lines sequentially, from beginning to end.

Code

PlusOne.java

package lecture1105;

import java.util.Arrays;

public class PlusOne {
  public static void main(String[] args) {
    int[] nums = {1, 2, 3};
    System.out.println("nums: " + Arrays.toString(nums));
    int[] numsPlusOne = plusOne(nums);
    System.out.println("nums: " + Arrays.toString(nums));
    System.out.println("numsPlusOne: " + Arrays.toString(numsPlusOne));
  }

  public static int[] plusOne(int[] src) {
    int[] dst = new int[src.length];
    
    for (int i = 0; i < src.length; ++i) {
      dst[i] = src[i] + 1;
    }

    return dst;
  }
}

Freezing.java

package lecture1105;

import java.util.Arrays;

public class Freezing {
  public static void main(String[] args) {
    int[] nums = {30, 31, 32, 33, 34, 35, 42, 100};
    System.out.println(Arrays.toString(nums));
    boolean[] truths = isNotFreezing(nums);
    System.out.println(Arrays.toString(truths));
  }

  public static boolean[] isNotFreezing(int[] fahrenheits) {
    boolean[] isNotFreezing = new boolean[fahrenheits.length];
    
    for (int i = 0; i < fahrenheits.length; ++i) {
      isNotFreezing[i] = fahrenheits[i] > 32;
    }

    return isNotFreezing;
  }
}

Log.java

package lecture1105;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Log {
  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(new File("/var/log/apache2/access_log"));
  
//    String[] lines = new String[10000000];
    ArrayList<String> lines = new ArrayList<String>();
    while (in.hasNextLine()) {
      lines.add(in.nextLine());
    }
    
    for (int i = lines.size() - 10; i < lines.size(); ++i) {
      System.out.println(lines.get(i));
    }
  }
}

Haiku

on CDL at 16:
Dad bought my first car
Not a car, but a school bus
“You might need the room”