Wednesday, March 7, 2007

Notes from Week #8
Mock Suwannatat
7 March 2007

QUIZ

Adapted from:
http://www.andrew.cmu.edu/course/15-111-kesden/index/labs_index.html
Prof Gregory Kesden

Download your "quiz" from:
http://www.contrib.andrew.cmu.edu/user/psuwanna/cs10w07/FCLinkedList.java
http://www.contrib.andrew.cmu.edu/user/psuwanna/cs10w07/Fortune.java

Implement 2 out of 3 blank methods to get a BIG chocolate bar :)
 * - addInOrder
* - getFortune
* - remove

- Mock

Sunday, March 4, 2007

Lab 7 Strategy Session

Monday March 3, 2007
5pm - 8pm
@ Phelp 1413
The show starts at 5:40pm*

This will replace my office hours on Thursday.

* I will be there at 5pm. I will be eating my dinner and answering your questions. I will start talking about Lab 7 Strategy at 5:40pm. The talk may be about 60 - 90 mins.

Tentative Outline
  1. The math needed
    For those who already know how to write this program but get stuck on Math.
  2. How spiral example works
    Understanding how the spiral application (in the book) works.
  3. Basic hints
    Aimed at putting you in the right mindset to do the lab yourself. If you don't want to spoil the challenge, you should leave after this.
  4. More hints
    More detailed hints, suggested design. Warning: the fun could be spoiled. But you still need to understand what's going on in order to write the code.
  5. Even more hints? Nah... But let's look at some other examples.
    What if the lab is a Sierpinski Gasket? or a fractal tree?
  6. Questions

I can stick around a little after 8pm if people need me.

- Mock

Friday, March 2, 2007

Lab7 FAQ (part I)

Lab7 FAQ (part I)

Q1: A snowflake looks like a (fancy) triangle. But each smaller part is not a triangle. How do I use recursion to solve the problem?
Answer:
We do not draw a big triangle. Instead, we call the method 3 times (with different vertices as argument) to draw 3 segments of the snowflake.

Q2: What is really being executed? If we call ourselves all the way down to the littlest point, we don't really have a reason to come back up(up the call ladder) because we are just drawing small lines.
Answer:
At the bottom level of recursion, we know what to draw, so draw. For this program, we do not start drawing anything until we get to the bottom. What's the point of backing up the "call ladder"? So we can draw other small segments that make up for other parts of the snowflake. Even though the upper (non-bottom) levels of recursion do not draw anything, they actually calculate the positions and make calls to the lower level.

Q3: How would recursion work with the snowflake? How does recursion draw the lines and cuts out the old section?
Answer:
Again, there is no "cutting out" any lines here. It's unlike the spiral (or the Sierpinski Gasket) where we performs a draw at each level. For this lab, we only draw at the bottom level (base case of recursion).

Q4: I write a class called SnowflakeSegment. What should be the arguments to the constructor?
Answer:
Up to you. I have 2 suggestions for you. Choose either one or come up with your own. There is no right or wrong.
  1. SnowflakeSegment(Point p1, Point p2);
  2. SnowflakeSegment(Point p1, double length, double angle);
Both options would give sufficient information to the SnowflakeSegment on what to draw. Which one should you pick? ... whatever. You will need to calculate the points of subdivision from the arguments. It's a little work on geometry. Both options give you enough information for the calculation.
If you have more questions, post them here (be sure to put your name) or email me.

- Mock

Lab 7 Strategy Session

Dear cs10 Students,

Lab 7 seems to be tricky to many people, although it will not be much of a code change from the spiral example. I encourage you all to start early.

At least, please (please, please) read the lab and try to understand the example code by this weekend. Type it in your computer, run it, appreciate it, modify it to look differently. Play around with it. Try to understand how the code works.

Next, please read my Notes for Week #7 (previous post). Toward the end, I wrote about Sierpinski Gasket (which I didn't get to in the session yesterday). This, together with the spiral example in the book, can provide an insight into how you approach your lab.

Now, I would like to take a vote from you. If you care (:P), please reply to this email with answers to the following questions:
[1] Should I reschedule my office hours next week to Monday?
[2] If so, what time on Monday works for you?

I will call it a "Lab 7 Strategy Session" where I will provide "incremental hints" to those who need. You can come in, take some ideas, and leave (so you won't be spoiled by the hints). Or you can stick around to see more concrete examples of (other similar kinds of) fractals.

Have a nice weekend :)
- Mock

Wednesday, February 28, 2007

Notes from Week #7

Notes from Week #7
Feb 28, 2007
by Mock

It's the last day of February!

Nobody has attempted my quiz from last week :(
So I had to do it myself, and ate all the chocolate.

Just kidding. Please (actively) participate today and take all my leftover chocolate from the Valentine's Day :)

Outline

  1. The blog: why you should check cs10w07.blogspot.com often.
  2. Solution to the "quiz"
    1. Posted online (on the blog).
    2. Ideas.
  3. Questions about Homework 1?
    1. Top-down stepwise refinement, Algorithms
    2. See more on the blog.
  4. Lab grades.
    1. Why am I so tough on the "CODE DOES NOT COMPILE" situation?
    2. Programmer-customer analogy
  5. Recursion
    1. Tower of Hanoi
    2. More on Fractals

The Blog

Please check this blog often, since it will be the main line of communication between you and me and Shaomei. I will use the mailing list only when I think necessary. I don't want to spam your mailboxes :)

http://cs10w07.blogspot.com

You may find tips and useful info for your exams, homework, or life. (well, not quite, but...)

Solution to the "Quiz"

This refers to the 2 problems I gave in the discussion session last week. The first one is easy -- just to finish up the mergeInOrder method. Here we go:

(TOBEWRITTEN)

The second one takes a little (or a lot?) more thinking. Here is the code:

(TOBEWRITTEN)

The idea is to define two new arrays left[] and right[],
where left[i] = product of everything on the left of i-th cell,
and right[i] = product of everything on the right of i-th cell.

It's easy to compute left[] and right[] arrays in linear time. Now, we can say that the result array b[i] = left[i]*right[i] for all i.

This technique is known as Dynamic Programming. You will learn more about it in your algorithm course.

Question about Hw1

Is there a question? Please see the blog entry regarding this.

An example of top-down stepwise refinement:

When you want to write the mergeInOrder method, you want to come up with an algorithm. So, you start with a very high-level, yet descriptive pseudocode:
mergeInOrder(array A, array B)
  1. Make a new array C to be the output.
  2. Put contents of A and B onto C, maintaining order.
  3. Return C
Note that at this first step, your pseudocode sounds like English (or another human language of your choice -- in my case, I sometimes write in Thai). And you may have no idea (yet) how to do Step 2 exactly. This is fine, we will gradually refine it.

Now you can refine the steps to make it more clear, more descriptive. The next step could be:
mergeInOrder(array A, array B)
  1. Make an array C of size A.length + B.length.
  2. Loop until A or B run out of values
    1. IF current element in A is less than current element in B
      THEN put current element of A in C, proceed A and C
      ELSE put current element of B in C, proceed B and C
  3. If A run out first, put the rest of B in C
  4. If B run out first, put the rest of A in C
  5. Return C
This looks more like a code now. So let's put more details on how we keep track of "current elements" in A, B, and C. We probably need some index variables. Let's call them i, j, k.
mergeInOrder(array A, array B)
  1. Make an array C of size A.length + B.length.
  2. Let the integers i = 0, j = 0, k = 0. /* they will be indices of A, B, C, respectively */
  3. WHILE i < A.length AND j < B.length DO THIS
    1. IF current A[i] < B[j]
      THEN C[k] = A[i]; increment k, i;
      ELSE C[k] = B[j]; increment k, j;
  4. /* If A run out first, put the rest of B in C */
    1. WHILE (j < B.length) DO THIS
      1. C[k] = B[j]; increment k, j;
  5. /* If B run out first, put the rest of A in C */
    1. WHILE (i < A.length) DO THIS
      1. C[k] = A[i]; increment k, i;
  1. Return C
And, we are pretty much done. This piece of pseudocode is very valuable, as we can directly translate it into (almost) any high-level languages: Java, C, Perl, python. It is much easier (and safer) to arrive at a code this way than by just writing a Java code on a blank screen (also known as "Debugging a Blank Screen").

Lab Grades

If your program did not compile on my machine, you probably got 0 or 5 (depending on whether you submitted a reasonably-looking screenshot).

Please visit my office hours. Grade disputes can only be done in person. To see why, please read my reasoning on the web.

In real-life programming, programmers write code, test their code, and ship the code to customers. Customers do not care how great the program run on the programmers' machines. They only care if the program works on their machines. This is why it is a responsibility of the programmers to make sure, and double check to really make sure, that the final version of their code will compile and work as expected. It is important to verify the submission, by making sure that you choose the right method to submit, that your email client has really sent that email, that you have attached all the needed files and nothing more, that you are using the "right" email client to do the job.

For this class, umail is a good choice. We are not too picky if you choose to send it from Gmail, Yahoo Mail, Hotmail, or other places. But if those websites act up, you are using it at your own risk. There was one time when Hotmail, with all its wisdom, truncates the lines in your java files for you if the lines are longer than a certain length. And this makes the code uncompilable. This is not really your fault, but it is your bad luck with Hotmail, which is the risk you have to take for having chosen to use it.

It also makes sense to keep record of your submission. That is, the mail may get lost, and you should be able to retain a credible proof that you did submit it on time. Saving the sent messages can save you a lot of troubles.

In some cases, the customers are just ... well ... dumb. You write a good program. The program works perfectly. But a customer insists that your program crashes his computer. It may turn out that, in fact, the customer happens to be kicking the power cord. It is not your fault at all.

In this case, you should provide a good customer service. Go to him/her in person and show him/her that your program does work. Ask him/her to prove that your program does not work. If you are not at fault (and if the customer is not too dumb), he/she will understand and you will win the argument. :)

For this class, as far as the grading is concerned, your graders are your customers. In real life, the customers may mean your boss, your peers, your professor, the Quality Assurance team, ... etc.

Tower of Hanoi

Take a look in your book, and these great resources:
http://www.cut-the-knot.org/recurrence/hanoi.shtml
http://en.wikipedia.org/wiki/Tower_of_Hanoi

We want to write the following method:

/**
* Prints the step-by-step instruction on how to solve the Tower of Hanoi problem.
* Specifically, tells the user how to move n disks from tower i to tower j, using tower k as a temporary tower.
*
* Assumes i, j, k are all different.
*/
private void solveHanoi(int n, int i, int j, int k);

For example solveHanoi(3, 1, 3, 2) will print the instruction on how to move 3 disks from the first to the third tower. The output will look like:
1 -> 3
1 -> 2
3 -> 2
1 -> 3
2 -> 1
2 -> 3
1 -> 3

How do we write this method? Let's think about an easy case first. If n = 0 (or less than 0), there is nothing to do. Just return without printing anything. If n = 1, we can just move the disk directly from tower i to tower j, so just print i -> j and return.

For all other cases (n > 1), we need to somehow move n-1 disks from tower i to the temporary tower k first, then move 1 disk from tower i to tower j. Finally, we move the n-1 disks we deposited on the temp tower k forward to tower j. Note that the description given here depends on a smaller number of disks. So we can recursively call solveHanoi to solve the problem because n will eventually reach 1 or 0.

The solution looks like:


/**
* Prints the step-by-step instruction on how to solve the
* Tower of Hanoi problem.
*
* Specifically, tells the user how to move n disks from tower i to tower j,
* using tower k as a temporary tower.
*
* Assumes i, j, k are all different.
*/
private void solveHanoi(int n, int i, int j, int k) {
if (n <= 0) return;
if (n == 1) {
System.out.println(i + " -> " + j);
return;
}

/** we may now assume n > 1 */
solveHanoi(n-1, i, k, j);
solveHanoi(1, i, j, k);
solveHanoi(n-1, k, j, i);
}


Try computing solveHanoi(3, 1, 3, 2) on paper. See if the result looks the same as above.

This problem is a classic example of the use of recursion. It is possible to solve this without recursion, but it is much easier this way.

Sierpinski Gasket

See http://en.wikipedia.org/wiki/Sierpinski_triangle

Let's attempt to write a pseudocode for the following function:
/**
* Draws a Sierpinski Gasket whose 3 corners are p1, p2, p3. Stops when p1 and p2 are "too close" -- having distance less than 3.
* Assumes we have this global variable:
* Graphics2D g2;
* Everything should be drawn onto g2.
*/
private void drawSierpinski(Point p1, p2, p3);

Our strategy will be as follows: we first compute the distance between p1 and p2. If they are too close, then return right away.

If not, then we first draw a normal, boring triangle with vertices p1, p2, p3. Then we subdivide the lines -- finding the midpoints between p1 & p2, p2 & p3, and p1 & p3. Call these midpoints p12, p23, and p13 respectively. Now, we can recursively call drawSierpinski(p1, p12, p13); drawSierpinski(p2, p12, p23); drawSierpinski(p3, p13, p23); And, well, we're done!

How does this work? It works because at each step, we do our job of drawing at this certain resolution, and use recursion to draw the sub-triangles at the finer resolution. Our base case is when the points are too close together. Each step of calling moves the points closer and closer to one another, so eventually it will reach the base case.

As we have convinced ourselves with this idea, we can write the following pseudocode:
private void drawSierpinski(Point p1, p2, p3);
  1. Compute distance between p1 and p2.
  2. If distance < 3, return;
  3. Draw a boring triangle (p1, p2, p3).
  4. Compute the midpoints p12, p23, and p13
  5. Make recursive calls.
Then, we refine it:
private void drawSierpinski(Point p1, p2, p3);
  1. double d = squareRootOf( (p1.x-p2.x)^2 + (p1.y-p2.y)^2 );
  2. IF d < 3 THEN return;
  3. /* Draw a boring triangle (p1, p2, p3). */
    1. Draw line p1 - p2
    2. Draw line p1 - p3
    3. Draw line p2 - p3
  4. /* Compute the midpoints p12, p23, and p13 */
    1. /* Compute p12 */
      1. p12.x = (p1.x + p2.x) / 2.0;
      2. p12.y = (p1.y + p2.y) / 2.0;
    2. blah... (for p23)
    3. blah blah... (for p13)
  5. /* Make recursive calls. */
    1. drawSierpinski(p1, p12, p13);
    2. drawSierpinski(p2, p12, p23);
    3. drawSierpinski(p3, p13, p23);
and that's pretty much the code! (except for the blah blah part :P)

To print this note, visit:
http://docs.google.com/Doc?id=ddm3gthj_689d8f53

Monday, February 26, 2007

Lab Grades

Dear Students:

If you are not satisfied with your lab grade (that was graded by me), especially for the functionality part, please read this email.

Grade disputes can be done in person by visiting my office hours: Thursday from noon - 3pm at Phelp 1413. If you cannot come in during that time, you can grab me after my discussion session on Wednesday from 4-5pm at Phelp 1445. If you still cannot make it, we can make an appointment.

In general, there will be a standard 10 points deduction for the "CODE DOES NOT COMPILE" or "CODE NOT EMAILED" situation. But if you need to change your code a lot, the deduction can be more. Of course, if you can show me that it is not at all your fault, then you will get your points back without a deduction, plus an apology from me :) (and probably some chocolate, if I still have some.)

I cannot re-grade your program by email because
  1. I've already graded it, and already found that it did not compile or function properly. (Please read my comment in your lab paper.)
  2. I need to show you that it really does not work. And you need to show me that, with minimal code change, you can make it work. This is easiest done in person, especially when there are many students with different circumstances.
  3. I need to make sure you understand the seriousness of, among other things, the "CODE DOES NOT COMPILE" situation. In real-life work, it usually does not matter if your program compiles and works on your machine. What matters is whether your program compiles and works on your customer's (or boss', or professor's, ...) machine. Therefore, it is of great importance to check and re-check to make sure that your submission will work as expected.
  4. I need to note the new points on your paper and take it back to Prof Carlin to record it.

For your information, the most common mistakes are:
  1. You did not include all the needed files.
    When I grade your code, I download your files into an empty directory, and run
    javac *.java
    If there is an error because it is missing some files (such as Mover.java), then it does not compile.
  2. You included too many files, and some of them do not compile.
    You may have edited some code and you decided you no longer need it. Do not include it in your submission, since
  3. You decided to put comments in at the last minute, and you did not test it after that.
  4. You put your code in a package, which requires a directory structure.
    Most likely, the IDE did this for you. Make sure you set it up properly.
  5. You forgot to turn it in.
  6. You turned it in, but you did not include your full name and lab number in the subject line.
  7. You turned it in properly, but the email got lost.
    For this, I will need to ask for a proof.

- Mock

Sunday, February 25, 2007

homework 1

Homework 1 is graded. If you submitted it on time, you will get it back soon.

Please review the solution and look at my comments -- even if you've got a good grade. Sometimes, there are minor mistakes that worth a note, but I didn't always take off points.

Grade dispute can be done in person during office hours, or by appointment.

These are some problems many people made mistakes on:

Problem
Comments
2b
The answer is "EMPTY STRING". Please note that there is a difference between null and empty strings.
2c
The answer is "STATIC". Normally, when we have a non-static method inside a class C, we have to call it by
_variableName.methodName();

where _variableName is a variable of type C. We cannot simply call:
C.methodName();

unless the method is static.
5a
javax.swing.JApplet is extended to create an applet. JFrame is not the correct answer. JFrame is used to create a window for a java application.
5g
The answer can be: blueprints, guides, stamps, models, cookiecutters.
9c
An algorithm is a set of steps leading to a result. Pseudocode can help develop an algorithm because it focuses on the steps, not the language.

An algorithm is NOT a process of refining pseudocode. An algorithm is a process of solving a problem. Pseudocode is used to describe an algorithm.
9e
To write a loop, one must not forget to set an initial value to the counter.
10c
Many of you wrote that in a sentinel-controlled repetition, the number of times the code is repeated depends on user's input. This is not wrong, but not entirely true. It could depend on a lot of other things: e.g. result of a calculation, random number, state of the machine, network data.

Please also check my calculation on the cover page. In summing up your scores, I may have made some mistakes. My apology if that really happens. :)

- Mock

Midterm Review

Midterm 3

Monday 2/26/07

Topics:

Chapters 7 & 8

How it works: bouncing ball program

Timer, Mover, MoveTimer

BorderLayout, FlowLayout, Button

Let’s review the bouncing ball app

BouncingBallApp

BouncingBallPanel

BouncingBall

Mover

MoveTimer

SmartEllipse

BouncingBallApp

Wrapper of the BouncingBallPanel

Doesn’t do much

BouncingBallPanel

implements Mover

So there must be a move() method

Objects contained:

a BouncingBall

a MoveTimer

Important methods:

paintComponent

move -- has to call repaint()

BouncingBall

extends SmartEllipse

Method move() – override or overload?

Mover

A simple interface

Why do we need this?

What if we don’t have this, can we still do the job? What do we need to modify?

Specifies one method

Can we make this into an abstract class?

What could be a problem?

MoveTimer

extends javax.swing.Timer

Concepts of inner class

SmartEllipse

Same thing you had before.

Layouts

BorderLayout, FlowLayout

Thursday, February 22, 2007

Notes from Week #6

