Early Seed Award

Write a sample binary addition 1 + 1 = 10

import java.util.Scanner;
    public class BinaryAdd{
        public static void main(String[] args) 
    {
        String b1,b2;
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter 1st binary no. : ") ;
        b1=sc.next();
        System.out.println("Enter 2nd binary no. : ") ;
        b2=sc.next();
        int num1=Integer.parseInt(b1,2);
        int num2=Integer.parseInt(b2,2);
        int sum=num1+num2;
        System.out.println("Additon is : "+Integer.toBinaryString(sum));
    }
    }
    BinaryAdd.main(null);

Tech Talk Notes

Notes from Tuesday (3/7) Tech Talk on Data Types.

Primitive vs Reference Data Types

Two data types in java

  • primitive (int, long, boolean, double, char, byte, short, float)
  • reference (object, arrays)

Primitive are stored directly in memory (local) whereas reference are stored as a reference to the memory location (local reference).

Wrapper Classes

Class that wraps the primitive type. We can use primitive types in collections (i.g. arraylists). Helps to convert int.s to objects and objects to int.s. Doesn't behave like a class though.

Autoboxing

  • Putting a box around int so it can be used in collections
  • similar to syntax for Int
// Both of these create new objects
Integer n = 5; // Auto-boxing, Integer n = new Integer(5);
n += 5;  // Auto-boxing, Integer n = new Integer(n + 5);

String isn't a primitive (only 1 value is a primitive) but it is a class (it is a group of values together).

Complex Data Structure

  • objects and arrays
    • can include user (metadata, etc.)
  • wrapper class retains teh things of a regular class
    • passes by value
  • class AtomicInteger passes by reference
    • hash code is on every object (built in Java)
      • unique signature (identification for the object)
      • point to memory location sometimes
  • swap IntbyReference
    • made a class, added private attribute/property with a primitive, try to use it by reference
    • made a method to swap from low to high order
    • had some values
      • method does a swapping routine (uses a temp location to easily swap using a triangle swapping method)

Hacks

Hack 1

Start with some small code exercises

  • Write a Jupyter notebook code example on the following primitive types with a code example (4 to 5 lines), preference would be using array and methods like substring and random as applicable: int, double, boolean, char.
  • Now convert each of the examples to corresponding Wrapper classes, using arrays.
  • Expression of these in Class or PBL forms is an option. But the review must be easy for me to see work.
import java.util.Random;

public class PrimitiveTypes {
  public static void main(String[] args) {
    // int
    int[] array = {1, 2, 3, 4, 5};
    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }

    // double
    double myDouble = 3.14;
    System.out.println(myDouble);

    // boolean
    boolean happy = false;
    boolean sad = false;

    if (!!!(happy || sad) && ((!happy && !sad) || !(!(happy || sad))) ) {
        System.out.println("You are sad.");
    }

    // char
    String myString = "Pranavi!";
    char myChar = myString.charAt(1); // get the second character
    System.out.println(myChar);
  }
}

PrimitiveTypes.main(null);
import java.util.Random;

public class WrapperTypes {
    public static void main(String[] args) {
        // Integer
        ArrayList<Integer> data = new ArrayList<Integer>();

        data.add( new Integer(1) );
        data.add( new Integer(3) );
        data.add( new Integer(17) );
        data.add( new Integer(29) );

        for ( int j=0; j < data.size(); j++ )
        System.out.print( data.get(j) + " " );

        System.out.println( );

        //Double
        Double[] myDoubleArr = {5.29, 213.72};
        System.out.println(myDoubleArr[0]);

        //Boolean
        Boolean a = true;
        Boolean b = false;
        Boolean c = a && b;
        
        System.out.printf("%b\n", c);

        //Char
        String word = "Pranavi";
        Character lastLetter = word.charAt(6);
        System.out.println("The last letter: " + lastLetter);
    }
}

WrapperTypes.main(null);

Hack 2

  • Explore Teacher Code: methodDataTypes. I would like a Jupyter Notebook that goes over key concepts in Teacher code and uses background from ChatGPT and from AP Classroom.

Answer what are Methods and Control Structures

Essentially, control structures are a program is a list of instructions. Control structures are programming blocks that can change the path we take through those instructions. There are three kinds of control structures. Conditional Branches, which we use for choosing between two or more paths. There are three types in Java: if/else/else if, ternary operator and switch. Loops that are used to iterate through multiple values/objects and repeatedly run specific code blocks. The basic loop types in Java are for, while and do while. Branching Statements, which are used to alter the flow of control in loops. There are two types in Java: break and continue.

Methods (also known as functions) are a block of code that, when called, perform whatever actions are mentioned in it. You can insert values or parameters into methods, and they will only be executed when called. You can only create a method within a class. There are a total of six components included in a method declaration. The components provide various information about the method. There are Predefined and User-defined methods in Java.

Explore AP FRQ that teaches us about Methods and Control Structures FRQ

package com.nighthawk.hacks.methodsDataTypes;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Menu: custom implementation
 * @author     John Mortensen
 *
 * Uses String to contain Title for an Option
 * Uses Runnable to store Class-Method to be run when Title is selected
 */

// The Menu Class has a HashMap of Menu Rows
public class Menu {
    // Format
    // Key {0, 1, 2, ...} created based on order of input menu
    // Value {MenuRow0, MenuRow1, MenuRow2,...} each corresponds to key
    // MenuRow  {<Exit,Noop>, Option1, Option2, ...}
    Map<Integer, MenuRow> menu = new HashMap<>();

    /**
     *  Constructor for Menu,
     *
     * @param  rows,  is the row data for menu.
     */
    public Menu(MenuRow[] rows) {
        int i = 0;
        for (MenuRow row : rows) {
            // Build HashMap for lookup convenience
            menu.put(i++, new MenuRow(row.getTitle(), row.getAction()));
        }
    }

    /**
     *  Get Row from Menu,
     *
     * @param  i,  HashMap key (k)
     *
     * @return  MenuRow, the selected menu
     */
    public MenuRow get(int i) {
        return menu.get(i);
    }

    /**
     *  Iterate through and print rows in HashMap
     */
    public void print() {
        for (Map.Entry<Integer, MenuRow> pair : menu.entrySet()) {
            System.out.println(pair.getKey() + " ==> " + pair.getValue().getTitle());
        }
    }

    /**
     *  To test run Driver
     */
    public static void main(String[] args) {
        Driver.main(args);
    }

}

// The MenuRow Class has title and action for individual line item in menu
class MenuRow {
    String title;       // menu item title
    Runnable action;    // menu item action, using Runnable

    /**
     *  Constructor for MenuRow,
     *
     * @param  title,  is the description of the menu item
     * @param  action, is the run-able action for the menu item
     */
    public MenuRow(String title, Runnable action) {
        this.title = title;
        this.action = action;
    }

    /**
     *  Getters
     */
    public String getTitle() {
        return this.title;
    }
    public Runnable getAction() {
        return this.action;
    }

    /**
     *  Runs the action using Runnable (.run)
     */
    public void run() {
        action.run();
    }
}

// The Main Class illustrates initializing and using Menu with Runnable action
class Driver {
    /**
     *  Menu Control Example
     */
    public static void main(String[] args) {
        // Row initialize
        MenuRow[] rows = new MenuRow[]{
            // lambda style, () -> to point to Class.Method
            new MenuRow("Exit", () -> main(null)),
            new MenuRow("Do Nothing", () -> DoNothingByValue.main(null)),
            new MenuRow("Swap if Hi-Low", () -> IntByReference.main(null)),
            new MenuRow("Matrix Reverse", () -> Matrix.main(null)),
            new MenuRow("Diverse Array", () -> Matrix.main(null)),
            new MenuRow("Random Squirrels", () -> Number.main(null))
        };

        // Menu construction
        Menu menu = new Menu(rows);

        // Run menu forever, exit condition contained in loop
        while (true) {
            System.out.println("Hacks Menu:");
            // print rows
            menu.print();

            // Scan for input
            try {
                Scanner scan = new Scanner(System.in);
                int selection = scan.nextInt();

                // menu action
                try {
                    MenuRow row = menu.get(selection);
                    // stop menu
                    if (row.getTitle().equals("Exit")) {
                        if (scan != null) 
                            scan.close();  // scanner resource requires release
                        return;
                    }
                    // run option
                    row.run();
                } catch (Exception e) {
                    System.out.printf("Invalid selection %d\n", selection);
                }

            } catch (Exception e) {
                System.out.println("Not a number");
            }
        }
    }
}

Look at Diverse Arrays, Matrix in Teacher code and see if you think this is Methods and Control structures

Diverse Arrays, Matrix is methods and control structures since it has code segments that are being called upon. The Diverse Arrays, Matrix also has loops and sequences in it.

Look at Diverse Arrays, Matrix in Teacher code an see if you thing this fits Data Types

Diverse Arrays, Matrix fits Data Types since it has code that involves integers (a type of data type).

Math.random is covered in Number, this Teacher code associated with random is critical knowledge when taking the AP Exam. Random numbers in range like 7 to 9 is very important

  • Extra Notes
    • Math.random() returns a random number between 0 and 1, but not including 1. The data type that Math.random() returns is a double.

Review DoNothingByValue, what is key knowledge here

The value of arguments are passed into a method's parameters. Java is pass-by-value, not pass-by-reference for methods. Since everything is pass-by-value, arrays are also passed-by-value. However, the value of an array is its reference. Therefore, when an array is passed into a method, the elements of the array can be changed directly. Pass-by-value is the value of a variable is passed Pass-by-reference is the variable's reference is passed. This allows the contents of the variable to be changed. There can only be 1 return value per method in Java. Classes and generics allow "pass-by-reference." Essentially, there are multiple data types being utilized in a single method.

Review IntByReference, what is key knowledge here

IntByReference essentially switches two integer numbers from lowest to highest using a tmp variable. These variables are passed by reference because they are part of an object. Therefore, the before and after are changed following the call to swapToLowHighOrder() method. Also, there is a conditionally built swap method.

Hack 3

Explore AP Classroom. Look at 1 unique FRQ per team member on AP Classroom that goes over Methods and Control Structures. Provide me a Jupyter Notebook, Video, and/or Code that cover key concepts. Make this better than AP Classroom, specifically trying to get these reviews to cover key parts in under Ten minutes. This option could use your PBL project and concepts if they were tailored to Teaching.

  • Explore Testing requirements in AP Classroom Video
  • Explore AP FRQ that teaches us about Methods and Control Structures FRQ, 18:10
  • Make sure that code runs completely, complete any portion of FRQ that is undone. Complete FRQs in a Jupyter notebook with markdown description and comments is a requirement.
  • Integrate Data Types into the discussion as this is import concept when studying early materials.
  • Integrate Definition of Methods and Control Structures in comments and definitions.

Me and my pair completed the 2019 APCSA FRQ Test. I did questions 1 and 2 whereas she did 3 and 4.

Question 1

parta partb

Complete method dayOfWeek below. You must use firstDayOfYear and dayOfYear appropriately to receive full credit.

 /** Returns the value representing the day of the week for the given date
 * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ...,
 * and 6 denotes Saturday.
 * Precondition: The date represented by month, day, year is a valid date.
 */
 public static int dayOfWeek(int month, int day, int year)
// part a
public static int numberOfLeapYears(int year1, int year2)
{  
   int numLeapYears = 0;
   for (int i = year1; i <= year2; i++) {
       if (isLeapYear(i)) {
           numLeapYears ++;
       }
   }
   return numLeapYears; 

}

