Arrays: 2D Arrays Intro

2D Arrays

Screen Shot 2014-11-21 at 9.58.20 AM

Screen Shot 2014-11-21 at 10.03.51 AM

Additional programming style guidelines:

/* 
 * 1. Make sure your program has indentation when is needed.
 * 2. Please include a comment line about local variables and group them all 
 *    together at the top of the program as long as it is not an OOD program.
 * 3. Never create a new local variable inside a loop!
 * 4. Have a blank line between different parts of the program
 */

final int COUNTRIES = 7;
final int MEDALS = 3;
int[][] counts = new int[COUNTRIES][MEDALS];

or but not both:

int[][] counts = {
 { 1, 0, 1 }, 
 { 1, 1, 0 }, 
 { 0, 0, 1 }, 
 { 1, 0, 0 }, 
 { 0, 1, 1 }, 
 { 0, 1, 1 }, 
 { 1, 1, 0 }
 };
for (int i = 0; i < COUNTRIES; i++)
{
  // Process the ith row
  for (int j = 0; j < MEDALS; j++) 
  {
      // Process the jth column in the ith row
      System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); // Start a new line at the end of the row 
 }

Screen Shot 2014-11-21 at 10.09.23 AM

for (int i = 0; i < counts.length; i++) 
{
  for (int j = 0; j < counts[0].length; j++) 
  {
     System.out.printf("%8d", counts[i][j]); 
  }
  System.out.println(); 
}

Accessing the neighboring elements of a 2D array
Screen Shot 2014-11-21 at 10.11.40 AM

Screen Shot 2014-11-21 at 10.12.44 AM

Adding by rows:

int total = 0;
for (int i = 0; i < COUNTRIES; i++)
{
  total = 0;
  for (int j = 0; j < MEDALS; j++) 
  {
    total = total + counts[i][j];
  }
}

Screen Shot 2014-11-21 at 10.13.44 AM

Adding by columns:

int total = 0;
for (int j = 0; j < MEDALS; j++)
{
  total = 0;
  for (int i = 0; i < COUNTRIES; i++) 
  {
    total = total + counts[i][j]; 
  }
}

Classwork:
Write a program, MedalsTable_YI.java to produce the following output:

Screen Shot 2014-11-21 at 11.30.17 AM

Assignment:
Consider as an example an 8 × 8 array for a board game:
int[][] board = new int[8][8];

BoardGame_YI.java: Using two nested loops, initialize the board using "for" loops so that zeroes and ones alternate, as on a checkerboard. Prompt the user for the size of the "square" 2D array and display the board on the screen.

0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
...
1 0 1 0 1 0 1 0

Hint: Check whether i + j is even.

Input/Output: Origami Half Areas

If you fold a square diagonally, you will create a right isosceles triangle. We will take the triangle’s area to be 1. Continue to halve this triangle again and again by placing the acute angles on top of each other. Write a java program, HalfAreas_YI.java and prompt the user how many times wants the square to be folded.

As an example, let’s say the user’s response to the prompt is 5.

Output: in full sentence display the number of folds and the area of the final triangle.

Find an origami paper on the last table and do it manually first. Do the calculations so you can check your program is doing the right thing.

Once you confirm your program is running properly, run the program for an input of 7 folds. Submit both, the hand calculation, the output for the test and the solution for the 7 folds.

NOTE: if you are aware of finding the solution by using a formula, you can add that information to your documentation. For this assignment you must use loops.

First fold. Let the area of this triangle be 1.
Second Fold
Third Fold
Fourth Fold
Fifth Fold

Input/Output: Animation – RandomBlock_YI.java

Implement an animation, RandomBlock_YI.java. The CheckerBoard.java can easily be changed to randomly select a random number of squares on the grid and become a solid color (“alive”) and then randomly it will turn back to white (“dead”) again.

Re-Use-Code: these are good resources for this assignment:
‌MyGraphPaper.java
BouncingBall.java
CheckerBoard.java

/******************************************************************************
 *  Compilation:  javac Checkerboard.java 
 *  Execution:    java Checkerboard n
 *  Dependencies: StdDraw.java
 *
 *  Plots an n-by-n checkerboard.
 *
 ******************************************************************************/

public class Checkerboard { 

    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        StdDraw.setXscale(0, n);
        StdDraw.setYscale(0, n);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i + j) % 2 != 0) StdDraw.setPenColor(StdDraw.BLACK);
                else                  StdDraw.setPenColor(StdDraw.RED);
                StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5);
            }
        }
    }

}


Arrays: Making Magic Squares

Screen Shot 2014-12-07 at 12.13.44 PM

2D Arrays