Topics
  1. Lab5
    1. your grades
      If you get 0-5 points on functionality, your program probably doesn't compile. But don't cry. If you can visit my office hours and show me that, with minimal tweaking on your code, you can make it compile and work, you will get some points back.
    2. how it works
      Even though you didn't get it, you should still make sure you understand how it works. Take a look at the solution. Talk to other people. Visit the TAs or Prof Carlin. We are more than happy to help you. This lab contains several important concepts (for your skills, for the exam, for life, ...)
  2. Future labs
    1. Lab 6 - Modifying the ClickApp program.
    2. Lab 7 - Recursively drawing a fractal.
  3. More on arrays
    1. mergeInOrder
      We partially implemented the method mergeInOrder that we introduced last week.

      /**
      * Merge the sorted array a and b together, putting the elements in correct order
      *
      * @param a a non-null ascendingly sorted array
      * @param b another non-null ascendingly sorted array
      * @return
      * a new array of size a.length + b.length containing elements from
      * a[] and b[] in ascendingly sorted order.
      */
      private int[] mergeInOrder(int[] a, int[] b) {
      int la = a.length;
      int lb = b.length;
      int[] c = new int[la+lb];
      int i = 0, j = 0, k = 0;

      while ((i < la) && (j < lb)) {
      if (a[i] < b[j]) {
      // a wins!
      c[k] = a[i];
      i++;
      k++;
      } else {
      // b wins!
      c[k] = b[j];
      j++;
      k++;
      }
      }

      return c;
      }

      We have not finished this method, yet. Why? Because we only take care of the case where both a and b still have some element(s) left to compare. In case we run out of elements on array a, we will also have to put the rest of elements on array b on the output array c. Or elements on array b could run out first, we also have to take care of that.

      Finishing this method is left as an excercise. Email me your solution. The first person who gets it right will get 1 big Hershey's bar (leftover from last Valentine's).

    2. productExcept

    3. Last week I introduced a method called product. The name was a bit misleading so I am renaming it to productExcept. We solved this problem together and came up with this nested-loop solution:

      /**
      * Computes a new array where the i-th element is the product of all elements in array a
      * except a[i]. For example, if a = {1, 2, 3, 4} then
      * productExcept(a) = {24, 12, 8, 6}
      *
      * @param a a non-null array of integers
      * @return
      * an array b of the same size as a where,
      * with n being the size of a,
      * b[i] = a[0]*...*a[i-1]*a[i+1]*...*a[n-1]
      * for every i from 0 to n-1
      */
      private int[] productExcept(int[] a) {
      int la = a.length;
      int[] b = new int[la];
      for (int i = 0; i < la; i++) {
      b[i] = 1;
      // we will compute the value of b[i]
      for (int j = 0; j < la; j++) {
      if (j != i) {
      b[i] = b[i] * a[j];
      }
      }
      }
      return b;
      }

      This solutions takes quadratic time in the size of input. If we have 100 input elements, it loops about 10,000 passes (not too bad). If we have 10000 input elements, it loops about 100 million passes (quite bad). Is there another solution where it takes linear time to run?

      The answer is yes. One idea is to multiply everything together in the first place. And, as we loop through b, we set b[i] = (the product)/a[i]. This solution seems correct, but may have a few problems: i) division by zero, ii) round-off errors in case of floating points, iii) arithmetic overflow.

      Is there a good solution without division? This was an interview question I got last year from Google. If you have a good idea for this, email me and you will get 1 big Hershey's bar. If you email me the working code, you will get 2 big Hershey's bars. Supplies are limited :) Act fast.

  4. Recursion
    1. Tower of Hanoi

    2. We introduced a game called the Tower of Hanoi and presented a rough idea on how to tackle this problem, and how to think recursively.
    3. Fractals
      1. Sierpinski gasket
      2. Fractal Tree
      3. Koch snowflakes

Wednesday, February 14, 2007

IMPORTANT: Office hours moved!

Tomorrow (2/15/07), Mock's office hours are rescheduled to:
6pm - 9pm
same place (Phelp 1413)

I can stay longer after 9pm as needed. Bring a pillow and sleeping bag if you want.
;)

This change is a result of the votes from the discussion session today, and it is temporary. His office hours for the following weeks will still be the same (12pm-3pm).

Notes from Week #5

Java Arrays



private int[] myArray;

private void printAll(int[] a) {
for (int x : a) {
System.out.print(x + " ");
}
System.out.println();
}

public static void main(String[] args) {
myArray = new int[10];
a[0] = 10;
a[1] = 9;
a[2] = 8;
...
a[9] = 1;
printAll(myArray);
}


Write these methods:


/** returns index k such that a[k] == x
* but if x is not in a, then returns -1
*/
private int findInArray(int[] a, int x);

/** returns the maximum value of the elements in a
*/
private int findMaxValue(int[] a);

/** returns the minimum value of the elements in a
*/
private int findMinValue(int[] a);

/** Returns a new array whose elements are a reversal of array a
* For example, if a = [1 2 3 4 5]
* then reverseArray(a) = [5 4 3 2 1]
* Array a should not be modified.
*/
private int[] reverseArray(int[] a);

/** Merge a and b together, put a first, then b
*/
private int[] mergeArrays(int[] a, int[] b)

/** Assume a and b are sorted in ascending order
* Returns the merged array in sorted order.
*/
private int[] mergeInOrder(int[] a, int[] b)

/** Returns array b such that
* b[i] = products of all elements in a except a[i]
*/
private int[] product(int[] a)


Note: the last 2 problems are similar to Google's interview questions.

Random

What if you want to make an array of size 10 that contains 10 random integers between 1 and 100?

We use:
public static double random()
Returns:
a pseudorandom double greater than or equal to 0.0 and less than 1.0.

int[] a = new int[10];
for (int i=0; i<10; i++) a[i] = (Math.random()*100)+1;


Would that compile? What did we miss?

Tuesday, February 13, 2007

Happy V-Day

Chocolates to everyone who attends the discussion session tomorrow. Big Hershey's bars to those who actively participate.
:)

- mock

Monday, February 12, 2007

Please turn in your code for Lab 4 as soon as possible

Even if you have turned in the report, we still need to compile and actually run your code.

Thanks,

-Shaomei

Wednesday, February 7, 2007

About Lab 4

1. As Mock has mentioned before, please turn in ALL your code by email as well. Put your main method in SketchApp.java file. It is your responsibility to make sure that they are compilable. I will definitely compile, run (java SketchApp) and test every program.
2. You also need to print out all your code and attach that in your lab report. Please be careful about the line truncation, which will effect my impression on the code.
3. UML diagrams are important to show your design and program structure. I will be strict with them this time, but not picky.

Good luck in midterm II and any question is welcome!

-Shaomei

Notes from Week #4

Announcement:
  • Lab 3 is graded. Please see this blog if you have questions about grading. If you still have questions, please visit my office hours. For those whose functionality points were severely deducted, you may still be able to get some points back by visiting my office hours. Requests for regrading must be done in person, so you can show me that your program really works.
  • Lab 4 is due this Friday (2/9). Shaomei will be your grader.
  • Lab 5 is due next Friday (2/16). I will be your grader.

Recursive Programs: What does the following program print?


private int f(int x) {
if (x==0) return 1;
else return x * f(x-1);
}

private int a(int m, int n) {
if (m==0) return n+1;
if (n==0) return a(m-1, 1);
return a(m-1, a(m, n-1));
}

public static void main(String[] args) {
System.out.println(f(5));
System.out.println(a(3, 1));
}



Lab 4: Augmenting the SketchApp program in the text (Page 169). Please visit this blog often to see if there are any updates/hints. You should already know all the needed concepts. It's just a little (?) more work than Lab 3.

Lab 5:
A little animation involving the bouncing ball program (Chapter 7 of the text). You've already had everything needed. You just need to study the original program.

Good styles:

What is a good style?

  1. This is a good style that I personally like. It's the standard java style. Many companies also like this style:
    Code Conventions for the JavaTM Programming Language
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

  2. The textbook is a good style.
  3. Many, many other styles...

What are important?
  • One class per file (... generally)
  • private/protected/public
    • The constructor should be public. The main method needs to be public. The accessors/mutators need to be public. The methods that other classes need to call may need to be public.
    • Make everything else as private as possible. If it can be private, make it private. If it cannot be private, maybe it can be protected (only subclasses can access)? Only when absolutely neccessary should you make an instance variable public.
  • Consistent indentation is very important for the readability of your program.
    • Different level of code should be at different depth of indents.
    • Same level of code should be at the same depth.
  • Line width should be limited to 80 charactors for good printing and viewing.

Suggestions:
  • Use spaces instead of tab. Set the tab stop to 2 or 4 spaces.
  • (Strongly suggested) Use an IDE or a good text editor. It can be painful to do good indentation in NotePad. I reccommend Eclipse, NetBeans, or Crimson Editor. Feel free to come to my office hours if you need help on setting up these programs.

Friday, February 2, 2007

Lessons from Lab3 grading

Lessons from Lab3 grading

Logistics
  • Do not forget to email all the code. Attach the files as attachments. When I grade your program, I download the files into an empty directory and do:
    javac *.java

    If, for any reason, there is an error in this step, it means that your program does not compile. This will be very bad for your grade. So it is your responsibility to verify everything. You must test your code before you submit. Once you have submitted, I suggest that you make a (temporary) empty directory, download the attachments into it, and test your program.

    This time I was more lenient. Some of you forgot to email the code or were missing some files. I only deducted 10 points and offered you a chance to resubmit.



  • To submit your lab, you should follow the instruction on this page:
    http://www.whizbangscholar.com/laboratory1.htm#General%20Instructions%20For%20Lab%20Reports
    In particular, you must "put your name and the Lab number (e. g. Lab 1) on the subject line." Otherwise, your submission may not be found.
  • AlienApp should contain the main method. Otherwise, it will be hard for me to look for your main class. (-5 if AlienApp is not found.)
    [update (2/5)]: Upon the second thought, I think this is unfair since the instruction on the lab sheet did not clearly specify which class should contain the main method. So I gave the 5 points back. If I miss anybody, please visit my office hours.
  • Do not forget to include the code listing of all classes.

