teaching machines

CS1: Lecture 16 – Logic Continued

October 9, 2019 by . Filed under cs1, fall 2019, lectures.

Dear students,

Today we keep asking questions about data. Let’s start with some blackboxes!

Now let’s do some more free-form exercises:

Truth Tables

Let me be frank with you. Expressing a program’s logic can get really confusing, and this is probably the spot where we make the most mistakes when writing code. There are various tools to help us think about our logic, and we will examine a very common one now: the truth table. Truth tables enumerate all possible combinations of the inputs and show the resulting outputs. For instance, here is AND’s truth table:

a b a && b
0 0 0
0 1 0
1 0 0
1 1 1

And OR’s:

a b a || b
0 0 0
0 1 1
1 0 1
1 1 1

And NOT’s:

a !a
0 1
1 0

What are the truth tables for these expressions?

TODO

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

See you next class!

Sincerely,

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

I named my cat cat
My dog !cat. My next cat?
Why not !!cat

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

Blackbox.java

package lecture1009.cs145;

public class Blackbox {
  public static boolean isSmaller(String s, int n) {
    return s.length() <= n;
  }

  public static boolean isFactor(int numerator, int denominator) {
    return numerator % denominator == 0;
  }

  public static boolean isSameFirst(String a, String b) {
    return a.charAt(0) == b.charAt(0);
  }

  public static boolean isNotIn(String haystack, char needle) {
    return haystack.indexOf(needle) == -1;
//    return !haystack.contains(needle + "");
  }

  public static boolean isNeighbors(int a, int b) {
//    return a - b == 1 || a - b == -1;
    return Math.abs(a - b) == 1;
  }

  public static boolean isCapital(char c) {
    return 'A' <= c && c <= 'Z';
  }
}

Booleans.java

package lecture1009.cs148;

public class Booleans {
  public static boolean isGreaterThanWord(String text, int length) {
    return text.length() <= length;
  }

  public static boolean isFactor(int a, int b) {
    return a % b == 0;
  }

  public static boolean isFirstSamesies(String a, String b) {
    return a.charAt(0) == b.charAt(0);
  }

  public static boolean isExcluding(String haystack, char needle) {
    return haystack.indexOf(needle) == -1;
//    return !haystack.contains(needle + "");
  }

  public static boolean isOneAwayMG(int a, int b) {
    return Math.abs(a - b) == 1;
  }

  public static boolean isOneAwayVF(int a, int b) {
    return a == b + 1 || a == b - 1;
  }

  public static boolean isUppercase(char c) {
    return 'A' <= c && c <= 'Z';
  }
}