Show Menu
Cheatography

fundamentals_exam Cheat Sheet by

Cheat Sheet for the exam

Basics

Hello, World

Editing, Compiling, and executing

Built in Datatypes

Integers

Integer Operations

Floating Point Numbers

Floating Point Numbers Operations

String Data Type

String operations

Commands to Split a String Into Separate Parts

Scanner scan = new Scanner(System.in);

        System.out.println("What is your date of birth? (Format: dd mm yyyy) ");
        String dateBirthday = scan.nextLine();

        String[] parts = dateBirthday.split(" ");

        // Storing users birthday data
        int day = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);
        int year = Integer.parseInt(parts[2]);

        // Obtaining today's date:
        int currentDay = LocalDate.now().getDayOfMonth();
        int currentMonth = LocalDate.now().getMonthValue();
        int currentYear = LocalDate.now().getYear();

Math Library

Type Conver­sions

Parsing Comman­d-Line Arguments

Swtich statement

Do-While Loop

Example Functions

Typical Array Problems

Formatted Output

Memory Usage of Data Types

Command Line Input from File

Classes Overview

Method to Read a Matrix From a File

public static double[][] readMatrix(String filename)
    throws java.io.FileNotFoundException{
    File file = new File(filename);
    Scanner input = new Scanner (file);
    
    int rows = input.nextInt();
    int columns = input.nextInt();
    
    double[][] matrix = new double[rows][columns];
    
    for (int i=0;i<rows;i++){
      for (int j=0;j<columns;j++){
        matrix [i] [j]= input.nextDouble();
        
      }   
    }
    
    input.close();
    return matrix;
  }
Two first Integers in a file defines the size of a matrix n x m.

Tutorial Content

Random Arrays

// returns an array of length n containing random integer values
   public static int[] randomIntArray(int n){
      Random random = new Random();
      int[] array = new int[n];
      for(int i=0; i < n; i++){
         array[i] = random.nextInt();
      }
      return array;
   }
   
   // returns an array of length n containing random integer values
   // in the interval [lb,ub]
   public static int[] randomIntArray(int n, int lb, int ub){
      Random random = new Random();
      int[] array = new int[n];
      for(int i=0; i < n; i++){
         array[i] = random.nextInt(ub-lb+1) + lb;
      }
      return array;
   }
   
   // returns an array of length n containing random double values
   public static double[] randomDoubleArray(int n){
      Random random = new Random();
      double[] array = new double[n];
      for(int i=0; i < n; i++){
         array[i] = random.nextDouble();
      }
      return array;
   }
 
   // returns an array of length n containing random double values
   // in the interval [lb,ub]
   public static double[] randomDoubleArray(int n, int lb, int ub){
      Random random = new Random();
      double[] array = new double[n];
      for(int i=0; i < n; i++){
         array[i] = random.nextDouble(ub-lb+1) + lb;
      }
      return array;
   }

Read Double Array.

public static double[] readArray(String filename)
    throws java.io.FileNotFoundException{
    File file = new File(filename);
    Scanner input = new Scanner (file);
    
    int n = input.nextInt();
    
    double[] doubleArray = new double[n];
    
    for (int i=0;i<n;i++){
      doubleArray [i] = input.nextDouble();
    }   
    
    input.close();
    
    return doubleArray;
  }
To read other type array, we substitute the "­dou­ble­s" with int or int[] or nextInt()

Digit Sum Method

public static int totalDigitSum(int n) {

        int numberOfDigits = (String.valueOf(n)).length();
        int sum = 0;
        System.out.print("The total digit sum");

        while(numberOfDigits != 0) {

            sum = sum + (n%10);
            n = n/10;

            numberOfDigits--;

        }

        return sum;

    }

Print Prime Factors

public static void printPrimeFactors(int n) {
        if (n <= 1) {
            System.out.print("No prime factors");
            return;
        }

        for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                System.out.print(i + " ");
                n /= i;
            }
        }
    }
Method to print the prime factors of a given number

Method to compute Factorials (n!)

