//BASIC ARRAY CONCEPTS

//Declare an array and then allocate memory
int myArray[];
myArray = new int[4];

//Declare while directly assign values
int[] myArray1 = new int[]{ 1, 6, 7, 9};

//Initialize element
myArray[0] = 2;

//Create an array of objects
Object[] arr = new Object[5];
//Basic for loop to print elements of array
int[] arr1 = {0, 6, 8, 2};

// Looping through array by incrementing value of i
//'i' is an index of array 'arr1'
for (int i = 0; i < arr1.length; i++) {

    // Print array element present at index i
    System.out.println(i + " " + arr1[i]);

}


for(int value: arr1){
    System.out.println(value);
}
0 0
1 6
2 8
3 2
0
6
8
2
void setArray(int[] arr, int n) {
    // your code here
}

int[] array = new int[10];
setArray(array, 10);

for (int i = 0; i<array.length; i++) {
    System.out.println(array[i]);
}
0
0
0
0
0
0
0
0
0
0
public static int maximum(int[] array) {
    //variable that holds value of max value
    int maxValue = array[0];
    //for each number in the array..
    for (int number: array) {
      //checks if current index is greater than maxValue
      if (number > maxValue) {
        //if new max value found, replace current maxValue
        maxValue = number;
      }
    }
    return maxValue;
  }

//tester array
int[] test = {3, 5, 7, 2, 10};

//returns 10
maximum(test);
10
public static void print2D(int mat[][])
    {
        // For each row of the array (goes one array at a time)
        for (int row = 0; row < twoDArray1.length; row++) {
 
            //Goes through each element of the array
            for (int column = 0; column < twoDArray1[row].length; column++)
                System.out.print(mat[row][column] + " ");

            // runs for every row (not every element)
            System.out.println();
        }
    }

    int twoDArray1[][] = { { 1, 2, 3 },
                           { 4, 6, 7 },
                           { 8, 9, 10} };
 
print2D(twoDArray1);
1 2 3 
4 6 7 
8 9 10 
public static int averageDiagonal (int[][] array2D) {
    // your code here
    return 0;
}

int[][] arr = {
    {1,2,3,4,5,6},
    {7,8,9,10,11,12},
    {0,1,2,3,4,5},
    {10,11,12,13,14,15},
    {15,16,17,18,19,20}
};

System.out.println(averageDiagonal(arr));
0
//create a new 2-d array (default to all 0s)
int[][] twoDArray = new int[3][3];

//access the value at row 2 column 1
twoDArray[1][0];

twoDArray[twoDArray.length - 1][twoDArray[0].length - 1];
0
//Finds the maximum in an array
public static int average(int[] array) {
    // put your code here
    return 0;
}

//tester array
int[] test = {3, 5, 7, 2, 10};