Classwork/Homework:

  1. Implement the following algorithm to construct magic n × n squares; it works only if n is odd.Set row = n – 1, column = n / 2.
    For k = 1 … n * n
    Place k at [row][column].
    Increment row and column.
    If the row or column is n, replace it with 0.
    If the element at [row][column] has already been filled
    { Set row and column to their previous values.
    Decrement row.}

    Here is the 5 × 5 square that you get if you follow this method:

    Screen Shot 2014-11-23 at 9.53.37 PM

    Write a program, MagicNSquare_YI.java whose input is the number n and whose output is the magic square of order n if n is odd. Include the code to check the new array is in fact a Magic Square. Display the sum of the columns, rows and diagonals.

  2. (Financial tsunami) Banks lend money to each other. In tough economic times, if a bank goes bankrupt, it may not be able to pay back the loan. A bank’s total assets are its current balance plus its loans to other banks. The diagram in the figure below shows five banks. The banks’ current balances are 25, 125, 175, 75, and 181 million dollars, respectively. The arrow from node 1 to node 2 indicates that bank 1 lends 40 million dollars to bank 2.

    If a bank’s total assets are under a certain limit, the bank is unsafe. The money it borrowed cannot be returned to the lender, and the lender cannot count the loan in its total assets. Consequently, the lender may also be unsafe, if its total assets are under the limit. Write a program, BankFinancing_YI.java to find all the unsafe banks. Your program reads the input as follows. It first reads two integers n and limit, where n indicates the number of banks and limit is the minimum total assets for keeping a bank safe. It then reads n lines that describe the information for n banks with IDs from 0 to n-1.
    The first number in the line is the bank’s balance, the second number indicates the number of banks that borrowed money from the bank, and the rest are pairs of two numbers. Each pair describes a borrower. The first number in the pair is the borrower’s ID and the second is the amount borrowed. For example, the input for the five banks in the figure is as follows (note that the limit is 201):

    5 201
    25 2 1 100.5 4 320.5
    125 2 2 40 3 85
    175 2 0 125 3 75
    75 1 0 125
    181 1 2 125
    

    The total assets of bank 3 are (75 + 125), which is under 201, so bank 3 is unsafe. After bank 3 becomes unsafe, the total assets of bank 1 fall below (125 + 40). Thus, bank 1 is also unsafe. The output of the program should be

    Unsafe banks are 3 1
    
    

    (Hint: Use a two-dimensional array borrowers to represent loans. borrowers[i][j] indicates the loan that bank i loans to bank j. Once bank j becomes unsafe, borrowers[i][j] should be set to 0.)

If you are done with every assignment, here is the next topics

PU Input and Output Standard classes

Book site
Screen Shot 2015-02-23 at 12.19.21 AM

Lesson’s pdf
Screen Shot 2015-11-22 at 4.48.06 PM

Create a new project:
InputOutput
You can get the following files from edmodo.com. Add them to your workspace:

StdIn.java
StdOut.java
StdDraw.java
StdAudio.java

Arrays 2D: Minesweeper

Screen Shot 2014-12-07 at 12.13.44 PM

minesweeper

youtube “how-to”

Write a program Minesweeper_YI.java that takes 3 input arguments m, n, and p and produces an m-by-n boolean array where each entry is occupied with probability p. In the minesweeper game, occupied cells represent bombs and empty cells represent safe cells. Print the array using an asterisk for bombs and a period for safe cells. Then, replace each safe square with the number of neighboring bombs (above, below, left, right, or diagonal) and print the solution.

HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.2
. . . 
. . . 
* . . 

0 0 0 
1 1 0 
* 1 0 


Try to write your code so that you have as few special cases as possible to deal with, by using an (m+2)-by-(n+2) boolean array.

HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.3
. . * 
. . * 
. . * 

0 2 * 
0 3 * 
0 2 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.4
. . . 
* . . 
. . . 

1 1 0 
* 1 0 
1 1 0 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.5
* * * 
. * * 
* . * 

* * * 
4 * * 
* 4 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.6
* * * 
. . * 
* * * 

* * * 
4 7 * 
* * * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.7
. * * 
* * * 
* . * 

3 * * 
* * * 
* 5 * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.8
* . * 
* * . 
* * * 

* 4 * 
* * 4 
* * * 
HS-TEACHER-17464:Array2D gracielaelia$ java Minesweeper 3 3 0.9
* * * 
* * . 
* * * 

* * * 
* * 5 
* * *

Required Submission:

  1. Copy and paste the program (with the output as a paragraph comment at the end of your program) to the Text entry tab.

  2. Submit the file with the ‘”java” extension.

3. Make sure you document code snippets that have a particular purpose!

4. Testing: Have multiple boards with different board sizes and different probabilities. The minimum should be 3 boards.


					

Arrays: Game of Life

Game Of Life:

If you have successfully completed the random block program and written the draft for the algorithm in pseudocode, you should be able to get started with the game of life assignment.

Start small. Hardcode the seed for the glider:

Requirements:
1. Take as input the size of the grid.
2. Show the live cells in color other than black.

Challenges:
1. Take as input the coordinates for the seed. You must include in your documentation the coordinates for the glider seed.
2. Change the color of the dead cells to a faded color for at least one generation after dying.
3. Take as input the option to speed or slow down the simulation.