public static int[] computeFactorials(int n) {
        int[] factorials = new int[n];
        factorials[0] = 1;
        
        for (int i = 1; i < n; i++) {
            factorials[i] = factorials[i - 1] * (i + 1);
        }
        
        return factorials;
    }

Method Simulating Dice Rolling N times

public static double expectedValue (int numberOfTrials){
   
      double sum = 0;
    
      for(int i = 1; i <= numberOfTrials; i++){
         sum = sum + (int) (Math.random() * 6) +1;
      }
      return sum/numberOfTrials;
   }
Program that computes the expected value of rolling a six sided dice. Input parameter is the number of trials

Method for Standard Deviation

// Method that computes standard deviation of an array
    public static double getStandardDeviation(double[] array) {
        double sum = 0;
        double mean = getMean(array);

        for(double i : array) {
            double temp = (i - mean) * (i - mean);
            sum += temp;
        }

        double standardDeviation = sum/array.length;
        standardDeviation = Math.sqrt(standardDeviation);
        return standardDeviation;

    }

Greatest Common Divisor & Least Common Multiple

// GCD
public static int getGcd(int n, int m) {
        while(m%n != 0) {
            int temp = m%n;
            m = n;
            n = temp;
        }
        return n;
    }

// LCM
public static int lcm(int a, int b) {
        int gcd = gcd(a, b);
        return (a / gcd) * b;
    }

Determ­ening the Season

/* Program that asks the user for a date and returns in which season this date falls.

// method calculating determining the season, given the month and day
    public int getSeason(int day, int month) {

        // Formula to translate everything on one 'scale'
        int combinedValue = month*100 + day;

        if (combinedValue >= 321 & combinedValue <= 620) {

            this.season = 1;

        }
        else if (combinedValue >= 621 & combinedValue <= 920) {

            this.season = 2;

        }
        else if (combinedValue >= 921 & combinedValue <= 1220) {

            this.season = 3;

        }
        else {

            this.season = 0;

        }

        return this.season;
    }

Sorting Algorithms

Commands for Random Numbers

 double random1 = Math.random();
                  
      System.out.println("A random value between 0 and 1: " + random1);
      
      double random2 = Math.random()*100;
      
      System.out.println("A random double value between 0 and 100: " + random2);
   
      int random3 = (int) (Math.random()*100);
      
      System.out.println("A random integer value between 0 and 99: " + random3);

Binary Search Method

 public static boolean find(int[] array, int number){
   
      int low = 0;
      int high = array.length-1;
      
      while (low+1 < high) {
         int mid = (high + low) /2;
          
         if (array[mid] == number){
            return true;
         }
         else if (array[mid] < number){
            low = mid;
         }
         else {
            high = mid;
         }      
      }
   
      return ((array[low] == number) || (array[high] == number));
   }

Random Sorted Int Array

public static int[] randomSortedIntArray(int n, int startValue, int maxIncrement){
      Random random = new Random();
      int[] array = new int[n];
      array[0] = startValue;
      for(int i=1; i < n; i++){
         array[i] = array[i-1] + random.nextInt(maxIncrement);
      }
      return array;
   }
Random Sorted Int Array (Basis for Binary Search)

Insertion Sort Algorithm

public static void sort(int[] a) {
    int n = a.length;  // Get the length of the input
                                  array 'a'.
    for (int i = 1; i < n; i++) {
        for (int j = i; j > 0; j--) {
            // This loop iterates from the current
                 position 'i' towards the beginning 
                 of the array.
            if (a[j-1] > a[j]) {
                // If the element at the previous
                    position is greater than the
                     current element,
                // we need to swap them to sort
                    the array in ascending order.
                swap(a, j-1, j);
            } else {
                // If the element at the previous
                 position is not greater than the
                 current element,
                // it means the array is sorted
               up to this point, so we break out of the
                loop.
                break;
            }
        }
    }
}

public static void swap(int[] arr, int index1, int index2) {
    // This function swaps two elements
       in the array 'arr' at the given indices 'index1' 
         and 'index2'.
    int temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}

Random Array in Interval

public static int[] randomArray(int n){
   int[] array = new int[n];
   
   for(int i=0; i<n;i++){
    array [i] =  (int) ( Math.random()*1000 - 500);
   }
   return array;
  }
random array length n, interval int between [-500;500]

Insertion Sort of an Object w.r.t. String/Int

// Insertion Sort Algorithm based on First Name
   public static void sortFirstName(PersonNew[] personList) {

      for(int i = 1; i < personList.length; i++) {

         PersonNew currentPerson = personList[i];
         int j = i - 1;
         boolean flag = true;

         // We will compare current person's name with other ones
         while(j >= 0 && flag) {

            String currentName = currentPerson.getFirstName();
            String testName = personList[j].getFirstName();

            // Checking which name is shorter:
            int minimum = Math.min(currentName.length(), testName.length());
            int k = 0;

            // Now we will check which name is "smaller" based on ascii:
            while(k < minimum) {

               char letterCurrent = currentName.charAt(k);
               char letterTest = testName.charAt(k);

               // Current Name is larger than other
               if(letterCurrent < letterTest) {

                  personList[j+1] = personList[j];
                  j--;
                  break;

               }
               // Current Name is already smaller
               else if(letterTest < letterCurrent) {

                  flag = false;
                  break;

               }
               // They have the same characters, thus we continue going through each string
               else {

                  k++;

               }

               // We reach the end of smaller name, meaning that they have the same name:
               if(k == minimum) {

                  personList[j+1] = personList[j];
                  j--;

               }

            }


         }

         // Inserting in its correct position.
         personList[j+1] = currentPerson;

      }

   }

// Insertion Sort Algorithm based on Height
   public static void sortHeight(PersonNew[] personList) {

      for(int i = 1; i < personList.length; i++) {

         PersonNew currentPerson = personList[i];
         int j = i-1;

         while((j >= 0) && currentPerson.isTaller(personList[j])) {

            personList[j+1] = personList[j];
            j--;

         }

         personList[j+1] = currentPerson;
      }

   }

Objects

Constr­uctor Method for Point / Line

// constructor for a line through points p and q
// sets slope and intercept to Double.NaN for vertical lines
    public Line(Point p, Point q) {

        // vertical line:
        if (p.getX() == q.getX()) {

            this.intercept = Double.NaN;
            this.slope = Double.NaN;

        }

        // otherwise we compute the slope (y2 - y1) / (x2 - x1)
        // and intercept from y = mx + c, using one of the points
        else {

            this.slope = (q.getY() - p.getX()) / (q.getX() - p.getX());
            this.intercept = p.getY() - this.slope * p.getX();

        }
    }
This Constr­uctor computes the equation of the line, given two points

Few Methods for Object Date

// method that  returns true if this date is before  the date given by the argument
    public boolean isBefore(Date date) {

        if (this.year <= date.year) {
            if(this.month <= date.month) {
                if(this.day <= date.day) {
                    return true;
                }
                return false;
            }
            return false;
        }
        return false;
    }

    // method that increments this date by one day
    public void increment() {

        // Array storing days per month
        int[] daysPerMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        // Figure out if its leap year, to change daysPerMonth[2] = 29.
        if(isLeapYear()) {
            daysPerMonth[2] = 29;
        }

        // Check if its last day of the month
        if(this.day == daysPerMonth[this.month]) {
            this.day = 1;

            // Check if its new year:
            if(this.month == 12) {

                this.month = 1;
                year++;

            }
            else {
                month++;
            }
        }
        else {
            day++;
        }

    }

    // method that returns true if the year of this date is a leap year
    private boolean isLeapYear() {

        return (this.year % 4 == 0 && this.year % 100 != 0) || (this.year % 400 == 0);

}
We store dd/mm/yyyy in the Object Date. Constr­uctor method is not shown here.

Methods For Rational Numbers (Object Rational)

// add rational f2 to this rational and return the result.
    public Rational add(Rational f2) {

        if(this.denominator == f2.getDenominator()) {

           int newNumerator = this.numerator + f2.getDenominator();
           return new Rational(newNumerator, this.denominator);

        }
        else {

           // we find the new denominator:
           int newDenominator = findLCM(this.denominator, f2.getDenominator());
           int newNumerator = (this.numerator(newDenominator / this.denominator)) +  (f2.getNumerator()(newDenominator / f2.getDenominator()));

           return new Rational(newNumerator, newDenominator);

        }

    }

// compute the reciprocal of this Rational and return the result
    public Rational reciprocal() {

        return new Rational(this.denominator, this.numerator);

    }

// divide this Rational by Rational f2  and return the result
    public Rational divide(Rational f2) {

        Rational reciprocalf2 = f2.reciprocal();

        int newNum = this.numerator * reciprocalf2.getNumerator();
        int newDen = this.denominator * reciprocalf2.getDenominator();

        return new Rational(newNum, newDen);

    }
Recipr­ocal: x/y becomes y/x.

Runtime Exercises

Run Times

Knapsack Problem

public static int knapsackAlgorithm(int n, int[] profits, int[] volumes, int V) {
    // Create a 2D array 'P' to store the maximum profit for different combinations
 of items and volumes.
    int[][] P = new int[n + 1][V + 1];

    // Initialize the first row (no items) with zeros, as no profit can be gained.
    for (int v = 0; v <= V; v++) {
        P[0][v] = 0;
    }

    // Loop through the items (i) and the available volume (v).
    for (int i = 1; i <= n; i++) {
        for (int v = 0; v <= V; v++) {
            // Check if the volume of the current item can fit in the 
available volume (v).
            if (volumes[i - 1] <= v) {
                // If it can fit, calculate the maximum profit for two options:
                // 1. Including the current item and subtracting its volume 
from the available volume.
                // 2. Excluding the current item.
                P[i][v] = Math.max(profits[i - 1] + P[i - 1]
[v - volumes[i - 1]], P[i - 1][v]);
            } else {
                // If the current item cannot fit, take the maximum profit 
from the previous row.
                P[i][v] = P[i - 1][v];
            }
        }
    }

    // The final element of the 'P' array (bottom-right) contains the 
maximum profit achievable with the given constraints.
    return P[n][V];
}

public static int[] generateRandomArray(int size, int min, int max) {
    // Create an array of the specified size.
    int[] array = new int[size];
    Random rand = new Random();
    
    // Fill the array with random integers in the range [min, max].
    for (int i = 0; i < size; i++) {
        array[i] = rand.nextInt(max - min + 1) + min;
    }
    
    // Return the generated array.
    return array;
}

Magic Square Problem

public static boolean isMagic(int[][] matrix) {

        return (hasUniqueNumbers(matrix) && hasEqualSums(matrix));

    }

    // Method that checks if all rows, columns and 
two diagonals (right & left) have equal sums:
    public static boolean hasEqualSums(int[][] matrix) {

        // Variable to store target sum:
        int targetSum = 0;

        // Target sum = sum of first row
        for(int i = 0; i < matrix.length; i++) {

            targetSum += matrix[0][i];

        }

        int leftDiagonal = 0;
        int rightDiagonal = 0;

        for(int j = 0; j < matrix.length; j++) {

            int sumColumn = 0;
            int sumRow = 0;

            for(int k = 0; k < matrix[0].length; k++) {

                sumRow += matrix[j][k];
                sumColumn += matrix[k][j];

                // Check if we are on the left diagonal:
                if(j == k) {

                    leftDiagonal += matrix[j][k];

                }
                // Check if we are on the right diagonal:
                if(j+k == matrix.length - 1) {

                    rightDiagonal += matrix[j][k];

                }

            }

            // Check if the sum is equal to our target one:
            if (sumRow != targetSum || sumColumn != targetSum) {

                return false;

            }

        }

        // Check if diagonal sums are = target
        if(rightDiagonal != targetSum || leftDiagonal != targetSum) {

            return false;

        }

        return true;

    }

    // Method that checks whether matrix contains 
only unique numbers from 1 to n*n.

    public static boolean hasUniqueNumbers(int[][] matrix) {

        /*
         We know that there will be numbers from 1 to n*n.
         We create boolean array of size n*n which 
will help to flag  not unique numbers.
         Default array element value = false.
        */
        int n = matrix.length;
        boolean[] seenNumber = new boolean[n*n];
        int arrayIndex = 0;

        for(int i = 0; i < matrix.length; i++) {

            for(int j = 0; j < matrix[0].length; j++) {

                int number = matrix[i][j];
                // We check whether the number has 
already been flagged && whether 1 <= number <= n*n
                if(!seenNumber[number - 1] && number >= 1 && number <= (n*n)) {

                    // Number is being flagged:
                    seenNumber[number - 1] = true;

                }
                else {

                    return false;

                }

            }


        }

        return true;

    }


   public static int [][] rotate(int[][] matrix){
      int n = matrix.length;
      int m = matrix[0].length;

      // Create a new matrix to store the rotated elements
      int[][] transpose = new int[n][m];

      for(int i=0;i<n;i++){
         for(int j=0;j<n;j++){
            transpose[i][j]=matrix[j][i];
         }
      }

      int[][] rotated = new int[n][m];
      int x = n-1;
      for (int k = 0; k < n; k++) {
         rotated[k] = transpose[x];
         x--;
      }


      return rotated;
   }