//returns 10
System.out.println(average(test));
0
public class Hack {
    void merge(String arr[], int l, int m, int r)
    {
        // Find the sizes of two subarrays to be merged
        int n1 = m - l + 1;
        int n2 = r - m;

        /* Create temp arrays */
        String[] L = new String[n1];
        String[] R = new String[n2];

        /* Copy data to temp arrays */
        for (int i = 0; i < n1; ++i)
            L[i] = arr[l + i];
        for (int j = 0; j < n2; ++j)
            R[j] = arr[m + 1 + j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of merged subarray array
        int k = l;
        while (i < n1 && j < n2) {
            if (L[i].compareTo(R[j]) <= 0) {
                arr[k] = L[i];
                i++;
            }
            else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy remaining elements of L[] if any */
        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        /* Copy remaining elements of R[] if any */
        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    public void sort(String arr[], int l, int r) {
        if (l < r) {
            int mid = l + (r - l) / 2;

            sort(arr, l, mid);
            sort(arr, mid + 1, r);

            //run merge
            merge(arr, l, mid, r);
        }

    }

    public static void main(String[] args) {
        Hack hack = new Hack();
        String[] test = {"string1", "ddfff", "w32wfz", "okmqji", "alih"};
        hack.sort(test, 0, test.length - 1);
        System.out.println(Arrays.toString(test));
    }
}
Hack.main(null);
[alih, ddfff, okmqji, string1, w32wfz]
/**
 *  Implementation of a Double Linked List;  forward and backward links point to adjacent Nodes.
 *
 */

 public class LinkedList<T>
 {
     private T data;
     private LinkedList<T> prevNode, nextNode;
 
     /**
      *  Constructs a new element
      *
      * @param  data, data of object
      * @param  node, previous node
      */
     public LinkedList(T data, LinkedList<T> node)
     {
         this.setData(data);
         this.setPrevNode(node);
         this.setNextNode(null);
     }
 
     /**
      *  Clone an object,
      *
      * @param  node  object to clone
      */
     public LinkedList(LinkedList<T> node)
     {
         this.setData(node.data);
         this.setPrevNode(node.prevNode);
         this.setNextNode(node.nextNode);
     }
 
     /**
      *  Setter for T data in DoubleLinkedNode object
      *
      * @param  data, update data of object
      */
     public void setData(T data)
     {
         this.data = data;
     }
 
     /**
      *  Returns T data for this element
      *
      * @return  data associated with object
      */
     public T getData()
     {
         return this.data;
     }
 
     /**
      *  Setter for prevNode in DoubleLinkedNode object
      *
      * @param node, prevNode to current Object
      */
     public void setPrevNode(LinkedList<T> node)
     {
         this.prevNode = node;
     }
 
     /**
      *  Setter for nextNode in DoubleLinkedNode object
      *
      * @param node, nextNode to current Object
      */
     public void setNextNode(LinkedList<T> node)
     {
         this.nextNode = node;
     }
 
 
     /**
      *  Returns reference to previous object in list
      *
      * @return  the previous object in the list
      */
     public LinkedList<T> getPrevious()
     {
         return this.prevNode;
     }
 
     /**
      *  Returns reference to next object in list
      *
      * @return  the next object in the list
      */
     public LinkedList<T> getNext()
     {
         return this.nextNode;
     }

     public void setNext(LinkedList<T> next) {
        this.nextNode = next;
    }
    
    // public void setNext(T data) {
    //     this.nextNode = new LinkedList<>(data);
    // }
    
 
 }

 import java.util.Iterator;

/**
 * Queue Iterator
 *
 * 1. "has a" current reference in Queue
 * 2. supports iterable required methods for next that returns a generic T Object
 */
class QueueIterator<T> implements Iterator<T> {
    LinkedList<T> current;  // current element in iteration

    // QueueIterator is pointed to the head of the list for iteration
    public QueueIterator(LinkedList<T> head) {
        current = head;
    }

    // hasNext informs if next element exists
    public boolean hasNext() {
        return current != null;
    }

    // next returns data object and advances to next position in queue
    public T next() {
        T data = current.getData();
        current = current.getNext();
        return data;
    }
}

/**
 * Queue: custom implementation
 * @author     John Mortensen
 *
 * 1. Uses custom LinkedList of Generic type T
 * 2. Implements Iterable
 * 3. "has a" LinkedList for head and tail
 */
public class Queue<T> implements Iterable<T> {
    LinkedList<T> head = null, tail = null;

    /**
     *  Add a new object at the end of the Queue,
     *
     * @param  data,  is the data to be inserted in the Queue.
     */
    public void add(T data) {
        // add new object to end of Queue
        LinkedList<T> tail = new LinkedList<>(data, null);

        if (this.head == null)  // initial condition
            this.head = this.tail = tail;
        else {  // nodes in queue
            this.tail.setNextNode(tail); // current tail points to new tail
            tail.setPrevNode(this.tail);
            this.tail = tail;  // update tail
        }
    }

    public void addList(T[] lists) {
        for (T data : lists) {
            this.add(data);
        }
      }

    /**
     *  Returns the data of head.
     *
     * @return  data, the dequeued data
     */
    public T delete() {
        T data = this.peek();
        if (this.tail != null) { // initial condition
            this.head = this.head.getNext(); // current tail points to new tail
            if (this.head != null) {
                this.head.setPrevNode(tail);
            }
        }
        return data;
    }

    /**
     *  Returns the data of head.
     *
     * @return  this.head.getData(), the head data in Queue.
     */
    public T peek() {
        return this.head.getData();
    }

    /**
     *  Returns the head object.
     *
     * @return  this.head, the head object in Queue.
     */
    public LinkedList<T> getHead() {
        return this.head;
    }

    /**
     *  Returns the tail object.
     *
     * @return  this.tail, the last object in Queue
     */
    public LinkedList<T> getTail() {
        return this.tail;
    }

    /**
     *  Returns the iterator object.
     *
     * @return  this, instance of object
     */
    public Iterator<T> iterator() {
        return new QueueIterator<>(this.head);
    }

    /**
     * Returns if queue is empty
     * 
     * @return boolean if it is empty
     */
    public boolean isEmpty() {
      return this.head == null;
    }

    /**
     * Changes the head
     * 
     */
    public void setHead(LinkedList<T> h) {
        this.head = h;
    }

    /**
     * Returns size of queue
     * 
     * @return size of queue
     */ 
    public int size() {
        int sz = 0;
        for (T e: this) {
            sz++;
        }
        return sz;
    }
    
    public String toString() {
      int count = 0;
      String str = "";
      for (T e : this) {
        str += e + " ";
        count++;
      }
      return "count: " + count + ", data: " + str;
    }
}
abstract class Sorter<T> {
    String name;
    double stime;
    double etime;
    double difftime;
    int compares;
    int swaps;


    public Sorter(String name) {
        this.name = name;
    }

    abstract public Queue<T> sort(Queue<T> list, boolean verbose);

    public Queue<T> sort(Queue<T> list) {
        return this.sort(list, true);
    }

    public void start() {
        this.stime = System.nanoTime();
    }

    public void end()  {
        this.etime = System.nanoTime();
    }

    public double elapsedtime()  {
        difftime = etime - stime;
        return difftime;
    }

    public void incrementcompare() {
        compares++;
    }

    public void incrementswap() {
        swaps++;
    }

    public int printcomp() {
        return this.compares;
    }

    public int printswap() {
        return this.swaps;
    }
}
/**

A class representing the Merge Sort algorithm for sorting a Queue of elements

@param <T> The type of elements in the Queue, must implement Comparable
*/
class Merge<T extends Comparable<T>> extends Sorter<T> {

    /**
    
    Creates a new instance of Merge Sort
    */
    public Merge() {
    super("Merge Sort");
    }
    /**
    
    Sorts the given Queue of elements using Merge Sort algorithm
    @param q The Queue of elements to be sorted
    @param verbose A boolean indicating whether to print out the sorting process or not
    @return The sorted Queue of elements
    */
    public Queue<T> sort(Queue<T> q, boolean verbose) {
    super.start();
    q.setHead(mergeSort(q.getHead()));
    super.end();
    return q;
    }

    private LinkedList<T> mergeSort(LinkedList<T> head) {
    // Base case: if the linked list is empty or has only one element
    if (head == null || head.getNext() == null) {
    return head;
    }
    
    // Find the middle node of the linked list
    LinkedList<T> middle = getMiddle(head);
    LinkedList<T> nextOfMiddle = middle.getNext();
    middle.setNext(null);
    
    // Recursively sort the left and right halves of the linked list
    LinkedList<T> left = mergeSort(head);
    LinkedList<T> right = mergeSort(nextOfMiddle);
    
    // Merge the two sorted halves of the linked list
    return merge(left, right);
    }
    
    private LinkedList<T> getMiddle(LinkedList<T> head) {
    // Base case: if the linked list is empty
    if (head == null) {
    return head;
    }
    
    // Initialize two pointers: slow and fast
    LinkedList<T> slow = head;
    LinkedList<T> fast = head;
    
    // Traverse the linked list using two pointers:
    // slow moves one node at a time, while fast moves two nodes at a time
    while (fast.getNext() != null && fast.getNext().getNext() != null) {
    slow = slow.getNext();
    fast = fast.getNext().getNext();
    }
    
    // The slow pointer is now pointing to the middle node of the linked list
    return slow;
    }
    
    private LinkedList<T> merge(LinkedList<T> left, LinkedList<T> right) {
    LinkedList<T> result = null;
    
    // Base case: if one of the linked lists is empty, return the other one
    if (left == null) {
    return right;
    }
    
    if (right == null) {
    return left;
    }
    
    // Compare the first nodes of the left and right linked lists,
    // and recursively merge the remaining halves until all nodes are merged
    if (left.getData().compareTo(right.getData()) <= 0) {
            result = left;
            result.setNext(merge(left.getNext(), right));
        } else {
            result = right;
            result.setNext(merge(left, right.getNext()));
        }

        super.incrementswap();
        super.incrementcompare();

        return result;
    }
}
public class Tester {
    private static double calcAvg(ArrayList<Double> arr) {
        double sum = 0;
        if(!arr.isEmpty()) {
            for (Double i : arr) {
                sum += i;
            }
            return sum / arr.size();
        }
        return sum;
    }
    public static void main (String[] args) {
        List<Sorter<Integer>> sorters = new ArrayList<Sorter<Integer>>();
        sorters.add(new Merge<>());
        int size = 5000;
        for (Sorter i : sorters) {
            int test = 1;
            ArrayList<Double> elapsed = new ArrayList<Double>();
            ArrayList<Double> comp = new ArrayList<Double>();
            ArrayList<Double> swap = new ArrayList<Double>();
            while (test <= 20) {
                ArrayList<Integer> arr = new ArrayList<Integer>();
                for (int j = 0; j < size; j++) {
                    int rand = (int) Math.floor(Math.random() * size * 10);
                    arr.add(rand);
                }
                Queue<Integer> q = new Queue<>();
                q.addList(arr.toArray(new Integer[size]));
                i.sort(q);
                elapsed.add(i.elapsedtime());
                comp.add(new Double(i.printcomp()));
                swap.add(new Double(i.printswap()));
                test++;
            }
            System.out.println(i.name);
            System.out.printf("Average Elapsed time: %.10fs\n", calcAvg(elapsed)/1000000000);
            System.out.printf("Average Number of compares: %.2f\n", calcAvg(comp));
            System.out.printf("Average Number of swaps: %.2f\n", calcAvg(swap));
            System.out.println();
        }
        System.out.println();
    }
}
Tester.main(null);
Merge Sort
Average Elapsed time: 0.0021541165s
Average Number of compares: 579877.35
Average Number of swaps: 579877.35


public class BinarySearch {
    
    private int search(int[] array, int group1, int group2, int selected ) {

        // if group1 index is greater than group2 or group1 index is greater than largest index, stop running and return -1

        if (group1 <= group2 && group1 < array.length-1) {
            // obtain the middle index

            int mid = group1+(group2-1)/2;
            if (selected == array[mid]) {
                // return index if selected is found
                return mid;

            } else if (selected < array[mid]) {
                // update index 

                return search(array, group1, mid-1, selected);
            } else if (selected > array[mid]) {

                // update index  and run search again
                return search(array, mid+1, group2, selected);
            }
        }
        return -1;
    }
    public int search(int[] array, int selected) {

        return this.search(array, 0, array.length-1, selected);
    }
    public static void main() {

        BinarySearch binary = new BinarySearch();

        int[] array = {1, 3, 5, 7, 9, 23, 45, 67};

        int index = binary.search(array, 45);
        
        System.out.println(index);
    }
}
BinarySearch.main();
6
public class UnsortedSearch {

    void merge(int arr[], int l, int m, int r) {
    
        int n1 = m - l + 1;

        int n2 = r - m;

        int[] L = new int[n1];
        int[] R = new int[n2];

        for (int i = 0; i < n1; ++i)
            L[i] = arr[l + i];

        for (int j = 0; j < n2; ++j)
            R[j] = arr[m + 1 + j];

        int i = 0, j = 0;

        int k = l;

        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            }

            else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    public void sort(int arr[], int l, int r) {
        if (l < r) {
            int mid = l + (r - l) / 2;
            sort(arr, l, mid);
            sort(arr, mid + 1, r);
            merge(arr, l, mid, r);
        }
    }

    private int search(int[] array, int selected) {
        this.sort(array,0,array.length-1);

        BinarySearch search = new BinarySearch();

        return search.search(array, selected);
    }
    
    public static void main() {
        UnsortedSearch search = new UnsortedSearch();
        
        int[] array = {5, 6, 3, 1, 8, 9, 4, 7, 2};
        int index = search.search(array, 7);
        
        System.out.println(index);
    }
}
UnsortedSearch.main();
6
public class StepTracker {
	private int activeDaysCount = 0;
	private int totalDays = 0;
	private int totalSteps = 0;
	private int minSteps;
	
	public StepTracker(int steps) {
		minSteps = steps;
	}
	
	public void addDailySteps(int steps) {
		if (steps >= minSteps) {
			activeDaysCount++;
		}
		totalDays++;
		totalSteps += steps;
	}
	
	public int activeDays() {
		return activeDaysCount;
	}
	
	public double averageSteps() {
		if (totalDays == 0) {
			return 0.0;
		}
		return (double) totalSteps / totalDays;
	}
}
public class ArrayTester {
    public static int[] getColumn(int[][] arr2D, int c) {
        // Create 1D array that will contain the column values
        int[] column = new int[arr2D.length];
        // Add all values in the specified column to the column array. Iterate through each row
        for (int i = 0; i < arr2D.length; i++) {
            column[i] = arr2D[i][c];
        }
        return column;
    }   

    public static boolean hasAllValues(int[] arr1, int[] arr2) {
        // Implementation not shown
    }

    public static boolean containsDuplicates(int[] arr) {
        // Implementation not shown
    }

    public static boolean isLatin(int[][] square) {
        // Get the first row array of the 2D array
        int[] firstRow = square[0];
        // Check if the first row contains any duplicate values
        if (containsDuplicates(firstRow) != true) {
            return false;
        }
        // For each row under the first, check if it contains all of the values of the first row
        for (int i = 1; i < square.length; i++) {
            if (hasAllValues(firstRow, square[i]) != true) {
                return false;
            }
        }
        // For each column in the square, check if it contains all of the values of the first row
        for (int j = 0; j < square[0].length; j++) {
            int[] column = getColumn(square, j);
            if (hasAllValues(firstRow, column) != true) {
                return false;
            }
        }
        return true;
    }
}
// Position class that will be processed by the Successors class
public class Position {
    public Position(int r, int c) {
        // Implementation not shown
    }
}

public class Successors {
    // Static function to return the position (row and column) of the searched value
    public static Position findPosition(int num, int[][] intArr) {
        boolean found = false;
        // Iterate through rows and columns to search through every element of the 2D array
        for (int i = 0; i < intArr.length; i++) {
            for (int j = 0; j < intArr[i].length; j++) {
                // Stop the search once the element is found
                if (intArr[i][j] == num) {
                    found = true;
                    Position positionObject = new Position(i, j);
                    break;
                }
            }
        }
        // Return null if the element is not found
        if (found == false) {
            return null;
        } else {
            return positionObject;
        }
        
    }

    // Static function
    public static Position[][] getSuccessorArray(int[][] intArr) {
        // Instantiate new array with the same dimensions as intArr
        Position[][] successorArray = new Position[intArr.length][intArr[0].length];
        // Set a Position object (position of respective intArr element + 1) for each element of successorArray
        for (int i = 0; i < successorArray.length; i++) {
            for (int j = 0; j < successorArray[i].length; j++) {
                successorArray[i][j] = findPosition(intArr[i][j] + 1, intArr);
            }
        }
        
        return successorArray;
    }
}
public class StringFormatter {
    public static int totalLetters(List<String> wordList) {
        int total = 0;
        // Add the length of every word in wordList to get the total letters
        for (int i = 0; i < wordList.size(); i++) {
            total += wordList.get(i).length();
        }
        return total;
    }

    public static int basicGapWidth(List<String> wordList, int formattedLen) {
        // Get the number of gaps for the wordList
        int numGaps = wordList.size() - 1;
        // Get the number of spaces by subtracting the total letters from the formatted sentence length
        int numSpaces = formattedLen - totalLetters(wordList);
        // Divide using int type to get rid of remainders, effectively getting the basic gap width
        int gapWidth = numSpaces/numGaps;
        return gapWidth;
    }

    public static int leftoverSpaces(List<String> wordList, int formattedLen) {
        // Implementation not shown
    }

    public static String format(List<String> wordList, int formattedLen) {
        // Instantiate empty string that will ultimately contain the formatted string
        String formattedString = "";
        // Get leftover spaces
        int leftover = leftoverSpaces(wordList, formattedLen);
        // Get basic gap width
        int gapWidth = basicGapWidth(wordList, formattedLen);
        for (int i = 0; i < wordList.size(); i++) {
            // Add each word to formattedString
            formattedString += wordList.get(i);
            // If not the last word, add the basic gap width, as well as a leftover space if applicable
            if (i < wordList.size() - 1) {
                for (int j = 0; j < gapWidth; j++) {
                    formattedString += " ";
                }
                if (leftover > 0) {
                    formattedString += " ";
                    leftover--;
                }
            }
        }

        return formattedString;
    }
}
//Example finding the average an array. 

//Finds the average of an array
public static double average(int[] array) {
    // Initialize sum to be 0
    int sum = 0;
    // Add all elements to sum
    for (int item : array) {
        sum += item;
    }
    // Divide sum by total number of elements to get the average. Note the double cast
    double average = (double) sum/array.length;
    return average;
}

//tester array
int[] test = {3, 5, 7, 2, 10};

//returns 5.4
System.out.println(average(test));
5.4
public static double averageDiagonal (int[][] array2D) {
    // Initialize important variables to control the function
    int sum = 0;
    int index = 0;
    int count = 0;
    // Loop through the 2d array by checking each row
    for (int[] array : array2D) {
        // Using the index variable, check the elements in a diagonal (going bottom right), 
        // adding them to the sum until there is no more elements in the current diagonal position
        try {
            sum += array[index];
            index++;
            count++;
        } catch (Exception e) {
            break;
        }
    }
    // Divide sum by total number of elements and double cast in order to find the average value
    double average = (double) sum/count;
    return average;
}

int[][] arr = {
    {1,2,3,4,5,6},
    {7,8,9,10,11,12},
    {0,1,2,3,4,5},
    {10,11,12,13,14,15},
    {15,16,17,18,19,20}
};

System.out.println(averageDiagonal(arr));
8.6