Category Archives: Lesson

Input/Output: Graphics and Arrays: A Bar graph – Tracing

Let’s do some tracing with a smaller set of positive integers.

raw data array
{4,5,6,5,5,12,4,5,4,5,4,4,11,5,…} 100 random positive integers of range 1 to 20 inclusive

the goal in this assignment is to have the least number of “if” statements (if any at all)

the counter array initialy all elements are equal to ZERO — this is an array of 20 elements
counter array
{0,0,1,0,5,5,….} this is going to be the height of the rectangle

i: 0 –> 20 barCounter[0,0,0,0,0,0,0,0,0,..]

barCounter[rawData[i]]++

i = 0
rawData[0] –> 4
barCounter[rawData[0]]++
barCounter[4]++ –> 1 barCounter[0,0,0,0,1,0,0,0,0,..]

i = 1
rawData[1] –> 5
barCounter[rawData[1]]++
barCounter[5]++ –> 1 barCounter[0,0,0,0,1,1,0,0,0,..]

i = 2
rawData[2] –> 6
barCounter[rawData[2]]++
barCounter[6]++ –> 1 barCounter[0,0,0,0,1,1,1,0,0,..]


i = 3
rawData[3] –> 5
barCounter[rawData[3]]++
barCounter[5]++ –> 2 barCounter[0,0,0,0,1,2,1,0,0,..]

i = 4
rawData[4] –> 5

barCounter[5]++ –> 3 barCounter[0,0,0,0,1,3,1,0,0,..]

i = 20 [0,1,0,0,1,6,9,0,18,19,17……,1,1] // height of
//each rectangle
// the index is the x coordinate of the bargraph rectangle
for ( int i = 0; i < 100; i++)
barCounter[rawData[i]]++;

for loop to draw the rectangles where x is the index of barCounter array
and y is the value of the array barCounter with index x

// a short program to trace it with print statements
public class bargraph0
{
    public static void main(String [] args)
    {
        int raw = 0;
        int counter =0;
      int [] rawData = {4,5,6,5,5,12,4,5,4,5,4,4,11,5};
      int [] barCounter = new int[13]; // since 12 is the max value
      for ( int i = 0; i < rawData.length; i++)
      {
          System.out.println("i " + i + " rawData " + rawData[i]);
            barCounter[rawData[i]]++;
            raw = rawData[i];
            counter = barCounter[rawData[i]];
            System.out.println("barCounter array");
            for ( int j = 0; j < barCounter.length; j++)
            {
                System.out.print(barCounter[j] + " ");
            }
            System.out.println();
        }
    }
    
}
Take a look at the output:
Inital  state of the barCounter array
0 0 0 0 0 0 0 0 0 0 0 0 0 
Loop with i from 0 to 13
i 0 rawData 4
barCounter array
0 0 0 0 1 0 0 0 0 0 0 0 0 
i 1 rawData 5
barCounter array
0 0 0 0 1 1 0 0 0 0 0 0 0 
i 2 rawData 6
barCounter array
0 0 0 0 1 1 1 0 0 0 0 0 0 
i 3 rawData 5
barCounter array
0 0 0 0 1 2 1 0 0 0 0 0 0 
i 4 rawData 5
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 0 
i 5 rawData 12
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 1 
i 6 rawData 4
barCounter array
0 0 0 0 2 3 1 0 0 0 0 0 1 
i 7 rawData 5
barCounter array
0 0 0 0 2 4 1 0 0 0 0 0 1 
i 8 rawData 4
barCounter array
0 0 0 0 3 4 1 0 0 0 0 0 1 
i 9 rawData 5
barCounter array
0 0 0 0 3 5 1 0 0 0 0 0 1 
i 10 rawData 4
barCounter array
0 0 0 0 4 5 1 0 0 0 0 0 1 
i 11 rawData 4
barCounter array
0 0 0 0 5 5 1 0 0 0 0 0 1 
i 12 rawData 11
barCounter array
0 0 0 0 5 5 1 0 0 0 0 1 1 
i 13 rawData 5
barCounter array
0 0 0 0 5 6 1 0 0 0 0 1 1 
i 0 rawData 4
barCounter array
0 0 0 0 1 0 0 0 0 0 0 0 0 
i 1 rawData 5
barCounter array
0 0 0 0 1 1 0 0 0 0 0 0 0 
i 2 rawData 6
barCounter array
0 0 0 0 1 1 1 0 0 0 0 0 0 
i 3 rawData 5
barCounter array
0 0 0 0 1 2 1 0 0 0 0 0 0 
i 4 rawData 5
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 0 
i 5 rawData 12
barCounter array
0 0 0 0 1 3 1 0 0 0 0 0 1 
i 6 rawData 4
barCounter array
0 0 0 0 2 3 1 0 0 0 0 0 1 
i 7 rawData 5
barCounter array
0 0 0 0 2 4 1 0 0 0 0 0 1 
i 8 rawData 4
barCounter array
0 0 0 0 3 4 1 0 0 0 0 0 1 
i 9 rawData 5
barCounter array
0 0 0 0 3 5 1 0 0 0 0 0 1 
i 10 rawData 4
barCounter array
0 0 0 0 4 5 1 0 0 0 0 0 1 
i 11 rawData 4
barCounter array
0 0 0 0 5 5 1 0 0 0 0 0 1 
i 12 rawData 11
barCounter array
0 0 0 0 5 5 1 0 0 0 0 1 1 
i 13 rawData 5
barCounter array
0 0 0 0 5 6 1 0 0 0 0 1 1 
Final state of the barCounter array.