Data Structures

Stack Data Type

Intger Stack Class

import java.util.*;

public class IntegerStack {

    private int size;          // size of the stack
    private Node first;     // top of stack

    // helper linked list class
    private class Node {
        private int value;
        private Node next;
    }

    // Constructor for an empty stack

    public IntegerStack() {

        this.first = null;
        this.size = 0;

    }

    // Returns true if this stack is empty.

    public boolean isEmpty() {
        return first == null;
    }

    // returns the size of this stack
    public int size() {
        return this.size;
    }

    // adds number to the top of the stack
    public void push(int number) {
        Node oldfirst = first;
        first = new Node();
        first.value = number;
        first.next = oldfirst;
        size++;
    }

    public String toString() {

        IntegerStack aux = new IntegerStack();

        String stackString = new String();

        while (!this.isEmpty()) {
            int x = this.pop();
            stackString += x + " ";
            aux.push(x);
        }

        while (!aux.isEmpty()) {
            this.push(aux.pop());
        }

        stackString += "\n";
        return stackString;
    }

    /**
     * Removes and returns the item most recently added to this stack.
     */
    public int pop() {
        // if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        int number = first.value;        // save item to return
        first = first.next;            // delete first node
        size--;
        return number;                   // return the saved item
    }

    public void absoluteValue() {

        IntegerStack aux = new IntegerStack();

        while (!this.isEmpty()) {
            aux.push(Math.abs(this.pop()));
        }

        // put auxiliary stack back on both stacks
        while (!aux.isEmpty()) {
            this.push(aux.pop());
        }

    }

