Tuesday, April 24, 2007

Base-of-Pascal-Pyramid Problem

Some students asked me for hints about the second part of PA2. I think a good
way to give hints is to do a similar, but not so exact, example.

The following problem will be a good practice for your homework. We will do
this together in my discussion tomorrow (9-10am, Phelp 1448) after I finish
talking about ASCII & Unicode.

Consider the following problem. I call it "Base-of-Pascal-Pyramid Problem".

You start with a 5x5 array like this:
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0

At each step, for each cell, you sum up the value in that cell with its
4 neighbors (N, E, W, S) to get the new value.

So, the next few steps will be:

After step 1:
0 0 0 0 0
0 0 1 0 0
0 1 2 1 0
0 0 1 0 0
0 0 0 0 0

After step 2:
0 0 1 0 0
0 2 3 2 0
1 3 6 3 0
0 2 3 2 0
0 0 1 0 0

After step 3:
0 3 4 3 0
3 8 14 8 3
4 14 18 14 4
3 8 14 8 3
0 3 4 3 0

Given n > 0 as input, we want to know what the array will look like after
step n.

We start with a pseudocode:
1. Declare a 5x5 array, initialize it to look like the starting configuration.
Call this array currentArray.
2. Have a backup array called nextArray of the same size.
3. Use nested for loops with variables i, j to go through each element.
For each (i, j), figure out what nextArray[i][j] should be.
4. Copy the values in nextArray to currentArray.
5. For n times, repeat steps 3-4.

Then we can write the Java code off that pseudocode.

No comments: