Extra Seed Point

  • Java Addition

  • Method 1, using built in Java program Integer.toBinaryString

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);

    int num1 = myObj.nextInt();
    System.out.println("Number 1: " + num1);

    int num2 = myObj.nextInt();
    System.out.println("Number 2: " + num2);

    int decSum = num1 + num2;

    // Output input by user
    System.out.println("Decimal addition sum: " + Integer.toBinaryString(decSum));
    System.out.println("Final Result: " + num1 + " + " + num2 + " = " + Integer.toBinaryString(decSum));
  }
}

Main.main(null);
Number 1: 1
Number 2: 1
Decimal addition sum: 10
Final Result: 1 + 1 = 10
  • Method 2, custom method...divide decimal by value...
    • Remainder becomes binary value and divide quotient by 2 until you are left with 0 (since it's using integers it'll eventually come down to 1/2 which equals 0)
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);

    int num1 = myObj.nextInt();
    System.out.println("Number 1: " + num1);

    int num2 = myObj.nextInt();
    System.out.println("Number 2: " + num2);

    int decSum = num1 + num2;

    int n = decSum;

    long binNum = 0;
    int remainder;
    int i = 1;

    while (n!=0) {
      remainder = n % 2;
        n /= 2;

        binNum += remainder * i;
        i *= 10;
    }
    
    System.out.println("Decimal addition sum: " + binNum);
    System.out.println("Final Result: " + num1 + " + " + num2 + " = " + binNum);
    }

  }

Main.main(null);
Number 1: 1
Number 2: 1
Decimal addition sum: 10
Final Result: 1 + 1 = 10

Tech Talk -- Data Types in Java

  • Primitive Data Types Collegeboard wants...

    • int
    • double
    • idr man
  • Primitive data types are value only

  • Local variables == all the variables in the method --> can see them in debugger

    • If you hover over classes/variables you can see the value and/or the reference to the value
  • Two data types in Java...Primitive and Reference...

    • Reference means inside of a structure, you have pointers to memory location...two types
    • Objects
    • Arrays
    • Primitive is a local value...right there in memory
  • Wrapper classes

    • Class that wraps a primitive data type into an object...
    • Example is int vs Integer...int is a primitive data type that stores 32-bit signed two's complement integer while the Integer is a class that wraps a primitive type int in an object
    • The primitive stores int values in memory while the wrapper converts the primitive data type into an object and to convert an object into the primitive data type
  • Auto-boxing:basically what wrapper does...you are putting a box around the value to be used later

// 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);
  • Objects and arrays are complex data structures...
    • Objects are instances of classes that encapsulate data and behavior --> allows for more flexibility in terms of what data types you want to store
    • Arrays are collections of data of the same type
public class IntByValue {
    
    public static void changeInt(int n) {
        System.out.println("In changeInt method");
        System.out.println("\tBefore n += 10: n = " + n); // prints 5
        n = n += 10;
        System.out.println("\tAfter n += 10: n = " + n); // prints 10
    }

    public static void main(String[] args) {
        int n = 5;
        System.out.println("Main method before changeInt(n): n = " + n); // prints 5
        changeInt(n);
        System.out.println("Main method after changeInt(n): n = " + n); // still prints 5
    }
}
IntByValue.main(null);
Main method before changeInt(n): n = 5
In changeInt method
	Before n += 10: n = 5
	After n += 10: n = 15
Main method after changeInt(n): n = 5
  • When swapping values, you need to have a temp location since the values might get damaged if they just directly swapped

Hack 1

Start with some small code excercises

  • 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 Main {
  public static void main(String[] args) {
    // int
    int myInt = 10;
    System.out.println(myInt);

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

    // boolean
    boolean myBool = true;
    System.out.println(myBool);

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

    // using substring method
    String substring = myString.substring(1, 5); // get a substring from the second to the fifth character
    System.out.println(substring);

    // using Random class
    Random rand = new Random();
    int myRandomInt = rand.nextInt(10) + 1; // get a random integer between 1 and 10
    System.out.println(myRandomInt);
  }
}

Main.main(null);
10
3.14
true
e
ello
1
import java.util.Random;

public class Main {
  public static void main(String[] args) {
    // Integer array
    Integer[] myIntArr = {10, 20, 30};
    System.out.println(myIntArr[0]);

    // Double array
    Double[] myDoubleArr = {3.14, 2.718, 1.414};
    System.out.println(myDoubleArr[1]);

    // Boolean array
    Boolean[] myBoolArr = {true, false, true};
    System.out.println(myBoolArr[2]);

    // Character array
    String myString = "hello world";
    Character[] myCharArr = new Character[myString.length()];
    for (int i = 0; i < myString.length(); i++) {
      myCharArr[i] = myString.charAt(i);
      System.out.println(myCharArr[i]);
    }

    // using substring method on String array
    String[] myStringArr = {"apple", "banana", "orange"};
    String substring = myStringArr[1].substring(0, 3); // get a substring from the second element in the array
    System.out.println(substring);

    // using Random class on Integer array
    Random rand = new Random();
    Integer[] myRandomIntArr = new Integer[10];
    for (int i = 0; i < 10; i++) {
      myRandomIntArr[i] = rand.nextInt(10) + 1;
    }
    System.out.println(myRandomIntArr[5]);
  }
}

Main.main(null);
10
2.718
true
h
e
l
l
o
 