    // Method that checks if two stacks are exactly the same
    public boolean isEqual(IntegerStack secondStack) {

        IntegerStack aux = new IntegerStack();
        boolean flag = true;

        // Stacks are of a different size.
        if(this.size != secondStack.size) {

            flag = false;
            return flag;

        }

        // Checking whether the two are the same
        while(!this.isEmpty() && !secondStack.isEmpty()) {

          int thisNumber = this.pop();
          int secondNumber = secondStack.pop();

          if(!(thisNumber == secondNumber)) {

            // Immediately push back the numbers on top:
            this.push(thisNumber);
            secondStack.push(secondNumber);

            flag = false;
            break;

          }

          aux.push(thisNumber);

        }

        // Restoring both stacks:
        while (!aux.isEmpty()) {

          int number = aux.pop();

          this.push(number);
          secondStack.push(number);

        }

        return flag;

    }

    // Method that reverses the order of the stack:
    public void reverse() {

        // empty stack:
        if(this.isEmpty()) {

            System.out.println("Empty stack was provided.");
            return;

        }

        Queue<Integer> tempQ = new Queue<Integer>();

        // Putting all elements from stack to queue data structure
        while(!this.isEmpty()) {

            tempQ.enqueue(this.pop());

        }

        // Putting everything form queue to stack, to get reverse order
        while(!tempQ.isEmpty()) {

            this.push(tempQ.dequeue());

        }

    }

// Fills stack with -1 and 1 randomly
    public void fillStackRandom() {

        Random randomNumber = new Random();

        for(int i = 0; i < 100; i++) {

            int number = randomNumber.nextInt(2) == 0 ? 1 : -1;
            this.push(number);

        }

    }

}

