Quiz: 30/39

Early Seed Check

// Importing the Scanner class
import java.util.Scanner;

// Declaring the Binary class
public class Binary {
   
   // Defining the main method
   public static void main(String[] args)
   {
      // Initializing two integer variables, i and carry
      int i = 0, carry = 0;

      // Initializing an integer array with size 10 to hold the binary sum
      int[] sum = new int[10];

      // Initializing two integer variables with value 1
      int b1 = 1;
      int b2 = 1;

      // Executing a while loop until b1 and b2 are both 0
      while (b1 != 0 || b2 != 0) 
      {
         // Performing binary addition of b1 and b2 with the carry and storing the result in the sum array
         sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);

         // Updating the carry for the next iteration of the loop
         carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);

         // Removing the least significant digit from b1 and b2
         b1 = b1 / 10;
         b2 = b2 / 10;
      }
      
      // If there is still a carry after the loop has finished, add it to the sum array
      if (carry != 0) {
         sum[i++] = carry;
      }

      // Decrementing i to get the correct index for printing the sum array in reverse order
      --i;

      // Printing the binary sum
      System.out.print("1 + 1 = ");
      while (i >= 0) {
         System.out.print(sum[i--]);
      }

      // Printing a new line character to separate the output from any subsequent output
      System.out.print("\n");
   }
}

// Calling the main method of the Binary class with a null argument to execute the program
Binary.main(null);
1 + 1 = 10
public class IntByReference {
    private int value;

    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }

    public void swapToLowHighOrder(IntByReference i) {
        if (this.value > i.value) {
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0);
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b);  // conditionally build swap method to change values of a, b
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16

public class IntByReference {
    private int value;

    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }

    public void swapToLowHighOrder(IntByReference i) {
        if (this.value > i.value) {
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0);
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b);  // conditionally build swap method to change values of a, b
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16

Hacks

Methods and Control Structures

Methods, also known as functions or subroutines, are blocks of code that can be executed repeatedly in a program. A method typically takes input parameters, performs some operations, and returns a result. Methods are used to organize code into reusable units and to reduce code duplication.

Control structures, on the other hand, are constructs that determine the order in which statements in a program are executed. There are three main types of control structures:

Conditional statements (if-else, switch) - which allow the program to make decisions based on certain conditions. Looping statements (for, while, do-while) - which allow the program to execute a block of code repeatedly until a condition is met. Jump statements (break, continue, return) - which allow the program to change the normal flow of execution. Control structures are used to create logic and flow in a program. They allow programmers to control how their code executes and make decisions based on certain conditions.

Math.random

Math.random() is a built-in function in the JavaScript programming language that generates a random number between 0 and 1.

To generate a random integer within a specific range, you can use the following code:

let randomNumber = Math.random();
console.log(randomNumber);
let min = 1;
let max = 10;
let randomInteger = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInteger);
|   let randomNumber = Math.random();
cannot find symbol
  symbol:   class let

Do Nothing By Value

The value of arguments are passed into a method's parameters

Java is pass-by-value, not pass-by-reference for methods

But basically 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: The value of a variable is passed Pass-by-reference: 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"

Int By Reference

This switches two integer numbers to lowest to highest by 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.

Diverse Array

Contains methods and control structures Multiple methods that allow stuff to happen Multiple control structures

Loops For While If statements Fits within data types because contains arrays which is a data type

Takeaway: most code segments no matter what they are on have to do with methods and control structu

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");
            }
        }
    }

AP 2017 Q3 (part b)

public int findLastOccurrence(String str)
{
int n = 1;
while (findNthOccurrence(str, n+1) != -1)
{
n++;
}
return findNthOccurrence(str, n);
}