Neatness
  • Bad handwriting is bad for your grade.
  • Some of you are confused between UML Diagram (showing containment) and class hierarchy diagram (showing inheritance). Please look into the book. Also, if we ask you to write 2 or more diagrams, please clearly label both of them.
  • Please use a fixed-width font for code listing. (Courier New is a good choice.) Please also make sure the font size is big enough, but not too big so that the lines get truncated or wrapped around. Do not print-screen the code. The quality is usually poor. Instead, print it out as text.
  • Color printing not necessary.

Coding Styles
  • Please make everything private unless it really needs to be public. If a subclass needs to read a variable, make it protected.
  • Please limit the lines' lengths to 80 chars (for nice printing and preventing truncation).
  • Limit the use of // comment, especially when it makes the line too long. Consider putting comments in another line. Use this style of /* comment */ instead for multi-line comment.
  • Indentation is important for the readability of your program. You can follow Prof Carlin's style or the book's style. Just pick one and be consistent.
  • One class per file: each class should be put in its own file.

Hall of Fame:
  • Very nice diagrams: Alvin Yip, Drew Martin, Christian Banzon
  • Francois Hebert: an army of 13 aliens
  • Steven Pease: 6 aliens with very amazing animation and interactions.

Wednesday, January 31, 2007

Notes from Week #3