// part b
public static int dayOfWeek(int month, int day, int year)
 {  
    int firstDay = firstDayOfYear(year);
    int theDate = dayOfYear(month, day year);
    int theDay = (firstDay + theDate - 1) % 7;
    return theDay;
 }

 public class APCalendar
 {
  /** Returns true if year is a leap year and false otherwise. */
  private static boolean isLeapYear(int year)
  { /* implementation not shown */ }
  /** Returns the number of leap years between year1 and year2, inclusive.
  * Precondition 0 <= year1 <= year2
  */
  public static int numberOfLeapYears(int year1, int year2)
  { /* to be implemented in part (a) */ 
     int numLeapYears = 0;
     for (int i = year1; i <= year2; i++) {
         if (isLeapYear(i)) {
             numLeapYears ++;
         }
     }
     return numLeapYears; 
 
 }
  /** Returns the value representing the day of the week for the first day of year,
  * where 0 denotes Sunday, 1 denotes Monday, ..., and 6 denotes Saturday.
  */
  private static int firstDayOfYear(int year)
  { /* implementation not shown */ }
 
  /** Returns n, where month, day, and year specify the nth day of the year.
  * Returns 1 for January 1 (month = 1, day = 1) of any year.
  * Precondition The date represented by month, day, year is a valid date.
  */
  private static int dayOfYear(int month, int day, int year)
  { /* implementation not shown */ }
 
  /** Returns the value representing the day of the week for the given date
  * (month, day, year), where 0 denotes Sunday, 1 denotes Monday, ...,
  * and 6 denotes Saturday.
  * Precondition The date represented by month, day, year is a valid date.
  */
  public static int dayOfWeek(int month, int day, int year)
  {  
     int firstDay = firstDayOfYear(year);
     int theDate = dayOfYear(month, day year);
     int theDay = (firstDay + theDate - 1) % 7;
     return theDay;
  }
  // There may be instance variables, constructors, and other methods not shown.
 }

Question 2

question2

Write the complete StepTracker class, including the constructor and any required instance variables and methods. Your implementation must meet all specifications and conform to the example.

public class StepTracker {

    // accessing and showing our private instance variables
     private int totalSteps;
     private int minimumSteps;
     private int daysActive;
     private int days;
     
     // constructor with the parameter 
     public StepTracker(int least){
         minimumSteps = least;
         totalSteps = 0; // values to initialize variables
         daysActive = 0;
         days = 0;
     }
 
     //added the dailySteps method as the "AddDailySteps"
     public void AddDailySteps(int steps){
         totalSteps += steps; //shows active days and the incremental counting
         days++;
         if (steps >= minSteps){
             daysActive++; // updates the other instance variables
         }
     }
 
     //the activeDays method
     public int getdaysActive(){ // declared and implemented into program
         return days;
     }
 
     public double avgSteps(){
         if (days == 0){
             return 0.0;
         } 
         else{
 
             //returns the calculated double of the average number of steps walked
             return (double) totalSteps / days; 
         }
     }
 
 }

Multiple Choice Question Test (AP CollegeBoard)

This is a deeper analysis on the result and mistakes I made on this practice multiple choice test.

Question 13

Consider the following instance variable and method.

private int, open square bracket, close square bracket, numbers, semicolon. 

public void mystery, open parenthesis, int x, close parenthesis. 
{
for (int k equals 1; k < numbers.length; k = k + x)
    {
        numbers[k] = numbers[k-1] + x;
    }
}

Assume that numbers has been initialized with the following values. {17, 34, 21, 42, 15, 69, 48, 25, 39} Which of the following represents the order of the values in numbers as a result of the call mystery(3)?

Answer

Answer option D "{20, 23, 21, 42, 45, 69, 51, 54, 39}" is incorrect because this result modifies five values in numbers, but since the loop control variable k starts at 1 and is incremented by 3, only three elements will be updated. The correct answer option would be answer A "{17, 20, 21, 42, 45, 69, 48, 51, 39}." The values of the loop control variable k starts at 1 and is incremented by 3 as long as k is less than numbers.length. As a result, k will have the values 1, 4, 7 and then when it becomes 10, the loop will end. Only the values in numbers at indexes 1, 4, and 7 will be updated to the value of the sum of the element at the index that is one less than k (the element before the one being updated) and 3. So, numbers[1] will be assigned the value of numbers[0] + 3 or 20, numbers[4] will be assigned the value of numbers[3] + 3 or 45, and numbers[7] will be assigned the value of numbers[6] + 3 or 51. All other values will be unchanged.

Question 14

Consider the following method, biggest, which is intended to return the greatest of three integers. It does not always work as intended.

