Category Archives: Assignment

Chapter 3 – Slot Machine

September 24th, 2015

Classwork/Homework
Design and implement an application, YI_SloptMachine.java that simulates a simple slot machine in which three numbers between 0 and 9 are randomly selected and printed side by side. Print a statement saying all three of the numbers are the same, or any two of the numbers are the same, when this happens. Keep playing until the user chooses to stop.
Screen Shot 2014-09-16 at 2.47.15 PM

Homework:
Short answer 3.6 through 3.10.

Chapter 3 – Rock-paper-scissors

Classwork:
Homework review

Classwork/Homework
Design and implement an application that plays the rock-paper-scissors game against the computer. When played between two people, each person picks one of three options (usually shown by a hand gesture) at the same time, and a winner is determined. In the game, rock beats scissors, scissors beats paper, and paper beats rock. The program should randomly choose one of the three options (without revealing it), then ask for the user’s selection. At that point, the program reveals both choices and prints a statement indicating that the user won, that the computer won, or that it was a tie. Keep playing until the user chooses to stop, then print the number of user wins, losses, and ties.

rockpaperscissor

screen-shot-2016-09-20-at-6-46-04-pm

Chapter 3: Floating point Exercises

Find the errors in problems 1 through 8 and fix them if possible

1. if quarters > 0 then System.out.println(quarters + " quarters");
2. if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
3. if (x  =  1) y++;   else if  (x  =  2)   y  =  y  +  2;
4. if (x  && y  ==  0)   { x  =  1; y  = 1; }
5. if  (1 <=   X   <=  10) 
       System.out.println(x);
6. if (s !=  "nickels" || s  !=  "pennies"
      || s  !=  "dimes" || s  !=  "quarters")
      System.out.print("Input error!");
7. if (input.equalsIgnoreCase("N") || "NO")
      return;
8. int x  =  Integer.parseInt(input);
   if (x ! = null) y  =  y  +  x;
9. Write a truth table for the following boolean expressions and compare them: 

Complete the table below.
  p     q     r    (p && q) || !r     !(p && (q || !r))
  f     f     f
  f     f     t
  f     t     f
       ...
  5 more combinations

Programming Assignments:

1 . Write a program that reads in three floating-point numbers and prints the three inputs in sorted order. For example:

Please enter  three  numbers:
  4
  9
  2.5
The  inputs in sorted order are
  2.5
  4
  9

2. Write a Java program, CompareFloats_YI.java to show two floating-point numbers x and y such that Math.abs(x – y) is larger than 1000, but x and y are still identical except for a round­ off error.

Chapter 2: Concepts Review

Concepts Review

  1. The information we manage in a Java program is either primitive data or ADT.
  2. An abstraction hides details. A good abstraction hides the right details at the right time.
  3. A variable is a name for a memory location used to hold a value of a particular data type.
  4. A variable can store only one value of its declared type.
  5. Java is a strongly typed language. Each variable has a specific type, and we cannot assign a value of one type to a variable of another type.
  6. Constants are like variables, but they hold one particular value.
  7. Java has two kinds of numeric values: integers and floating point. The primitive type int is an integer data type and double is a floating point data type.
  8. Many programming statements involve expressions. Expressions are combinations of one or more operands and the operators used to per­ form a calculation.
  9. Java has rules that govern the order in which operators will be evalu- ated in an expression.
  10. Avoid narrowing conversions because they can lose information.
  11. The new operator returns a reference to a newly created object.
  12. The Java standard class library is a useful set of classes that anyone can use when writing Java programs.

Submit answers to the following questions:
1. What is the content of an object variable?
2. Write a code snipped to compare two strings, s1 and s2. If s1 comes first in the lexicographic order, then it will print “move two steps forward” else “move two steps backwards.
3. Why the “= =” cannot be used to compare objects?
4. Give an example of widening and narrowing type conversion for each.
5. What is the purpose of casting when using a casting operator in the case of narrowing type conversion.
6. What is the result of 21 % 6 when evaluated in a java expression?
7. What is the result of (double) (15/2) in a java expression?
8. What does the operator new do?
9. Write the statement to print “Hello World” including the quotes.
10. What does “123456789”.substring(3,6) return?
11. Write a main method that prompts the use for two numbers, x and y, and it displays it back the following format: (x,y).

Chapter 2: Do programming assignments 2.13, 2.14 and 2.15 but instead of an applet write an application. You can use the university libraries or the java graphics libraries. The assignments are at the end of the chapter.
Screen Shot 2014-09-09 at 10.13.27 PM

screen-shot-2016-09-19-at-5-25-49-pm

Homework:
Read/browse pages 58 through 79

Project: NBody Simulation

May 15th, 2015

Screen Shot 2015-05-12 at 11.47.35 AM

Using PU Classes:
Programming Assignment due on 5/29: N-Body Simulation
Screen Shot 2015-05-13 at 1.47.10 PM

Checklist

Some cool links:
Screen Shot 2015-05-13 at 1.54.01 PM

Screen Shot 2015-05-13 at 1.55.27 PM

Screen Shot 2015-05-13 at 1.57.08 PM


Some math and little bit of physics:

Chapter 8: Sorts Projects

Classwork:
The purpose of this assignment is to observe the different performance of the quick sort based on the data.

  1. Create 3 data sets of 50,000 integers:

Data Set A: randomly generate the data in range from 1 to 50,000.(no duplicates)
Data Set B: generate integers in range from 1 to 50,000 sorted in ascending order.
Data Set C: generate integers in range from 1 to 50,000 sorted in descending order.

  1. Set up a counter in your quick sort trace program and run the three sets separately.
    Your results will be meaningful depending where you put the counter. So be mindful of what you are trying to achieve.

  2. Find an expression that relates the size of the data to the number of comparisons or visits to the data.

  3. Make a conclusion about the three different cases.

NOTE: Use Arrays and the version of Quick sort we have used.

**** If your program crashes with “stack overflow”, change the number of elements from 50,000 to 10,000 ****

Documentation:
Besides the usual, explain where and why your counter is placed.
The conclusion about the behavior of the sort based on the data characteristic.

Sorting Project
Due date: February 15th, 2017

You are to write a program that tests each of five sorting algorithms with arrays of random integer values of four different sizes. You also need a counter for this project. And just like in the previous assignment you need to decide where the counter should be so the comparisons make sense for the all the sorts. The documentation must explain where and why the counter is placed.

The five algorithms are: selection sort, insertion sort, bubble sort, quick sort and merge sort.
The array sizes to use are: 10, 100, 1000, and 5000.
The Counter class and also a class that generates arrays of random integers are posted below.
You will need to modify the sort code to include an increment to the counter where appropriate.

The main part of this project is the design and implementation of a driver program that will test the sorts on the same set of arrays.

  1. It should keep track of the count result for each sort for each array size and generate a table to summarize the results. A sample table is shown.

  1. It should create a scatter plot for each of the sorts. The plot could be either text based or as a GUI. You have the option of entering the data in a spreadsheet and use the graphing feature to create the scatter plot.

  1. Use mathematical regressions to find an expression for each of the sorts’ data.

NOTE: Counter, RandomIntArray classes, and public static void bubbleSort1(int[] x) resources are optional. You can make substitutions.

import java.util.Scanner;
//********************************************************************
//  RecursiveSorts.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the merge sort and quick sort algorithms.
//********************************************************************

public class RecursiveSorts
{
   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using merge sort.
   //-----------------------------------------------------------------
   public static void mergeSort (int[] numbers)
   {
       
      doMergeSort(numbers, 0, numbers.length - 1);
   }

   //-----------------------------------------------------------------
   //  Recursively sorts the the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doMergeSort (int[] numbers, int start, int end)
   {
       
      if (start < end)
      {
         int middle = (start + end) / 2;
         doMergeSort (numbers, start, middle);
         doMergeSort (numbers, middle + 1, end);
         merge (numbers, start, middle, end);
      }
   }