Input/Output: Animation: DeluxeBouncingBall.java

Screen Shot 2015-02-23 at 12.19.21 AM

Standard Drawing: Animation and images
Images. PU standard draw library supports drawing pictures as well as geometric shapes.

  • Images. Our standard draw library supports drawing pictures as well as geometric shapes. The command StdDraw.picture(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y).
  • Resources:
    https://introcs.cs.princeton.edu/java/15inout/TennisBall.png 
    https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
  • User interaction. Our standard draw library also includes methods so that the user can interact with the window using the mouse.
    double mouseX()          return x-coordinate of mouse
    double mouseY()          return y-coordinate of mouse
    boolean mousePressed()   is the mouse currently being pressed?
    
      • A first example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan. A simple attractor. OneSimpleAttractor.java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag force.
      • Many simple attractors. SimpleAttractors.java simulates the motion of 20 blue balls that are attracted to the mouse. It also accounts for a drag force. When the user clicks, the balls disperse randomly.
      • Springs. Springs.java implements a spring system.

    Standard audio.

    StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound.

    We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing.

    • Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the x-axis, so if we measure t in seconds and plot the function sin(2πt × 440) we get a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the volume. We assume it is scaled to be between −1 and +1.
    • Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic scale, and we get the ith note above a given note by multiplying its frequency by the (i/12)th power of 2.

    • When you double or halve the frequency, you move up or down an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A.
    • Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curve—a widely used sampling rate is 44,100 samples per second. It is that simple: we represent sound as an array of numbers (real numbers that are between −1 and +1).
    •  

    For example, the following code fragment plays concert A for 10 seconds.

    int SAMPLING_RATE = 44100;
    double hz = 440.0;
    double duration = 10.0;
    int n = (int) (SAMPLING_RATE * duration);
    double[] a = new double[n+1];
    for (int i = 0; i <= n; i++) {
       a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLING_RATE); 
    }
    StdAudio.play(a);
    • Play that tune. PlayThatTune.java is an example that shows how easily we can create music with StdAudio. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.

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.

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: Students Show and Tell

Welcome back!!
new-year-gif
Class activity:
Discussions and students’ presentations about the following assignments:
StdIn/StdOut – Hwk 12/3 -YI_Duplicates.java
StdDraw – Hwk 12/4 – YI_TriangleTess.java
StdDraw – Clwk 12/4 – YI_MyGraphPaper.java
StdDraw – Hwk 12/7 – YI_SongLyrics.java
StdDraw – Clwk 12/8 – YI_Histogram.java

Homework:
1 Question on edmodo.com
Work on missing assignments.

Midterm Review Part 1

Content for some questions:

  1. Overflow

From

The int data type is a 32-bit signed two’s complement integer. It has a minimum value of -2,147,483,648 (0x80000000) and a maximum value of 2,147,483,647 (0x7FFFFFFF) (inclusive)

So when you add one to an integer’s max value:

0x7FFFFFFF + 0x00000001 = 0x80000000 (-2,147,483,648)

Arrays: Intro

Screen Shot 2014-11-11 at 7.17.48 AM

Screen Shot 2014-12-07 at 12.13.44 PM

  • Typical array-processing code.
  • Programming with arrays.
    • Zero-based indexing
    • Array length
    • Memory representation
    • Bounds checking
    • Setting array values at compile time
    • Setting array values at run time
  • Shuffling and sampling
    • Exchange
    • Shuffling
    • Hardwired constants
    • Sampling without replacement

 

classwork:
Write a program, ArrayBasics_YI.java to do the following:

  1. Create an array a[] size 10. Assign a random number between 1 and 30 to each element.
    a. Display the first element of the array.
    b. Display the last element of the array assuming you do not know the size of the array.
    c. Display the messages given when you try to access an element with a negative index and with an index beyond the size of the array.
  2. Create two arrays, suit[] and face_value[].
    a. The suit[] array contains the 4 different suits as elements.
    b. The face_value array contains “2”, “3”,…,”Jack”,…,”Ace” elements.
    c. Use the random function to select five cards and display them.
  3. Create two arrays x[] and y[] with N number of elements both. Prompt the user for N. Assign random integers to each element. Then have another loop to find the product of each element wit the same index and add them all together. This operation is called the “dot product”.

Assignments:
ClosestPair_YI.java
Write a program to create an array of 100 random integers between the values of 1 and 1000 and find the two consecutive integers with the smallest difference between the two of them.

MaxInArray_YI.java
Write a program to create an array of 100 random integers between the values of 1 and 1000 and find the largest value.

AverageArray_YI.java
Write a program to create an array of 100 random integers between the values of 1 and 1000 and find the average of all the elements of the array.

PrintArray_YI.java
Write a program to create an array of 100 random integers between the values of 1 and 1000 and print them separated by 3 spaces. Note: Use printf to keep all your numbers tab properly.
A printf format reference page (cheat sheet)

Pop Quiz Array 1
Pop Quiz 1: Fix the problem