Themes:
  1. Beware: local vs. global
  2. Overiding: which method is called?
  3. Overloading: which method is called?
  4. Static variables
  5. Recursion (we didn't get to this topic this time)

Example 1:

How big will you see the sun?

public class BigSun extends wheels.users.Frame {

private wheels.users.Ellipse e;
private int bigSize;

public BigSun() {
int bigSize = 200;

e = new wheels.users.Ellipse();
}

public void makeBig() {
e.setSize(bigSize, bigSize);
}

public static void main(String[] args) {
BigSun sun = new BigSun();
sun.makeBig();
}

}

Example 2:
What is wrong here? How to make it right? What does the output look like? What if we change changeSize in BlueSun to changeSize2 ?

import wheels.users.*;

public class Sun extends Frame {

private Ellipse e;

public Sun() {
e = new Ellipse();
}

public void changeSize() {
e.setSize(3,3);
}

}
----
import java.awt.Color;

public class BlueSun extends Sun {

public BlueSun() {
super();
e.setColor(Color.BLUE);
}

public void changeSize() {
e.setSize(200, 200);
}

public static void main(String[] args) {
BlueSun sun = new BlueSun();
sun.changeSize();
}

}

Example 3:
What is the output?

public class TestOverload {

private static int f(int x) {
return x*x;
}

private static int f(int[] a) {
return f(a[0]) + f(a[1]) + f(a[2]);
}

public static void main(String[] args) {
int x = 7;
int a[] = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;

System.out.println("The 1st result is " + f(x));
System.out.println("The 2nd result is " + f(a));
}

}

Example 4:
import java.awt.Color;

import wheels.users.*;

public class UglyAlien extends Ellipse {

private static Ellipse eye;

public UglyAlien() {
this.setSize(100, 100);
eye = new Ellipse();
eye.setFillColor(Color.WHITE);
eye.setSize(20, 20);
}

public void moveTo(int x, int y) {
this.setLocation(x, y);
eye.setLocation(x+40, y+40);
}

public void wink() {
eye.setSize(20, 5);
}
}

import wheels.users.*;

public class UglyAlienApp extends Frame{

public UglyAlienApp() {
UglyAlien a1, a2;

a1 = new UglyAlien();
a2 = new UglyAlien();

a1.moveTo(0, 0);
a2.moveTo(100, 0);

a2.wink();
}

public static void main(String[] args) {
new UglyAlienApp();
}

}


Note: the code on this post is badly commented. It's because of the blogger's thing... I'm too lazy to fix it. Do not follow this style. You should always indent your code nicely.

Thursday, January 25, 2007

Common Questions for Lab 2

Question:

Hi, I have a problem for cs10 Lab 2. Not a big problem, but I just
realized that whenever I run my program, it draws a red circle in the
middle of the frame...
Its no big deal, because everything else runs fine, but is there a way
to get rid of it?

Michael

Answer:

Hi Michael,

Yes, there is. It will be easy once I tell you how. But I should also
tell you why it works.

When you make the Alien class extends Ellipse, that means the Alien
itself is an Ellipse .. with some extra ellipses and maybe some
rectangles/lines. Inside the Alien constructor, you probably have a
statement like this...

face = new Ellipse();
face.setSize(...);
face.setLocation(...);

which creates a new Ellipse for variable face, resizes it, and puts it
at some location.

If you didn't call setSize() and setLocation(), what would happen?
Yes, the face will just be a red dot at the middle of the screen...

and that is exactly what is happening to your Alien's ellipse. So, to
fix this problem, you can make use of a special variable called "this"
(without the quotes) .. this refers to the class itself.

Since "this" is already an Ellipse, you do not need to create a new
Ellipse for the face. So, instead of saying

face = new Ellipse();

you can just say
face = this;

and then anything you do with the face, will be performed to the Alien
itself (which is initially a red dot).

Hope this helps!
- Mock

Wednesday, January 24, 2007

Notes from Week #2

Today I talked about Lab 2, giving clarifications and hints (as posted on the previous entry). I also presented a problem similar to Lab 2.

The problem is to write 2 classes SnowMan.java and SnowManApp.java so that SnowManApp will show 2 snowmen on the screen, one without a hat and the other with a hat.

We did the problem together on the board. Those who attended the discussion may have got a handful of hints for Lab 2 (due this Friday). Those who did not attend can come to my office hours tomorrow (Thurs: 12-3pm @ Phelp 1413) if they have questions.

Notes from Week #1:
Last week, we talked about different editors & IDEs you can use to develop your java program. I do not remember the full list, but popular ones (in my opinion) are listed here:

  • Text Editors
    • NotePad, DOS' edit
      Simple, fast, already available on your machine
    • TextPad
      Available on the labs' machines. If you want to use it on your machine, you will have to buy.
    • Crimson Editor
      Very nice, freely available at http://www.crimsoneditor.com/
      You can also use this tool to print out your code very nicely.
  • Integrated Development Environment (IDEs)
    • Eclipse
      Very popular, freely available at http://www.eclipse.org/
      You can use it for other programming languages, too.
    • NetBeans
      My choice. Specially designed for Java. Freely available at http://www.netbeans.org/
      It has a very nice GUI editing tool.
    • BlueJ
      Freely available at http://www.bluej.org/index.html
    • DrJava
      A lightweight IDE.
      Freely available at http://www.drjava.org/
      A light (Thanks to Kelly for her recommendation.)

Lab 2 clarification

Refered to: http://www.whizbangscholar.com/EB/010%20Lab%202%20W07%20B.pdf

There is a slight typo in the original lab write-up. On the line that says
public class
Alien extends wheels.users.Frame { ... }
It should have been
public class AlienApp extends wheels.users.Frame { ... }

In other words, the Alien class should NOT extend wheels.users.Frame. It does NOT need to extend anything. In fact, when write the Alien class, the header should be simply:
public class Alien { ... }

The AlienApp class, however, needs to "extends wheels.users.Ellipse".

You do not need to know what "extends" mean at this point. It has not been covered yet (but will be soon). If you are curious, read Chapter 3 on Inheritance.

QUESTION: Where should I put my main method?
Answer: The AlienApp class MUST have a main method. The Alien class does not need a main method.

QUESTION: How will my program be graded?
Answer:
We will do the following...
  • First, we will compile your program by...
    javac *.java
    If this creates an error, lots of points will be deducted. So, you must check to make sure there is no error at this point. If there is a "warning", minor points may be deducted.

  • Next, we will run AlienApp by
    java AlienApp
    If it doesn't run, or if it says the class is missing, or the main method is missing, your functionality points will be greatly affected (possibly zero!). So, make sure that AlienApp has a main method.

  • We will look at the result, we must see something like the following:

    That is, it must have 5 aliens on the same window. Note that alien #5 looks like alien #3 because he just winked and unwinked so rapidly our eye could not see.

    Your aliens don't have to look exactly like these. You may arrange them in a different ways -- just make sure we can see them all. Also, you can include your creativity by including a nose, a hat, ears, eyeglasses, body, ... whatever. Try to practice with different ways to draw things in wheels.

    If your program runs fine in this step, you will get a very good score.

  • We will try clicking on the alien face to see if you have implemented the extra credit.

  • Next, we will look at your code. You should submit only 2 classes:
    Alien.java and AlienApp.java
    If you have more files and they create errors, this may affect your score.

    We will look for the 4 methods specified in the lab write-up: moveTo, turnGreen, wink, and unwink.

    We will also look to see if you really made alien #5 wink and then unwink.

    Be sure to organize your code nicely. At least, you must indent your code, write your name and date at the top, include a short description of the program. Provide some comments.
QUESTION: I attempted the extra credit, but couldn't get mousePressed to work. Why?

You should put mousePressed method in Alien class. Also, modify the header of your Alien class to the following:

public class Alien extends wheels.users.Ellipse { ... }

This will make the Alien itself an ellipse which can be clicked by the user. However, it will create an extra red dot at the center of the screen. This is fine. When we click at the red dot, it will turn the alien to green & winked state.

Can you get rid of the red dot? (For the answer, visit my office hours -- Thurs 12-3pm @ Phelp 1413)

Even more fun: try to implement
public void mouseReleased(java.awt.event.MouseEvent e) { ... }

so that the alien only turn green and wink when the user holds down the mouse button. When the mouse button is released, the alien should turn white and unwinked again.

Contributors