   //-----------------------------------------------------------------
   //  Merges in sorted order the two sorted subarrays
   //  [start, middle] and [middle + 1, end].
   //-----------------------------------------------------------------
   private static void merge (int[] numbers, int start, int middle,
                     int end)
   {

      // This temporary array will be used to build the merged list.
      int[] tmp = new int[end - start + 1];

      int index1 = start;
      int index2 = middle + 1;
      int indexTmp = 0;

      // Loop until one of the sublists is exhausted, adding the smaller
      // of the first elements of each sublist to the merged list.
      while (index1 <= middle && index2 <= end)
      {
         if (numbers[index1] < numbers[index2])
         {
             tmp[indexTmp] = numbers[index1];
             index1++;
         }
         else
         {
             tmp[indexTmp] = numbers[index2];
             index2++;
         }
          indexTmp++;
      }

      // Add to the merged list the remaining elements of whichever sublist
      // is not yet exhausted.
      while (index1 <= middle)
      {
         tmp[indexTmp] = numbers[index1];
         index1++;
         indexTmp++;
      }
      while (index2 <= end)
      {
         tmp[indexTmp] = numbers[index2];
         index2++;
         indexTmp++;
      }


      // Copy the merged list from tmp into numbers.
      for (indexTmp = 0; indexTmp < tmp.length; indexTmp++)
      {
         numbers[start + indexTmp] = tmp[indexTmp]; 
      }

   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using quick sort.
   //-----------------------------------------------------------------
   public static void quickSort (int[] numbers)
   {
      doQuickSort(numbers, 0, numbers.length - 1);
   }
   //-----------------------------------------------------------------
   //  Recursively sorts the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doQuickSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = partition(numbers, start, end);
         doQuickSort(numbers, start, middle);
         doQuickSort(numbers, middle + 1, end);
      }
   }

   //-----------------------------------------------------------------
   //  Partitions the array such that each value in [start, middle]
   //  is less than or equal to each value in [middle + 1, end].
   //  The index middle is determined in the procedure and returned.
   //-----------------------------------------------------------------
   private static int partition (int[] numbers, int start, int end)
   {
      int pivot = numbers[start];
      int i = start - 1;
      int j = end + 1;

      // As the loop progresses, the indices i and j move towards each other.
      // Elements at i and j that are on the wrong side of the partition are
      // exchanged. When i and j pass each other, the loop ends and j is
      // returned as the index at which the elements are partitioned around.
      while (true)
      {
         i = i + 1;
         while (numbers[i] < pivot)
            i = i + 1;

         j = j - 1;
         while (numbers[j] > pivot)
            j = j - 1;

         if (i < j)
         {
            int tmp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tmp;

            for (int index = 0; index < numbers.length; index++)
                System.out.print (numbers[index] + "   ");
         }
         else return j;
      }
   }
}

Bubble Sort — fixed number of passes
This version of bubble sort makes a fixed number of passes (length of the array – 1). Each inner loop is one shorter than the previous one.

public static void bubbleSort1(int[] x) {
    int n = x.length;
    for (int pass=1; pass < n; pass++) {  // count how many times
        // This next loop becomes shorter and shorter
        for (int i=0; i < n-pass; i++) {
            if (x[i] > x[i+1]) {
                // exchange elements
                int temp = x[i];  
                x[i] = x[i+1];  
                x[i+1] = temp;
            }
        }
    }
}

Optional Resources:

public class Counter

{
    private static int count = 0;

    public static int getcount( )

    {
        return count;
    }

    public static void reset( )
    {
        count = 0;
    }

    public static void increment( )
    {
        count++;
    }
}
import java.util.Random;

public class RandomIntArray
{
    public static int[ ] generateArray( int n )
    {
    // generates an array of length n populated
    // with random integers

        int[ ] result = new int[n];
                Random random = new Random();
        for (int i = 0; i < n; i++)

            result[i] = random.nextInt(5*n);

        return result;
    }
}


Homework:
Start working on the project.

Chapter 8: Recursion Intro Part 2

Intro to Recursion

A simple example from stackoverflow with OOD:



    class Calculation
    {
        int fact(int n)
        {
            int result;

           if(n==1)
             return 1;

           result = fact(n-1) * n;
           return result;
        }
    }

    public class Factorial
    {
         public static void main(String args[])
         {
           Calculation obj_one = new Calculation();

           int a = obj_one.fact(4);
           System.out.println("The factorial of the number is : " + a);
         }
    }


factorial1

Assignments:
1. Use the same visual representation as the one above for 4!

fibRec

2. Modify the method that calculates the sum of the integers between 1 and N shown in this chapter. Have the new version match the following recursive definition: The sum of 1 to N is the sum of 1 to (N/2) plus the sum of (N/2 + 1) to N. Trace your solution using an N of 7.


3. Design and implement a program that implements Euclid’s algorithm for finding the greatest common divisor of two positive integers. The greatest common divisor is the largest integer that divides both values without producing a remainder. An iterative version of this method was part of the RationalNumber class presented in Chapter 4.

Rational


//********************************************************************
//  Rational.java       Author: Lewis/Loftus/Cocking
//
//  Represents one rational number with a numerator and denominator.
//********************************************************************

public class Rational
{
   private int numerator, denominator;

   //-----------------------------------------------------------------
   //  Sets up the rational number by ensuring a nonzero denominator
   //  and making only the numerator signed.
   //-----------------------------------------------------------------
   public Rational (int numer, int denom)
   {
      if (denom == 0)
         denom = 1;

      // Make the numerator "store" the sign
      if (denom < 0)
      {
         numer = numer * -1;
         denom = denom * -1;
      }

      numerator = numer;
      denominator = denom;

      reduce();
   }

   //-----------------------------------------------------------------
   //  Returns the numerator of this rational number.
   //-----------------------------------------------------------------
   public int getNumerator ()
   {
      return numerator;
   }