public static int biggest (int a comma int b comma int c)
{
    if ((a > b) && (a > c))
    {
        return a;
    }
    else if ((b > a) && (b > c))
    {
        return b;
    }
    else
    {
        return c;
    }
}

Which of the following best describes the error in the method?

Answer

Answer option E is wrong because the example where a = 3, b = 5, and c = 5. In this case, the first boolean condition evaluates to false since a is not greater than b and the second boolean condition evaluates to false since b is not greater than c, and the value of c is returned, which is the greatest of all three integers. Consider the second example where a = 6, b = 5, and c = 5. In this case, the first boolean condition evaluates to true since a is greater than b and a is greater than c, and the value of a is returned, the greatest of the three values. Therefore, the correct answer option is C since the example where a = 5, b = 5, and c = 3. The boolean expression ((a > b) && (a > c)) would be false because a is not greater than b, so the code will evaluate the boolean expression in the else if. The boolean expression ((b > a) && (b > c)) will also evaluate to false because b is not greater than a, this will cause c to be returned, however c is the smallest of the three integers and not the greatest.

Question 18

What is printed as a result of executing the following statement?

System.out.println(404 / 10 * 10 + 1);
Answer

Answer option E with 405 is incorrect since this would be the result if the division used was floating point division instead of integer division and the result was cast to an int, as in (int)(404.0 / 10 * 10 + 1). The correct answer option is D with 401 since the first operation that is executed is 404 / 10. Since both 404 and 10 are integers, integer division is used resulting in 40. The value 40 is then multiplied by 10, resulting in 400, and finally 1 is added, meaning 401 is printed.

Question 19

Consider the following code segment.

int x = 1;
while ( /* condition */ )
{
    if (x % 2 == 0)
    {
        System.out.print(x + " ");
    }
    x = x + 2;
}

The following conditions have been proposed to replace / condition / in the code segment.

I. x < 0 II. x <= 1 III. x < 10

For which of the conditions will nothing be printed?

Answer

Answer option C is incorrect since in condition III, the while loop will execute for x having the value 1, 3, 5, 7, and 9. When x becomes 11 the loop will terminate. Even though the loop executes multiple times, the values assigned to x are not even, so nothing is printed. The correct answer option is E since in condition I, the while loop will not execute, since 1, the value of x, is not less than 0, so nothing will be printed. In condition II, the while loop will execute one time, since 1, the value of x is less than or equal to 1, however, 1 is not even, so nothing will be printed. The value of x will then be incremented to 3, which is not less than or equal to 1, and the loop will terminate. In condition III, the while loop will execute for x having the value 1, 3, 5, 7, and 9. When x becomes 11 the loop will terminate. Even though the loop executes multiple times, the values assigned to x are not even, so nothing is printed.

Question 31

Consider the following code segment.

question31

Which of the following represents board after this code segment is executed?

Answer

Answer option C is incorrect since this image could be accomplished by iterating board and setting all locations where row == col to “X” and all locations where row + column == board.length-1 to “X”. Therefore, answer option E is the correct option since the first set of nested for loops sets each element in board to “O”. The next for loop starts val at 0 and increments by 1 until val is 4, when val is 5 the loop terminates. When val is even, board is not updated, so nothing happens when val is 0. When val is 1, row is assigned 1 and col is assigned 0. The boolean condition in the while loop is true, so board[1][0] is assigned “X”. Then col is incremented to 1 and row is decremented to 0 and board[0][1] is assigned “X”. Then col is incremented to 2 and row is decremented to -1 and the while loop terminates. When val is 2, nothing changes about board. When val is 3, row is assigned 3 and col is assigned 0. The boolean condition in the while loop is true, so board[3][0] is assigned “X”. Then col is incremented to 1 and row is decremented to 2 and board[2][1] is assigned “X”. Then col is incremented to 2 and row is decremented to 1 and board[1][2] is assigned “X”. Then col is incremented to 3 and row is decremented to 0 and board[0][3] is assigned “X”. Finally, col is incremented to 4 and row is decremented to -1 and the while loop terminates. When val is 4, nothing changes about board.