teaching machines

CS 1: Lecture 21 – Loops, Part 3

October 27, 2017 by . Filed under cs1, cs145, cs148, fall 2017, lectures.

Dear students,

We explore more examples of loops today. Because we are, in fact, stuck in a loop. There’s no way out of this.

Here’s your TODO list to complete before we meet again:

See you next class!

Sincerely,

P.S. It’s time for a haiku!

Sorry I’m so late
My self-driving car got stuck
In a roundabout

P.P.S. Here’s the code we wrote together in class…

Spacer.java

package lecture1027;

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

public class Spacer {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int nFailures = 0;
    File file;
    do {
      System.out.print("Enter a filename: ");
      String name = in.nextLine();
      file = new File(name);
      if (!file.exists()) {
        ++nFailures;
      }
    } while (!file.exists() && nFailures < 3);

    System.out.println(nFailures);
    if (nFailures == 3) {
      System.err.println("You shall not pass.");
    } else {
      System.out.println(file.length() / 1024.0 / 1024);
    }
  }
}

Spelunking.java

package lecture1027;

import java.util.Random;

public class Spelunking {
  public static void main(String[] args) {
    Random g = new Random();
    int n = g.nextInt(100);
    for (int i = 0; i < n; ++i) {
      System.out.println(getRandomLine(g));
    }
  }

  public static String getRandomLine(Random g) {
    int n = g.nextInt(15) + 1;
    String line = "";
    for (int i = 0; i < n; ++i) {
      line += "*";
    }
    return line;
  }
}

Unicode.java

package lecture1027;

public class Unicode {
  public static void main(String[] args) {
    for (int i = 0; i < 65536; ++i) {
      System.out.print((char) i);
      if (i % 20 == 0) {
        System.out.println();
      }
    }
  }
}

Factor.java

package lecture1027;

public class Factor {
  public static void main(String[] args) {
    int max = 0;
    int winnerSoFar = 0;
    for (int i = 1; i <= 1000; ++i) {
      int count = factorCount(i);
//      max = Math.max(count, max);
      if (count > max) {
        System.out.println(i + " -> " + count);
        max = count;
        winnerSoFar = i;
      }
    }
    System.out.println(winnerSoFar);
  }

  public static int factorCount(int n) {
    int nFactors = 0;
    for (int i = 2; i < n; i++) {
      if (n % i == 0) {
        nFactors += 1;
      }
    }
    return nFactors;
  }
}