   //-----------------------------------------------------------------
   //  Returns the denominator of this rational number.
   //-----------------------------------------------------------------
   public int getDenominator ()
   {
      return denominator;
   }

   //-----------------------------------------------------------------
   //  Returns the reciprocal of this rational number.
   //-----------------------------------------------------------------
   public Rational reciprocal ()
   {
      return new Rational (denominator, numerator);
   }

   //-----------------------------------------------------------------
   //  Adds this rational number to the one passed as a parameter.
   //  A common denominator is found by multiplying the individual
   //  denominators.
   //-----------------------------------------------------------------
   public Rational add (Rational op2)
   {
      int commonDenominator = denominator * op2.getDenominator();
      int numerator1 = numerator * op2.getDenominator();
      int numerator2 = op2.getNumerator() * denominator;
      int sum = numerator1 + numerator2;

      return new Rational (sum, commonDenominator);
   }

   //-----------------------------------------------------------------
   //  Subtracts the rational number passed as a parameter from this
   //  rational number.
   //-----------------------------------------------------------------
   public Rational subtract (Rational op2)
   {
      int commonDenominator = denominator * op2.getDenominator();
      int numerator1 = numerator * op2.getDenominator();
      int numerator2 = op2.getNumerator() * denominator;
      int difference = numerator1 - numerator2;

      return new Rational (difference, commonDenominator);
   }

   //-----------------------------------------------------------------
   //  Multiplies this rational number by the one passed as a
   //  parameter.
   //-----------------------------------------------------------------
   public Rational multiply (Rational op2)
   {
      int numer = numerator * op2.getNumerator();
      int denom = denominator * op2.getDenominator();

      return new Rational (numer, denom);
   }

   //-----------------------------------------------------------------
   //  Divides this rational number by the one passed as a parameter
   //  by multiplying by the reciprocal of the second rational.
   //-----------------------------------------------------------------
   public Rational divide (Rational op2)
   {
      return multiply (op2.reciprocal());
   }

   //-----------------------------------------------------------------
   //  Determines if this rational number is equal to the one passed
   //  as a parameter.  Assumes they are both reduced.
   //-----------------------------------------------------------------
   public boolean equals (Rational op2)
   {
      return ( numerator == op2.getNumerator() &&
               denominator == op2.getDenominator() );
   }

   //-----------------------------------------------------------------
   //  Returns this rational number as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      String result;

      if (numerator == 0)
         result = "0";
      else
         if (denominator == 1)
            result = numerator + "";
         else
            result = numerator + "/" + denominator;
    
      return result;
   }

   //-----------------------------------------------------------------
   //  Reduces this rational number by dividing both the numerator
   //  and the denominator by their greatest common divisor.
   //-----------------------------------------------------------------
   private void reduce ()
   {
      if (numerator != 0)
      {
         int common = gcd (Math.abs(numerator), denominator);

         numerator = numerator / common;
         denominator = denominator / common;
      }
   }

   //-----------------------------------------------------------------
   //  Computes and returns the greatest common divisor of the two
   //  positive parameters. Uses Euclid's algorithm.
   //-----------------------------------------------------------------
   private int gcd (int num1, int num2)
   {
      while (num1 != num2)
         if (num1 > num2)
            num1 = num1 - num2;
         else
            num2 = num2 - num1;

      return num1;
   }
}



[collapse]

In a class called DivisorCalc, define a static method called gcd that accepts two integers, num1 and num2. Create a driver to test your implementation. The recursive algorithm is defined as follows:

gcd (num1, num2) is num2 if num2 <= num1 and num2 divides num1

gcd (num1, num2) is gcd (num2, num1) if num1 < num2

gcd (num1, num2) is gcd (num2, num1%num2) otherwise

4. Design and implement a recursive program, Pascal_YI.java to determine and print the Nth line of Pascal’s Triangle, as shown below. Each interior value is the sum of the two values above it. Hint: use an array to store the values on each line.

pascal

Pi Day The Gridworld

March 12th, 2014

Screen Shot 2014-03-12 at 9.40.23 AM

Friday is Pi Day – We will have a pi-day activity
Starting tomorrow we are celebrating Pi day by writing a program to do one of the following:
1. Calculate the digits of Pi to highest possible precision
2. Illustrate how Pi works
3. Illustrate how Pi was discovered

The programs will be judge based on ingenuity and/or creativity.
NOTE: You can use online resources to help you develop your program. You can not use already written programs.

Case Study: The Gridworld

Screen Shot 2014-03-04 at 10.35.50 AM

Classwork:
Group Activity 1-2 to create the Jumper class and the runner program.

Homework:
write the code for the Jumper class and the runner program.