Queue Data Type

Queue Class

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Queue<Item> implements Iterable<Item> {
    private int n;         // number of elements on queue
    private Node first;    // beginning of queue
    private Node last;     // end of queue

    // helper linked list class
    private class Node {
        private Item item;
        private Node next;
    }

// Initializes an empty queue.
    public Queue() {
        first = null;
        last  = null;
        n = 0;
    }

// Returns true if this queue is empty.
    public boolean isEmpty() {
        return first == null;
    }

// Returns the number of items in this queue.
    public int length() {
        return n;     
    }

// Returns the item least recently added to this queue.
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        return first.item;
    }

// Add the item to the queue.
public void enqueue(Item item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty()) first = last;
        else           oldlast.next = last;
        n++;
    }

// Removes and returns the item on this queue that was least recently added.
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = first.item;
        first = first.next;
        n--;
        if (isEmpty()) last = null;   // to avoid loitering
        return item;
    }

// Returns a string representation of this queue.
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    } 

    /*
     method to remove all negative integers from a queue.
     it checks the last element of the queue, if its not negative
     element goes to the back of the queue,
    */
    public void removeNegatives() {

        int sizeQ = this.size();

        for(int i = 0; i < sizeQ; i++) {

            Item lastElement = this.dequeue();

            if((int) lastElement >= 0) {

                // it's positive, thus put the item back of the queue
                this.enqueue(lastElement);

            }

        }

    }

// Returns an iterator that iterates over the items in this queue in FIFO order.
    public Iterator<Item> iterator()  {
        return new ListIterator();  
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator implements Iterator<Item> {
        private Node current = first;

        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }
  
}

ArrayList data structure Commands

ArrayList<Integer> list = new ArrayList<>();

// Add an element to the list
	list.add(x);

// Copy list
	list.clone();

// Element at the index i
	list.get(i);

// Is element present in the list, returns T/F
	list.contains(x);

// Returns the index of the item x
	list.indexOf(x);

// Returns the size of list
	list.size();

// Check if list is empty, return T/F
	list.isEmpty();

// Replace an element x at index i with element y
	list.set(i, y);

// ArrayList into array: 

size of array is same as the ArrayList
    int[] arr = new int[list.size()];

    // Convert ArrayList into an array
    list.toArray(arr);

// Convert ArrayList into String, basically ouputs the list
	list.toString();

Advanced Tutorial Content

Call Center Exercise

import java.util.ArrayList;

public class CallCenter{

   // Constants for the simulation
   private final int numberOfEmployees = 10;
   private final int numberOfTimePeriods = 480;
   private final int maxNumberOfCustomers = 5;
   private final int maxServiceTime = 5;

   // Variables to store simulation results
   private int totalWaitTime = 0;
   private int totalNumberOfServedCustomers = 0;
   private int finalQueueLength = 0;

   public static void main (String[] args){

      // Create an instance of the CallCenter class
      CallCenter myCallCenter = new CallCenter();

      // Run the call center simulation
      myCallCenter.runSimulation();

      // Print the simulation statistics
      myCallCenter.printStatistics();

   }

   public void printStatistics(){

      // Printing the simulation statistics.
      System.out.println("The call center simulation was run with " +  numberOfEmployees + " employees.");
      System.out.println("Between 9am and 5pm " + (finalQueueLength + totalNumberOfServedCustomers) + " customers have called");
      System.out.println("The average wait time was "+ (1.0*totalWaitTime / totalNumberOfServedCustomers) + " minutes.");
      System.out.println("Number of unserved customers: " + finalQueueLength);

   }