w
o
r
l
d
ban
1

Hack 2

Based on Mr. M's code...answer the following...

  • Answer what are Methods and Control Structures
    • Methods are blocks of code which only run when called upon. Control structures are coding methods where you code your data according to research questions or topics. There are typically 3 main types of code structures...sequences, selections, and loops.
  • Explore AP FRQ that teaches us about Methods and Control Structures FRQ
    • See below.
  • Look at Diverse Arrays, Matrix in Teacher code and see if you think this is Methods and Control structures.
    • It would appear that they are methods and control structures. You can see blocks of code that need to be called upon and examples of loops, sequences, and selections.
  • Look at Diverse Arrays,Matrix in Teacher code an see if you thing this fits Data Types.
    • There are integers which is an example of a data type. Therefore, the code does have data types.
  • 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.
    • OK
  • Review DoNothingByValue, what is key knowledge here?
    • There are multiple data types being utilized in a single method.
  • Review IntByReference, what is key knowledge here?
    • There is a conditionally built swap method.
  • Review Menu code. Try, Catch, Runnable are used to control program execution. See if there is a way to get this to work in Jupyter Notebooks.
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");
            }
        }
    }
}

Hack 3

2019 FRQ...I did questions 3 and 4, Pranavi did 1 and 2

3A A string containing text and possibly delimiters has been split into tokens and stored in String[] tokens. Each token is either an open delimiter, a close delimiter, or a substring that is not a delimiter. You will write the method getDelimitersList, which returns an ArrayList containing all the open and close delimiters found in tokens in their original order. The following examples show the contents of an ArrayList returned by getDelimitersList for different open and close delimiters and different tokens arrays.

public ArrayList<String> getDelimitersList(String[] tokens)
{
 ArrayList<String> d = new ArrayList<String>();
    for (String str : tokens)
    {
        if (str.equals(openDel) || str.equals(closeDel))
        {
             d.add(str);
            }
        }
        
        return d;
}

3B Write the method isBalanced, which returns true when the delimiters are balanced and returns false otherwise. The delimiters are balanced when both of the following conditions are satisfied; otherwise, they are not balanced.

When traversing the ArrayList from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. The total number of open delimiters is equal to the total number of close delimiters. Consider a Delimiters object for which openDel is "" and closeDel is "". The examples below show different ArrayList objects that could be returned by calls to getDelimitersList and the value that would be returned by a call to isBalanced.

public boolean isBalanced(ArrayList<String> delimiters) {
	int openDels = 0;
	int closeDels = 0;
	
	for (String del : delimiters) {
		if (del.equals(openDel)) {
			openDels++;
		} else {
			closeDels++;
		}
		
		if (closeDels > openDels) {
			return false;
		}
        if (openDels == closeDels)
        {
            return true;
        }
        else
        {
            return false;
        }
	}
	
	return openDels == closeDels;
}

4A Write the constructor for the LightBoard class, which initializes lights so that each light is set to on with a 40% probability. The notation lights[r][c] represents the array element at row r and column c.

public LightBoard(int numRows, int numCols)
{
    lights = new boolean[numRows][numCols];
    for (int r = 0; r < numRows; r++)
    {
         for (int c = 0; c < numCols; c++)
         {
             double rnd = Math.random();
             lights[r][c] = rnd < 0.4;
            }
        }
    }

4B Write the method evaluateLight, which computes and returns the status of a light at a given row and column based on the following rules.

If the light is on, return false if the number of lights in its column that are on is even, including the current light. If the light is off, return true if the number of lights in its column that are on is divisible by three. Otherwise, return the light’s current status. For example, suppose that LightBoard sim = new LightBoard(7, 5) creates a light board with the initial state shown below, where true represents a light that is on and false represents a light that is off. Lights that are off are shaded.

public boolean evaluateLight(int row, int col)
{
 int numOn = 0;

 for (int r = 0; r < lights.length; r++)
 {
    if (lights[r][col])
    {
        numOn++;
    }
 }

 if (lights[row][col] && numOn % 2 == 0)
 {
    return false;
 }
 if (!lights[row][col] && numOn % 3 == 0)
 {
    return true;
 }
 return lights[row][col];
}

MC Review -- 35/39

Q13: Given the int variable and Mystery method...

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)?

Right Answer and Explanation: {17, 20, 21, 42, 45, 69, 48, 51, 39}

  • Correct. 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.

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

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

Right Answer and Explanation:401- Correct. 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.

Q19: Given the code segment...

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

x < 0

x <= 1

x < 10

For which of the conditions will nothing be printed?

Right Answer and Explanation: I, II, and III

  • Correct. 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.

Q20: Considering the Mystery method...

Assume that nums has been declared and initialized as an array of integer values. Which of the following best describes the value returned by the call mystery(nums) ?

Right Answer and Explanation: An index of a value that occurs most often in nums

  • Correct. The outer loop starts at 0 and loops through all the indices in arr. The inner loop starts at the index that is one more than outer and iterates through all indices to the right of this element. For each iteration of the inner loop, the element at the current value of outer is compared with each subsequent element. If the elements are equal, then count is incremented. This results in counting the number of occurrences of each value in the arr. After the inner loop terminates, if the number of occurrences of the current value is greater than previous highest count, the new count is assigned to m and the index of this element is stored in index. The method then returns the value of index, which represents the index of a value that occurs most often in nums.