Arrays: Connect Four

Game: Connect Four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.

The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before an opponent can do likewise. The program prompts a player to choose a color disk. Then the computer and the player will drop a red or yellow disk alternately. In the figure, the player with the red disk is the winner of the game.

This implementation is text based. Take a look a the simplicity of the format. This will enable you to concentrate on the algorithm and the strategy you need to implement to have the computer to win. Let’s develop the “computer to win” a bit further. You do not want to play against an infallible player (the computer) because you will not even want to play the game. So a better approach would be a good blend of random moves with smart moves. You decide how “smart” the computer is.

Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). Here is a sample run:

Let's assume the user is controlling the red disk,

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
———————————————

Drop a red disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
———————————————

Computer drops a yellow disk at column 4

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | |Y| | |
.
.
.
.

Computer drops a yellow disk at column 6 

| | | | | | | |
| | | | | | | |
| | | | |Y| | |
| | | |Y|Y|Y|R|
| | |Y|R|R|Y|Y|
|R|Y|R|Y|R|R|R|
———————————————
The computer won
Do you want to play again?
  1. Write a one-player program, Connect4TwoD_YI.java using 2D array. Display at a every move the board as shown in the example above. Include a prompt to continue playing.
  2. Write a one-player program, Connect4OneD_YI.java using only 1D array. Display at a every move the board as shown in the example above. Include a prompt to continue playing. This is a bit more complex but you will find a pattern to help you implement it.

Little help #1: Use paper and pencil to design, trace and test your algorithm before you start.
Little help #2: You can use static methods (functions) to make the code more readable and easier to manage. This is only optional.

Arrays: Connect 4 Algorithm – 2D Arrays

Let’s not just connect 4. Let’s connect what you have learned about arrays and everything that brought you to this point to develop your first AI game in java.

  1. What does “your” simplified flowchart for a game look like?
Invent With Python – https://inventwithpython.com/invent4thed/chapter7.html

2. Let’s talk about “your” algorithm.

Let’s play the game

Red is the player – Blue is the computer
Answer the following questions
1. How would your program select the next move?
2. When would your program choose to make a random move?
3. When would your program make an intelligent move?
4. If the red ball numbered 1 was the first move, can you trace the following steps up to this point?
5. Can you make an educated guess as to how many different ways?

3. Use your “Toolkit” from previous lessons:

2D Arrays Intro

  1. You learned how to add rows:

    int total = 0;
    for (int i = 0; i < COUNTRIES; i++)
    {
      total = 0;
      for (int j = 0; j < MEDALS; j++) 
      {
        total = total + counts[i][j];
      }
    }
    

  2. You learned how to add columns:
    int total = 0;
    for (int j = 0; j < MEDALS; j++)
    {
      total = 0;
      for (int i = 0; i < COUNTRIES; i++) 
      {
        total = total + counts[i][j]; 
      }
    }
    

And accessing the neighboring elements of a 2D array

and from Magic Square

You learned how to add diagonals:

sum = 0;
for (int i = 0; i < square.length; i++) {
            sum += square[i][i];
        }

sum = 0;
        for (int i = 0; i < square.length; i++) {
            sum += square[i][square.length-i];
        }

4. Add details to your simplified flowchart. Let's develop the "computer to win" a bit further. You do not want to play against an infallible player (the computer) because you will not even want to play the game. So a better approach would be a good blend of random moves with smart moves. You decide how "smart" the computer is.

5. Levels of difficulty. Choose the "Medium" level of difficulty and start the same as in the first game. Do the same for "Hard" level and compare to easy and medium. How different are the behaviors of the "computer" moves? Can you find a pattern?

Arrays – Connect Four

Classwork/Homework:
(Game: connect four) Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.

connectfour

The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a red or yellow disk alternately. In the preceding figure, the red disk is shown in a dark color and the yellow in a light color. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). Here is a sample run:

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
———————————————

Drop a red disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
———————————————

Drop a yellow disk at column (0–6): 4

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | |Y| | |
.
.
.
.

Drop a yellow disk at column (0–6): 6 

| | | | | | | |
| | | | | | | |
| | | | |Y| | |
| | | |Y|Y|Y|R|
| | |Y|R|R|Y|Y|
|R|Y|R|Y|R|R|R|
———————————————
The yellow player won
Do you want to play again?

Write the two-player program, YI_Connect4.java. Display at a every move the board as shown in the example above. Include a prompt to continue playing.

Your program should include:
1. Good documentation
2. An introduction message
3. Functions (Optional)
4. An end of game message
5. Input/output

What is good documentation?
Answer:

  1. Header with author’s name, assignment description, date and python version.
  2. Comments in each function. A short sentence will be sufficient.
  3. Comments for code snippets written for specific handling. An example might be checking if there are 3 in a row, or 4 in a row.
  4. Comments to indicate unusual or rare situations that don’t follow a pattern or repetition.