   // runs the simulation as described in the assignment
   public void runSimulation(){

      // We begin with an empty queue
      Queue<Customer> myQ = new Queue<>();

      // List of Employees
      ArrayList<Employee> listEmployees = assignEmployee(numberOfEmployees);

      // We go through the day:
      for(int currentTime = 0; currentTime < numberOfTimePeriods; currentTime++) {

         // Each minute new customers "join the queue"
         randomArrivals(maxServiceTime, maxNumberOfCustomers, currentTime, myQ);

         // For each employee we assign a new customer if possible:
         for(Employee employee : listEmployees) {

            // There are customers in queue and employee is available:
            if(employee.getAvailableAt() <= currentTime && !myQ.isEmpty()) {

               Customer servedCustomer = myQ.dequeue();

               // Adding how long customer waited to the total & recording him as served one.
               totalWaitTime += (currentTime - servedCustomer.getArrivalTime());
               totalNumberOfServedCustomers++;

               int timeRequired = servedCustomer.getServiceTime();

               // Change employees available time
               employee.setAvailableAt(currentTime + timeRequired);

            }

         }

         // After 8 hours, number of people not served:
         finalQueueLength = myQ.size();

      }


   }

   // helper method to fill employee list
   public ArrayList<Employee> assignEmployee(int n) {

      ArrayList<Employee> list = new ArrayList<>();

      for(int i = 0; i < n; i++) {

         // Create Employee objects and add them to the list
         Employee emp = new Employee(i);
         list.add(emp);

      }

      return list;

   }

   // helper method for simulating callers arriving to the queue:
   public void randomArrivals(int maxServiceTime, int maxNumberOfCustomers, int timeOfArrival, Queue myQ) {

      int numberOfArrivals = (int) (Math.random()*maxNumberOfCustomers + 1);

      for(int i = 0; i < numberOfArrivals; i++){

         // each customer will have different service time
         int serviceTime = (int) (Math.random()*maxServiceTime + 1);

         Customer customer = new Customer(timeOfArrival, serviceTime);

         // add customer to the end of the queue
         myQ.enqueue(customer);

      }

   }


}

Employee Class For Call Center

public class Employee{
  
  private final int id;
  private  int availableAt;
  
  // constructs an Employee with an id and initial available time at 0
  public Employee (int id){
    this.id = id;
    this.availableAt = 0;
  }
    
  // returns the id of this employee
  public int getId(){
    return this.id; 
  }
  
  // returns the time at which an employee is available again
  public int getAvailableAt(){
    return this.availableAt; 
  }
  
  // sets the time at which an employee is available again
  public void setAvailableAt(int time){
     this.availableAt = time; 
  }
  
}

Customer Class For Call Center

public class Customer{

  private final int arrivalTime;
  private final int serviceTime;
  
  // constructs a Customer with arrival time a and duration d
  public Customer (int arrivalTime, int serviceTime){
    this.arrivalTime = arrivalTime;
    this.serviceTime = serviceTime;
  }
  
  // returns the arrival time of this customer
  public int getArrivalTime(){
    return this.arrivalTime; 
  }
  
  // returns the service time of this customer
  public int getServiceTime(){
    return this.serviceTime; 
  }
  
}

Elevator Problem

// method to solve the number of elevators problem:
    public static int numberOfElevators(ArrayList<Person> personList) {

        ArrayList<Integer> elevators = new ArrayList<>();

        // Initial "bin" is empty:
        elevators.add(0);
        int elevatorCount = 1;

        for(Person person:personList) {

            // flag will tell whether the person fitted in the current elevator:
            boolean flag = false;
            int weight = person.getWeight();


            // Check if person fits in one of the existing bins (elevators):
            for (int i = 0; i < elevatorCount; i++) {

                int currentElevatorWeight = elevators.get(i);

                // Person fits in the elevator
                if((currentElevatorWeight + weight) <= 450) {

                    elevators.set(i, weight + currentElevatorWeight);
                    flag = true;

                }

            }

            // Other elevators didn't have space, we open new "bin":
            if(!flag) {

                elevators.add(weight);
                elevatorCount++;

            }

        }

        return elevatorCount;

    }


// helper method to sort the list descending or ascending by weight. char d for descending and a for ascending.
    public static void insertionSortWeight(ArrayList<Person> personList, char order){

        int n = personList.size();

        for (int i = 1; i < n; i++) {

            Person key = personList.get(i);
            int j = i - 1;

            // Compare weights for sorting
            if (order == 'a' || order == 'A') { // Ascending order

                while (j >= 0 && personList.get(j).getWeight() > key.getWeight()) {

                    personList.set(j + 1, personList.get(j));
                    j--;

                }

            } else if (order == 'd' || order == 'D') { // Descending order

                while (j >= 0 && personList.get(j).getWeight() < key.getWeight()) {

                    personList.set(j + 1, personList.get(j));
                    j--;

                }

            }

            personList.set(j + 1, key);
        }


    }

Game Of Stacks

public int runGameStrategy1(){

        // The first step of the game is to create 
the needed random stack
        IntegerStack gameStack = IntegerStack.createRandomStack();


        // From here we go to the procedures of the game itself
        // generate two player scores and ID's
        int aliceID = 1;
        int bobID = -1;

        int aliceScore = 0;
        int bobScore = 0;


        // Move tracker that checks whos turn it is
        int move = 0;

        // The game starts
        while (!gameStack.isEmpty()){

            // First we check whos turn it is since both 
players only take 1 turn every time due to the strategy
            if (move % 2 == 0) {
                // Alice starts and ONLY keeps every 1
                if (gameStack.pop() == aliceID){
                    aliceScore += 1;
                }
            } else {
                // Bob starts and ONLY keeps every -1
                if (gameStack.pop() == bobID){
                    bobScore += 1;
                }
            }
            move += 1;
        }

        if (aliceScore > bobScore) {
            return 1;
        } else if (aliceScore == bobScore) {
            return 0;
        } else {
            return -1;
        }
    }


    public int runGameStrategy2() {
        // The first step of the game is to create 
the needed random stack
        IntegerStack gameStack = IntegerStack.createRandomStack();

        int aliceScore = 0;
        int bobScore = 0;

        // Move tracker that checks whos turn it is
        int currentPlayer = 0;

        // The game starts
        while (!gameStack.isEmpty()) {
            int top = gameStack.pop();

            if( currentPlayer%2 == 0 ) {

                if (top == 1) {
                    int consecOnes = 1;
                    if(gameStack.isEmpty()) break;

                    int next = gameStack.pop();
                    if (next == 1) {
                        consecOnes++;
                    } else consecOnes = 0;

                    aliceScore += consecOnes;
                }

            } else if (top == -1) {
                bobScore += 1;
            }

            currentPlayer++;
        }

        if (aliceScore > bobScore) {
            return 1;
        } else if (aliceScore == bobScore) {
            return 0;
        } else {
            return -1;
        }

    }

Average BMI method

// Method that calculates average BMI index per age group:
    public static void averageBMI(ArrayList<Person> personList) {

        int[] ageGroup = {20,30,40,50,60,70};

        // 20-29 group corresponds to index 0, 30-39 to 1 and so on
        int[] groupCount = new int[ageGroup.length];
        double[] groupSumBMI = new double[ageGroup.length];

        for(int i = 0; i < personList.size(); i++) {

            Person currentPerson = personList.get(i);

            // age/10 - 2, will give correct index(group number) of the object for its place in the arrays.
            int personsGroup = currentPerson.getAge()/10 - 2;
            groupCount[personsGroup]++;

            groupSumBMI[personsGroup] += currentPerson.getBMI();

        }
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Passe Compose Cheat Sheet
          Security+ 601 Exam Cheat Sheet