iterator = cursorSpace[head];
+ for (int i = 0; i < count; i++) {
+ if (iterator.element.equals(element)) {
+ return i;
+ }
+ iterator = cursorSpace[iterator.next];
+ }
+
+
+ return -1;
+ }
+
+
+ /**
+ * @param position , the logical index of the element , not the actual one
+ * within the [cursorSpace] array .
+ * this method should be used to get the index give by indexOf() method.
+ * @return
+ */
+
+ public T get(int position) {
+
+ if (position >= 0 && position < count) {
+
+ int start = head;
+ int counter = 0;
+ while (start != -1) {
+
+ T element = cursorSpace[start].element;
+ if (counter == position){
+ return element;
+ }
+
+ start = cursorSpace[start].next;
+ counter++;
+ }
+
+ }
+
+ return null;
+ }
+
+
+ public void removeByIndex(int index){
+
+ if(index >= 0 && index < count){
+
+ T element = get(index);
+ remove(element);
+ }
+
+ }
+
+ public void remove(T element) {
+
+
+ Objects.requireNonNull(element);
+
+ // case element is in the head
+ T temp_element = cursorSpace[head].element;
+ int temp_next = cursorSpace[head].next;
+ if (temp_element.equals(element)) {
+ free(head);
+ head = temp_next;
+ } else { // otherwise cases
+
+ int prev_index = head;
+ int current_index = cursorSpace[prev_index].next;
+
+ while (current_index != -1 ) {
+
+ T current_element = cursorSpace[current_index].element;
+ if(current_element.equals(element)){
+ cursorSpace[prev_index].next = cursorSpace[current_index].next;
+ free(current_index);
+ break;
+ }
+
+ prev_index = current_index;
+ current_index = cursorSpace[prev_index].next;
+ }
+
+ }
+
+
+ count--;
+
+ }
+
+ private void free(int index) {
+
+ Node os_node = cursorSpace[os];
+ int os_next = os_node.next;
+ cursorSpace[os].next = index;
+ cursorSpace[index].element = null;
+ cursorSpace[index].next = os_next;
+
+ }
+
+
+ public void append(T element) {
+
+ Objects.requireNonNull(element);
+ int availableIndex = alloc();
+ cursorSpace[availableIndex].element = element;
+
+ if (head == -1) {
+ head = availableIndex;
+ }
+
+ int iterator = head;
+ while (cursorSpace[iterator].next != -1) {
+ iterator = cursorSpace[iterator].next;
+ }
+
+ cursorSpace[iterator].next = availableIndex;
+ cursorSpace[availableIndex].next = -1;
+
+
+ count++;
+ }
+
+ /**
+ * @return the index of the next available node
+ */
+ private int alloc() {
+
+
+ //1- get the index at which the os is pointing
+ int availableNodeIndex = cursorSpace[os].next;
+
+ if (availableNodeIndex == 0) {
+ throw new OutOfMemoryError();
+ }
+
+ //2- make the os point to the next of the @var{availableNodeIndex}
+ int availableNext = cursorSpace[availableNodeIndex].next;
+ cursorSpace[os].next = availableNext;
+
+ // this to indicate an end of the list , helpful at testing since any err
+ // would throw an outOfBoundException
+ cursorSpace[availableNodeIndex].next = -1;
+
+ return availableNodeIndex;
+
+ }
+
+
+}
diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java
index c3229d9c336d..27c1a1a24580 100644
--- a/DataStructures/Lists/DoublyLinkedList.java
+++ b/DataStructures/Lists/DoublyLinkedList.java
@@ -20,12 +20,24 @@ class DoublyLinkedList{
private Link tail;
/**
- * Constructor
+ * Default Constructor
*/
public DoublyLinkedList(){
head = null;
tail = null;
}
+
+ /**
+ * Constructs a list containing the elements of the array
+ * @param array the array whose elements are to be placed into this list
+ * @throws NullPointerException if the specified collection is null
+ */
+ public DoublyLinkedList(int[] array){
+ if (array == null) throw new NullPointerException();
+ for (int i:array) {
+ insertTail(i);
+ }
+ }
/**
* Insert an element at the head
@@ -60,13 +72,12 @@ public void insertTail(int x){
*
* @return The new head
*/
- public Link deleteHead(){
+ public void deleteHead(){
Link temp = head;
head = head.next; // oldHead <--> 2ndElement(head)
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
if(head == null)
tail = null;
- return temp;
}
/**
@@ -74,11 +85,11 @@ public Link deleteHead(){
*
* @return The new tail
*/
- public Link deleteTail(){
+ public void deleteTail(){
Link temp = tail;
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
tail.next = null; // 2ndLast(tail) --> null
- return temp;
+
}
/**
@@ -87,7 +98,7 @@ public Link deleteTail(){
* @param x element to be deleted
* @return Link deleted
*/
- public Link delete(int x){
+ public void delete(int x){
Link current = head;
while(current.value != x) //Find the position to delete
@@ -102,8 +113,7 @@ else if(current == tail)
else{ //Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next; // 1 --> 3
current.next.previous = current.previous; // 1 <--> 3
- }
- return current;
+ }
}
/**
@@ -211,4 +221,4 @@ public static void main(String args[]){
myList.insertOrdered(3);
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
}
-}
\ No newline at end of file
+}
diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java
index 32747cf2830f..c9d2413a8375 100644
--- a/DataStructures/Lists/SinglyLinkedList.java
+++ b/DataStructures/Lists/SinglyLinkedList.java
@@ -1,151 +1,182 @@
/**
* This class implements a SinglyLinked List. This is done
* using SinglyLinkedList class and a LinkForLinkedList Class.
- *
- * A linked list is implar to an array, it hold values.
+ *
+ * A linked list is similar to an array, it hold values.
* However, links in a linked list do not have indexes. With
* a linked list you do not need to predetermine it's size as
- * it gorws and shrinks as it is edited. This is an example of
+ * it grows and shrinks as it is edited. This is an example of
* a singly linked list. Elements can only be added/removed
* at the head/front of the list.
- *
- * @author Unknown
*
+ * @author yanglbme
*/
-class SinglyLinkedList{
- /**Head refered to the front of the list */
- private Node head;
-
- /**
- * Constructor of SinglyLinkedList
- */
- public SinglyLinkedList(){
- head = null;
- }
-
- /**
- * This method inserts an element at the head
- *
- * @param x Element to be added
- */
- public void insertHead(int x){
- Node newNode = new Node(x); //Create a new link with a value attached to it
- newNode.next = head; //Set the new link to point to the current head
- head = newNode; //Now set the new link to be the head
- }
-
-
- /**
+class SinglyLinkedList {
+ /**
+ * Head refer to the front of the list
+ */
+ private Node head;
+
+ /**
+ * This method inserts an element at the head
+ *
+ * @param x Element to be added
+ */
+ public void insertHead(int x) {
+ Node newNode = new Node(x);
+ newNode.next = head;
+ head = newNode;
+ }
+
+ /**
* Inserts a new node at a specified position
- * @param head head node of the linked list
+ *
* @param data data to be stored in a new node
* @param position position at which a new node is to be inserted
- * @return reference of the head of the linked list
*/
- Node InsertNth(Node head, int data, int position) {
-
- Node newNode = new Node();
- newNode.data = data;
-
- if (position == 0) {
- newNode.next = head;
- return newNode;
+ public void insertNth(int data, int position) {
+ if (position < 0 || position > getSize()) {
+ throw new RuntimeException("position less than zero or position more than the count of list");
+ }
+ else if (position == 0)
+ insertHead(data);
+ else {
+ Node cur = head;
+ Node node = new Node(data);
+ for (int i = 1; i < position; ++i) {
+ cur = cur.next;
+ }
+ node.next = cur.next;
+ cur.next = node;
}
+ }
- Node current = head;
+ /**
+ * This method deletes an element at the head
+ *
+ * @return The element deleted
+ */
+ public void deleteHead() {
+ if (isEmpty()) {
+ throw new RuntimeException("The list is empty!");
+ }
- while (--position > 0) {
+ head = head.next;
+ }
+
+ /**
+ * This method deletes an element at Nth position
+ */
+ public void deleteNth(int position) {
+ if (position < 0 || position > getSize()) {
+ throw new RuntimeException("position less than zero or position more than the count of list");
+ }
+ else if (position == 0)
+ deleteHead();
+ else {
+ Node cur = head;
+ for (int i = 1; i < position; ++i) {
+ cur = cur.next;
+ }
+ cur.next = cur.next.next;
+ }
+ }
+
+ /**
+ * Checks if the list is empty
+ *
+ * @return true is list is empty
+ */
+ public boolean isEmpty() {
+ return getSize() == 0;
+ }
+
+ /**
+ * Prints contents of the list
+ */
+ public void display() {
+ Node current = head;
+ while (current != null) {
+ System.out.print(current.value + " ");
current = current.next;
}
-
- newNode.next = current.next;
- current.next = newNode;
- return head;
+ System.out.println();
+ }
+
+ /**
+ * Returns the size of the linked list
+ */
+ public int getSize() {
+ if (head == null)
+ return 0;
+ else {
+ Node current = head;
+ int size = 1;
+ while (current.next != null) {
+ current = current.next;
+ size++;
+ }
+ return size;
+ }
+ }
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ SinglyLinkedList myList = new SinglyLinkedList();
+
+ assert myList.isEmpty();
+
+ myList.insertHead(5);
+ myList.insertHead(7);
+ myList.insertHead(10);
+
+ myList.display(); // 10 -> 7 -> 5
+
+ myList.deleteHead();
+
+ myList.display(); // 7 -> 5
+
+ myList.insertNth(11, 2);
+
+ myList.display(); // 7 -> 5 -> 11
+
+ myList.deleteNth(1);
+
+ myList.display(); // 7-> 11
+
}
-
- /**
- * This method deletes an element at the head
- *
- * @return The element deleted
- */
- public Node deleteHead(){
- Node temp = head;
- head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
- return temp;
- }
-
- /**
- * Checks if the list is empty
- *
- * @return true is list is empty
- */
- public boolean isEmpty(){
- return(head == null);
- }
-
- /**
- * Prints contents of the list
- */
- public void display(){
- Node current = head;
- while(current!=null){
- System.out.print(current.getValue()+" ");
- current = current.next;
- }
- System.out.println();
- }
-
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]){
- SinglyLinkedList myList = new SinglyLinkedList();
-
- System.out.println(myList.isEmpty()); //Will print true
-
- myList.insertHead(5);
- myList.insertHead(7);
- myList.insertHead(10);
-
- myList.display(); // 10(head) --> 7 --> 5
-
- myList.deleteHead();
-
- myList.display(); // 7(head) --> 5
- }
}
/**
* This class is the nodes of the SinglyLinked List.
- * They consist of a vlue and a pointer to the node
+ * They consist of a value and a pointer to the node
* after them.
- *
- * @author Unknown
*
+ * @author yanglbme
*/
-class Node{
- /** The value of the node */
- public int value;
- /** Point to the next node */
- public Node next; //This is what the link will point to
-
- /**
- * Constructor
- *
- * @param valuein Value to be put in the node
- */
- public Node(int valuein){
- value = valuein;
- }
-
- /**
- * Returns value of the node
- */
- public int getValue(){
- return value;
- }
+class Node {
+ /**
+ * The value of the node
+ */
+ int value;
+
+ /**
+ * Point to the next node
+ */
+ Node next;
+ /**
+ * Constructor
+ *
+ * @param value Value to be put in the node
+ */
+ Node(int value) {
+ this.value = value;
+ this.next = null;
+ }
}
diff --git a/DataStructures/Matrix/MatrixFastPower.java b/DataStructures/Matrix/MatrixFastPower.java
new file mode 100644
index 000000000000..19f8528a36ec
--- /dev/null
+++ b/DataStructures/Matrix/MatrixFastPower.java
@@ -0,0 +1,191 @@
+/**
+ *
+ * Java implementation of Matrix fast power
+ * It can calculate the high power of constant Matrix with O( log(K) )
+ * where K is the power of the Matrix
+ *
+ * In order to do that, Matrix must be square Matrix ( columns equals rows)
+ *
+ * Notice : large power of Matrix may cause overflow
+ *
+ *
+ * other Matrix basic operator is based on @author Kyler Smith, 2017
+ *
+ * @author DDullahan, 2018
+ *
+ */
+
+class MatrixFastPower {
+
+ /**
+ * Matrix Fast Power
+ *
+ * @param matrix : square Matrix
+ * @param k : power of Matrix
+ * @return product
+ */
+ public static Matrix FastPower(Matrix matrix, int k) throws RuntimeException {
+
+ if(matrix.getColumns() != matrix.getRows())
+ throw new RuntimeException("Matrix is not square Matrix.");
+
+ int[][] newData = new int[matrix.getColumns()][matrix.getRows()];
+
+ for(int i = 0; i < matrix.getColumns(); i++)
+ newData[i][i] = 1;
+
+ Matrix newMatrix = new Matrix(newData),
+ coMatrix = new Matrix(matrix.data);
+
+ while(k != 0) {
+
+ if((k & 1) != 0)
+ newMatrix = newMatrix.multiply(coMatrix);
+
+ k >>= 1;
+ coMatrix = coMatrix.multiply(coMatrix);
+
+ }
+
+ return newMatrix;
+ }
+
+ public static void main(String[] argv) {
+
+ int[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
+ Matrix matrix = new Matrix(data);
+
+ System.out.println("original matrix : ");
+ System.out.println(matrix.toString());
+
+ matrix = MatrixFastPower.FastPower(matrix, 5);
+
+ System.out.println("after power : ");
+ System.out.println(matrix.toString());
+
+ matrix = MatrixFastPower.FastPower(matrix, 1000000);
+
+ System.out.println("notice, large power may cause overflow : ");
+ System.out.print(matrix.toString());
+ System.out.println("you can use mod to fix that :-) ");
+
+ }
+}
+class Matrix {
+ public int[][] data;
+
+ /**
+ * Constructor for the matrix takes in a 2D array
+ *
+ * @param pData
+ */
+ public Matrix(int[][] pData) {
+
+ /** Make a deep copy of the data */
+ if(pData.length != 0) {
+ int[][] newData = new int[pData.length][pData[0].length];
+
+ for(int i = 0; i < pData.length; i++)
+ for(int j = 0; j < pData[0].length; j++)
+ newData[i][j] = pData[i][j];
+
+ this.data = newData;
+ } else {
+ this.data = null;
+ }
+ }
+
+ /**
+ * Returns the element specified by the given location
+ *
+ * @param x : x cooridinate
+ * @param y : y cooridinate
+ * @return int : value at location
+ */
+ public int getElement(int x, int y) {
+ return data[x][y];
+ }
+
+ /**
+ * Returns the number of rows in the Matrix
+ *
+ * @return rows
+ */
+ public int getRows() {
+ if(this.data == null)
+ return 0;
+
+ return data.length;
+ }
+
+ /**
+ * Returns the number of rows in the Matrix
+ *
+ * @return columns
+ */
+ public int getColumns() {
+ if(this.data == null)
+ return 0;
+
+ return data[0].length;
+ }
+
+ /**
+ * Multiplies this matrix with another matrix.
+ *
+ * @param other : Matrix to be multiplied with
+ * @return product
+ */
+ public Matrix multiply(Matrix other) throws RuntimeException {
+
+ int[][] newData = new int[this.data.length][other.getColumns()];
+
+ if(this.getColumns() != other.getRows())
+ throw new RuntimeException("The two matrices cannot be multiplied.");
+
+ int sum;
+
+ for (int i = 0; i < this.getRows(); ++i)
+ for(int j = 0; j < other.getColumns(); ++j) {
+ sum = 0;
+
+ for(int k = 0; k < this.getColumns(); ++k) {
+ sum += this.data[i][k] * other.getElement(k, j);
+ }
+
+ newData[i][j] = sum;
+ }
+
+ return new Matrix(newData);
+ }
+
+ /**
+ * Returns the Matrix as a String in the following format
+ *
+ * [ a b c ] ...
+ * [ x y z ] ...
+ * [ i j k ] ...
+ * ...
+ *
+ * @return Matrix as String
+ * TODO: Work formatting for different digit sizes
+ */
+ public String toString() {
+ String str = "";
+
+ for(int i = 0; i < this.data.length; i++) {
+ str += "[ ";
+
+ for(int j = 0; j < this.data[0].length; j++) {
+ str += data[i][j];
+ str += " ";
+ }
+
+ str += "]";
+ str += "\n";
+ }
+
+ return str;
+ }
+
+}
diff --git a/DataStructures/Queues/PriorityQueues.java b/DataStructures/Queues/PriorityQueues.java
index acb6b552537e..e709b13683a0 100644
--- a/DataStructures/Queues/PriorityQueues.java
+++ b/DataStructures/Queues/PriorityQueues.java
@@ -1,123 +1,128 @@
/**
* This class implements a PriorityQueue.
- *
+ *
* A priority queue adds elements into positions based on their priority.
* So the most important elements are placed at the front/on the top.
* In this example I give numbers that are bigger, a higher priority.
* Queues in theory have no fixed size but when using an array
* implementation it does.
- *
- * @author Unknown
*
*/
-class PriorityQueue{
- /** The max size of the queue */
- private int maxSize;
- /** The array for the queue */
- private int[] queueArray;
- /** How many items are in the queue */
- private int nItems;
+class PriorityQueue {
+ /**
+ * The max size of the queue
+ */
+ private int maxSize;
+ /**
+ * The array for the queue
+ */
+ private int[] queueArray;
+ /**
+ * How many items are in the queue
+ */
+ private int nItems;
- /**
- * Constructor
- *
- * @param size Size of the queue
- */
- public PriorityQueue(int size){
- maxSize = size;
- queueArray = new int[size];
- nItems = 0;
- }
+ /**
+ * Constructor
+ *
+ * @param size Size of the queue
+ */
+ public PriorityQueue(int size) {
+ maxSize = size;
+ queueArray = new int[size];
+ nItems = 0;
+ }
- /**
- * Inserts an element in it's appropriate place
- *
- * @param value Value to be inserted
- */
- public void insert(int value){
- if(nItems == 0){
- queueArray[0] = value;
- }
- else{
- int j = nItems;
- while(j > 0 && queueArray[j-1] > value){
- queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
- j--;
- }
- queueArray[j] = value; //Once the correct position is found the value is inserted
- }
- nItems++;
- }
+ /**
+ * Inserts an element in it's appropriate place
+ *
+ * @param value Value to be inserted
+ */
+ public void insert(int value) {
+ if (isFull()) {
+ throw new RuntimeException("Queue is full");
+ }
+ if (nItems == 0) {
+ queueArray[0] = value;
+ } else {
+ int j = nItems;
+ while (j > 0 && queueArray[j - 1] > value) {
+ queueArray[j] = queueArray[j - 1]; // Shifts every element up to make room for insertion
+ j--;
+ }
+ queueArray[j] = value; // Once the correct position is found the value is inserted
+ }
+ nItems++;
+ }
- /**
- * Remove the element from the front of the queue
- *
- * @return The element removed
- */
- public int remove(){
- return queueArray[--nItems];
- }
+ /**
+ * Remove the element from the front of the queue
+ *
+ * @return The element removed
+ */
+ public int remove() {
+ return queueArray[--nItems];
+ }
- /**
- * Checks what's at the front of the queue
- *
- * @return element at the front of the queue
- */
- public int peek(){
- return queueArray[nItems-1];
- }
+ /**
+ * Checks what's at the front of the queue
+ *
+ * @return element at the front of the queue
+ */
+ public int peek() {
+ return queueArray[nItems - 1];
+ }
- /**
- * Returns true if the queue is empty
- *
- * @return true if the queue is empty
- */
- public boolean isEmpty(){
- return(nItems == 0);
- }
+ /**
+ * Returns true if the queue is empty
+ *
+ * @return true if the queue is empty
+ */
+ public boolean isEmpty() {
+ return (nItems == 0);
+ }
- /**
- * Returns true if the queue is full
- *
- * @return true if the queue is full
- */
- public boolean isFull(){
- return(nItems == maxSize);
- }
+ /**
+ * Returns true if the queue is full
+ *
+ * @return true if the queue is full
+ */
+ public boolean isFull() {
+ return (nItems == maxSize);
+ }
- /**
- * Returns the number of elements in the queue
- *
- * @return number of elements in the queue
- */
- public int getSize(){
- return nItems;
- }
+ /**
+ * Returns the number of elements in the queue
+ *
+ * @return number of elements in the queue
+ */
+ public int getSize() {
+ return nItems;
+ }
}
/**
* This class implements the PriorityQueue class above.
- *
- * @author Unknown
*
+ * @author Unknown
*/
-public class PriorityQueues{
- /**
- * Main method
- *
- * @param args Command Line Arguments
- */
- public static void main(String args[]){
- PriorityQueue myQueue = new PriorityQueue(4);
- myQueue.insert(10);
- myQueue.insert(2);
- myQueue.insert(5);
- myQueue.insert(3);
- //[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
+public class PriorityQueues {
+ /**
+ * Main method
+ *
+ * @param args Command Line Arguments
+ */
+ public static void main(String[] args) {
+ PriorityQueue myQueue = new PriorityQueue(4);
+ myQueue.insert(10);
+ myQueue.insert(2);
+ myQueue.insert(5);
+ myQueue.insert(3);
+ // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
- for(int i = 3; i>=0; i--)
- System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2]
+ for (int i = 3; i >= 0; i--)
+ System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2]
- //As you can see, a Priority Queue can be used as a sorting algotithm
- }
-}
\ No newline at end of file
+ // As you can see, a Priority Queue can be used as a sorting algotithm
+ }
+}
diff --git a/DataStructures/Queues/Queues.java b/DataStructures/Queues/Queues.java
index 84638cb24751..cd66d5af0118 100644
--- a/DataStructures/Queues/Queues.java
+++ b/DataStructures/Queues/Queues.java
@@ -1,148 +1,156 @@
/**
* This implements Queues by using the class Queue.
- *
+ *
* A queue data structure functions the same as a real world queue.
* The elements that are added first are the first to be removed.
* New elements are added to the back/rear of the queue.
- *
- * @author Unknown
*
+ * @author Unknown
*/
-class Queue{
- /** Max size of the queue */
- private int maxSize;
- /** The array representing the queue */
- private int[] queueArray;
- /** Front of the queue */
- private int front;
- /** Rear of the queue */
- private int rear;
- /** How many items are in the queue */
- private int nItems;
-
- /**
- * Constructor
- *
- * @param size Size of the new queue
- */
- public Queue(int size){
- maxSize = size;
- queueArray = new int[size];
- front = 0;
- rear = -1;
- nItems = 0;
- }
-
- /**
- * Inserts an element at the rear of the queue
- *
- * @param x element to be added
- * @return True if the element was added successfully
- */
- public boolean insert(int x){
- if(isFull())
- return false;
- if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front
- rear = -1;
- rear++;
- queueArray[rear] = x;
- nItems++;
- return true;
- }
-
- /**
- * Remove an element from the front of the queue
- *
- * @return the new front of the queue
- */
- public int remove(){ //Remove an element from the front of the queue
- if(isEmpty()){
- System.out.println("Queue is empty");
- return -1;
- }
- int temp = queueArray[front];
- front++;
- if(front == maxSize) //Dealing with wrap-around again
- front = 0;
- nItems--;
- return temp;
- }
-
- /**
- * Checks what's at the front of the queue
- *
- * @return element at the front of the queue
- */
- public int peekFront(){
- return queueArray[front];
- }
-
- /**
- * Checks what's at the rear of the queue
- *
- * @return element at the rear of the queue
- */
- public int peekRear(){
- return queueArray[rear];
- }
-
- /**
- * Returns true if the queue is empty
- *
- * @return true if the queue is empty
- */
- public boolean isEmpty(){
- return(nItems == 0);
- }
-
- /**
- * Returns true if the queue is full
- *
- * @return true if the queue is full
- */
- public boolean isFull(){
- return(nItems == maxSize);
- }
-
- /**
- * Returns the number of elements in the queue
- *
- * @return number of elements in the queue
- */
- public int getSize(){
- return nItems;
- }
+class Queue {
+ /**
+ * Max size of the queue
+ */
+ private int maxSize;
+ /**
+ * The array representing the queue
+ */
+ private int[] queueArray;
+ /**
+ * Front of the queue
+ */
+ private int front;
+ /**
+ * Rear of the queue
+ */
+ private int rear;
+ /**
+ * How many items are in the queue
+ */
+ private int nItems;
+
+ /**
+ * Constructor
+ *
+ * @param size Size of the new queue
+ */
+ public Queue(int size) {
+ maxSize = size;
+ queueArray = new int[size];
+ front = 0;
+ rear = -1;
+ nItems = 0;
+ }
+
+ /**
+ * Inserts an element at the rear of the queue
+ *
+ * @param x element to be added
+ * @return True if the element was added successfully
+ */
+ public boolean insert(int x) {
+ if (isFull())
+ return false;
+ if (rear == maxSize - 1) // If the back of the queue is the end of the array wrap around to the front
+ rear = -1;
+ rear++;
+ queueArray[rear] = x;
+ nItems++;
+ return true;
+ }
+
+ /**
+ * Remove an element from the front of the queue
+ *
+ * @return the new front of the queue
+ */
+ public int remove() { // Remove an element from the front of the queue
+ if (isEmpty()) {
+ System.out.println("Queue is empty");
+ return -1;
+ }
+ int temp = queueArray[front];
+ front++;
+ if (front == maxSize) //Dealing with wrap-around again
+ front = 0;
+ nItems--;
+ return temp;
+ }
+
+ /**
+ * Checks what's at the front of the queue
+ *
+ * @return element at the front of the queue
+ */
+ public int peekFront() {
+ return queueArray[front];
+ }
+
+ /**
+ * Checks what's at the rear of the queue
+ *
+ * @return element at the rear of the queue
+ */
+ public int peekRear() {
+ return queueArray[rear];
+ }
+
+ /**
+ * Returns true if the queue is empty
+ *
+ * @return true if the queue is empty
+ */
+ public boolean isEmpty() {
+ return (nItems == 0);
+ }
+
+ /**
+ * Returns true if the queue is full
+ *
+ * @return true if the queue is full
+ */
+ public boolean isFull() {
+ return (nItems == maxSize);
+ }
+
+ /**
+ * Returns the number of elements in the queue
+ *
+ * @return number of elements in the queue
+ */
+ public int getSize() {
+ return nItems;
+ }
}
/**
* This class is the example for the Queue class
- *
- * @author Unknown
*
+ * @author Unknown
*/
-public class Queues{
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]){
- Queue myQueue = new Queue(4);
- myQueue.insert(10);
- myQueue.insert(2);
- myQueue.insert(5);
- myQueue.insert(3);
- //[10(front), 2, 5, 3(rear)]
-
- System.out.println(myQueue.isFull()); //Will print true
-
- myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue
- //[10, 2(front), 5, 3(rear)]
-
- myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around
- // [7(rear), 2(front), 5, 3]
-
- System.out.println(myQueue.peekFront()); //Will print 2
- System.out.println(myQueue.peekRear()); //Will print 7
- }
-}
\ No newline at end of file
+public class Queues {
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ Queue myQueue = new Queue(4);
+ myQueue.insert(10);
+ myQueue.insert(2);
+ myQueue.insert(5);
+ myQueue.insert(3);
+ // [10(front), 2, 5, 3(rear)]
+
+ System.out.println(myQueue.isFull()); // Will print true
+
+ myQueue.remove(); // Will make 2 the new front, making 10 no longer part of the queue
+ // [10, 2(front), 5, 3(rear)]
+
+ myQueue.insert(7); // Insert 7 at the rear which will be index 0 because of wrap around
+ // [7(rear), 2(front), 5, 3]
+
+ System.out.println(myQueue.peekFront()); // Will print 2
+ System.out.println(myQueue.peekRear()); // Will print 7
+ }
+}
diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java
new file mode 100644
index 000000000000..6e580918fabc
--- /dev/null
+++ b/DataStructures/Stacks/StackArray.java
@@ -0,0 +1,152 @@
+/**
+ * This class implements a Stack using a regular array.
+ *
+ * A stack is exactly what it sounds like. An element gets added to the top of
+ * the stack and only the element on the top may be removed. This is an example
+ * of an array implementation of a Stack. So an element can only be added/removed
+ * from the end of the array. In theory stack have no fixed size, but with an
+ * array implementation it does.
+ *
+ * @author Unknown
+ */
+public class StackArray {
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args) {
+ // Declare a stack of maximum size 4
+ StackArray myStackArray = new StackArray(4);
+
+ // Populate the stack
+ myStackArray.push(5);
+ myStackArray.push(8);
+ myStackArray.push(2);
+ myStackArray.push(9);
+
+ System.out.println("*********************Stack Array Implementation*********************");
+ System.out.println(myStackArray.isEmpty()); // will print false
+ System.out.println(myStackArray.isFull()); // will print true
+ System.out.println(myStackArray.peek()); // will print 9
+ System.out.println(myStackArray.pop()); // will print 9
+ System.out.println(myStackArray.peek()); // will print 2
+ }
+
+ /**
+ * The max size of the Stack
+ */
+ private int maxSize;
+
+ /**
+ * The array representation of the Stack
+ */
+ private int[] stackArray;
+
+ /**
+ * The top of the stack
+ */
+ private int top;
+
+ /**
+ * Constructor
+ *
+ * @param size Size of the Stack
+ */
+ public StackArray(int size) {
+ maxSize = size;
+ stackArray = new int[maxSize];
+ top = -1;
+ }
+
+ /**
+ * Adds an element to the top of the stack
+ *
+ * @param value The element added
+ */
+ public void push(int value) {
+ if (!isFull()) { // Checks for a full stack
+ top++;
+ stackArray[top] = value;
+ } else {
+ resize(maxSize * 2);
+ push(value); // don't forget push after resizing
+ }
+ }
+
+ /**
+ * Removes the top element of the stack and returns the value you've removed
+ *
+ * @return value popped off the Stack
+ */
+ public int pop() {
+ if (!isEmpty()) { // Checks for an empty stack
+ return stackArray[top--];
+ }
+
+ if (top < maxSize / 4) {
+ resize(maxSize / 2);
+ return pop();// don't forget pop after resizing
+ } else {
+ System.out.println("The stack is already empty");
+ return -1;
+ }
+ }
+
+ /**
+ * Returns the element at the top of the stack
+ *
+ * @return element at the top of the stack
+ */
+ public int peek() {
+ if (!isEmpty()) { // Checks for an empty stack
+ return stackArray[top];
+ } else {
+ System.out.println("The stack is empty, cant peek");
+ return -1;
+ }
+ }
+
+ private void resize(int newSize) {
+ // private int[] transferArray = new int[newSize]; we can't put modifiers here !
+ int[] transferArray = new int[newSize];
+
+ // for(int i = 0; i < stackArray.length(); i++){ the length isn't a method .
+ for (int i = 0; i < stackArray.length; i++) {
+ transferArray[i] = stackArray[i];
+ stackArray = transferArray;
+ }
+ maxSize = newSize;
+ }
+
+ /**
+ * Returns true if the stack is empty
+ *
+ * @return true if the stack is empty
+ */
+ public boolean isEmpty() {
+ return (top == -1);
+ }
+
+ /**
+ * Returns true if the stack is full
+ *
+ * @return true if the stack is full
+ */
+ public boolean isFull() {
+ return (top + 1 == maxSize);
+ }
+
+ /**
+ * Deletes everything in the Stack
+ *
+ * Doesn't delete elements in the array
+ * but if you call push method after calling
+ * makeEmpty it will overwrite previous
+ * values
+ */
+ public void makeEmpty() { // Doesn't delete elements in the array but if you call
+ top = -1; // push method after calling makeEmpty it will overwrite previous values
+ }
+}
diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java
new file mode 100644
index 000000000000..afc804440403
--- /dev/null
+++ b/DataStructures/Stacks/StackArrayList.java
@@ -0,0 +1,95 @@
+import java.util.ArrayList;
+
+/**
+ * This class implements a Stack using an ArrayList.
+ *
+ * A stack is exactly what it sounds like. An element gets added to the top of
+ * the stack and only the element on the top may be removed.
+ *
+ * This is an ArrayList Implementation of a stack, where size is not
+ * a problem we can extend the stack as much as we want.
+ *
+ * @author Unknown
+ */
+public class StackArrayList {
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args) {
+
+ StackArrayList myStackArrayList = new StackArrayList();
+
+ myStackArrayList.push(5);
+ myStackArrayList.push(8);
+ myStackArrayList.push(2);
+ myStackArrayList.push(9);
+
+ System.out.println("*********************Stack List Implementation*********************");
+ System.out.println(myStackArrayList.isEmpty()); // will print false
+ System.out.println(myStackArrayList.peek()); // will print 9
+ System.out.println(myStackArrayList.pop()); // will print 9
+ System.out.println(myStackArrayList.peek()); // will print 2
+ System.out.println(myStackArrayList.pop()); // will print 2
+ }
+
+ /**
+ * ArrayList representation of the stack
+ */
+ private ArrayList stackList;
+
+ /**
+ * Constructor
+ */
+ public StackArrayList() {
+ stackList = new ArrayList<>();
+ }
+
+ /**
+ * Adds value to the end of list which
+ * is the top for stack
+ *
+ * @param value value to be added
+ */
+ public void push(int value) {
+ stackList.add(value);
+ }
+
+ /**
+ * Pops last element of list which is indeed
+ * the top for Stack
+ *
+ * @return Element popped
+ */
+ public int pop() {
+
+ if (!isEmpty()) { // checks for an empty Stack
+ int popValue = stackList.get(stackList.size() - 1);
+ stackList.remove(stackList.size() - 1); // removes the poped element from the list
+ return popValue;
+ }
+
+ System.out.print("The stack is already empty!");
+ return -1;
+ }
+
+ /**
+ * Checks for empty Stack
+ *
+ * @return true if stack is empty
+ */
+ public boolean isEmpty() {
+ return stackList.isEmpty();
+ }
+
+ /**
+ * Top element of stack
+ *
+ * @return top element of stack
+ */
+ public int peek() {
+ return stackList.get(stackList.size() - 1);
+ }
+}
diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java
index 35052457fe1c..d9f737040271 100644
--- a/DataStructures/Stacks/StackOfLinkedList.java
+++ b/DataStructures/Stacks/StackOfLinkedList.java
@@ -1,7 +1,5 @@
/**
- *
* @author Varun Upadhyay (https://github.com/varunu28)
- *
*/
// An implementation of a Stack using a Linked List
@@ -25,9 +23,7 @@ public static void main(String[] args) {
stack.pop();
System.out.println("Top element of stack currently is: " + stack.peek());
-
}
-
}
// A node class
@@ -44,66 +40,71 @@ public Node(int data) {
/**
* A class which implements a stack using a linked list
- *
+ *
* Contains all the stack methods : push, pop, printStack, isEmpty
**/
class LinkedListStack {
Node head = null;
- int size = 0;
public void push(int x) {
Node n = new Node(x);
- if (getSize() == 0) {
+ if (head == null) {
head = n;
- }
- else {
+ } else {
Node temp = head;
n.next = temp;
head = n;
}
- size++;
}
public void pop() {
- if (getSize() == 0) {
+ if (head == null) {
System.out.println("Empty stack. Nothing to pop");
}
Node temp = head;
head = head.next;
- size--;
-
System.out.println("Popped element is: " + temp.data);
}
public int peek() {
- if (getSize() == 0) {
- return -1;
- }
-
- return head.data;
+ if (head == null) {
+ return -1;
+ }
+ return head.data;
}
public void printStack() {
-
Node temp = head;
System.out.println("Stack is printed as below: ");
while (temp != null) {
- System.out.println(temp.data + " ");
+ if (temp.next == null) {
+ System.out.print(temp.data);
+ } else {
+ System.out.print(temp.data + " -> ");
+ }
temp = temp.next;
}
System.out.println();
-
}
public boolean isEmpty() {
- return getSize() == 0;
+ return head == null;
}
public int getSize() {
- return size;
+ if (head == null)
+ return 0;
+ else {
+ int size = 1;
+ Node temp = head;
+ while (temp.next != null) {
+ temp = temp.next;
+ size++;
+ }
+ return size;
+ }
}
-
}
diff --git a/DataStructures/Stacks/Stacks.java b/DataStructures/Stacks/Stacks.java
deleted file mode 100644
index 2861ef5c17e8..000000000000
--- a/DataStructures/Stacks/Stacks.java
+++ /dev/null
@@ -1,240 +0,0 @@
-import java.util.ArrayList;
-
-/**
- * This class implements a Stack using two different implementations.
- * Stack is used with a regular array and Stack2 uses an ArrayList.
- *
- * A stack is exactly what it sounds like. An element gets added to the top of
- * the stack and only the element on the top may be removed. This is an example
- * of an array implementation of a Stack. So an element can only be added/removed
- * from the end of the array. In theory stack have no fixed size, but with an
- * array implementation it does.
- *
- * @author Unknown
- *
- */
-class Stack{
- /** The max size of the Stack */
- private int maxSize;
- /** The array representation of the Stack */
- private int[] stackArray;
- /** The top of the stack */
- private int top;
-
- /**
- * Constructor
- *
- * @param size Size of the Stack
- */
- public Stack(int size){
- maxSize = size;
- stackArray = new int[maxSize];
- top = -1;
- }
-
- /**
- * Adds an element to the top of the stack
- *
- * @param value The element added
- */
- public void push(int value){
- if(!isFull()){ //Checks for a full stack
- top++;
- stackArray[top] = value;
- }else{
- resize(maxSize*2);
- push(value);// don't forget push after resizing
- }
- }
-
- /**
- * Removes the top element of the stack and returns the value you've removed
- *
- * @return value popped off the Stack
- */
- public int pop(){
- if(!isEmpty()){ //Checks for an empty stack
- return stackArray[top--];
- }
-
- if(top < maxSize/4){
- resize(maxSize/2);
- return pop();// don't forget pop after resizing
- }
- else{
- System.out.println("The stack is already empty");
- return -1;
- }
- }
-
- /**
- * Returns the element at the top of the stack
- *
- * @return element at the top of the stack
- */
- public int peek(){
- if(!isEmpty()){ //Checks for an empty stack
- return stackArray[top];
- }else{
- System.out.println("The stack is empty, cant peek");
- return -1;
- }
- }
-
- private void resize(int newSize){
- //private int[] transferArray = new int[newSize]; we can't put modifires here !
- int[] transferArray = new int[newSize];
-
- //for(int i = 0; i < stackArray.length(); i++){ the length isn't a method .
- for(int i = 0; i < stackArray.length; i++){
- transferArray[i] = stackArray[i];
- stackArray = transferArray;
- }
- maxSize = newSize;
- }
-
- /**
- * Returns true if the stack is empty
- *
- * @return true if the stack is empty
- */
- public boolean isEmpty(){
- return(top == -1);
- }
-
- /**
- * Returns true if the stack is full
- *
- * @return true if the stack is full
- */
- public boolean isFull(){
- return(top+1 == maxSize);
- }
-
- /**
- * Deletes everything in the Stack
- *
- * Doesn't delete elements in the array
- * but if you call push method after calling
- * makeEmpty it will overwrite previous
- * values
- */
- public void makeEmpty(){ //Doesn't delete elements in the array but if you call
- top = -1; //push method after calling makeEmpty it will overwrite previous values
- }
-}
-
-/**
- * This is an ArrayList Implementation of stack, Where size is not
- * a problem we can extend the stack as much as we want.
- *
- * @author Unknown
- *
- */
-class Stack2{
- /** ArrayList representation of the stack */
- ArrayList stackList;
-
- /**
- * Constructor
- */
- Stack2(){
- stackList=new ArrayList<>();
- }
-
- /**
- * Adds value to the end of list which
- * is the top for stack
- *
- * @param value value to be added
- */
- void push(int value){
- stackList.add(value);
- }
-
- /**
- * Pops last element of list which is indeed
- * the top for Stack
- *
- * @return Element popped
- */
- int pop(){
-
- if(!isEmpty()){ // checks for an empty Stack
-
- int popValue=stackList.get(stackList.size()-1);
- stackList.remove(stackList.size()-1); //removes the poped element from the list
- return popValue;
- }
- else{
- System.out.print("The stack is already empty ");
- return -1;
- }
-
- }
-
- /**
- * Checks for empty Stack
- *
- * @return true if stack is empty
- */
- boolean isEmpty(){
- if(stackList.isEmpty())
- return true;
-
- else return false;
-
- }
-
- /**
- * Top element of stack
- *
- * @return top element of stack
- */
- int peek(){
- return stackList.get(stackList.size()-1);
- }
- }
-
-/**
- * This class implements the Stack and Stack2 created above
- *
- * @author Unknown
- *
- */
-public class Stacks{
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]){
- Stack myStack = new Stack(4); //Declare a stack of maximum size 4
- //Populate the stack
- myStack.push(5);
- myStack.push(8);
- myStack.push(2);
- myStack.push(9);
-
- System.out.println("*********************Stack Array Implementation*********************");
- System.out.println(myStack.isEmpty()); //will print false
- System.out.println(myStack.isFull()); //will print true
- System.out.println(myStack.peek()); //will print 9
- System.out.println(myStack.pop()); //will print 9
- System.out.println(myStack.peek()); // will print 2
-
- Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4
- //Populate the stack
- myStack2.push(5);
- myStack2.push(8);
- myStack2.push(2);
- myStack2.push(9);
-
- System.out.println("*********************Stack List Implementation*********************");
- System.out.println(myStack2.isEmpty()); //will print false
- System.out.println(myStack2.peek()); //will print 9
- System.out.println(myStack2.pop()); //will print 9
- System.out.println(myStack2.peek()); // will print 2
- System.out.println(myStack2.pop()); //will print 2
- }
-}
diff --git a/DataStructures/Trees/AVLTree.java b/DataStructures/Trees/AVLTree.java
index 4bcf402dc0b7..720d46fd51df 100644
--- a/DataStructures/Trees/AVLTree.java
+++ b/DataStructures/Trees/AVLTree.java
@@ -176,9 +176,10 @@ private int height(Node n) {
}
private void setBalance(Node... nodes) {
- for (Node n : nodes)
+ for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
+ }
}
public void printBalance() {
diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java
index a20d24eebc35..0c6e89cd36ae 100644
--- a/DataStructures/Trees/BinaryTree.java
+++ b/DataStructures/Trees/BinaryTree.java
@@ -69,8 +69,12 @@ public Node find(int key) {
Node current = root;
while (current != null) {
if(key < current.data) {
+ if(current.left == null)
+ return current; //The key isn't exist, returns the parent
current = current.left;
} else if(key > current.data) {
+ if(current.right == null)
+ return current;
current = current.right;
} else { // If you find the value return it
return current;
diff --git a/DataStructures/Trees/GenericTree.Java b/DataStructures/Trees/GenericTree.Java
index 16ab5fb53b1e..cc592e04082e 100644
--- a/DataStructures/Trees/GenericTree.Java
+++ b/DataStructures/Trees/GenericTree.Java
@@ -2,7 +2,7 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
-public class treeclass {
+public class GenericTree {
private class Node {
int data;
ArrayList child = new ArrayList<>();
@@ -22,7 +22,7 @@ public class treeclass {
I have done this, while calling from main one have to give minimum parameters.
*/
- public treeclass() { //Constructor
+ public GenericTree() { //Constructor
Scanner scn = new Scanner(System.in);
root = create_treeG(null, 0, scn);
}
diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java
index 8cb304f18c8f..1f657d92be97 100644
--- a/DataStructures/Trees/LevelOrderTraversal.java
+++ b/DataStructures/Trees/LevelOrderTraversal.java
@@ -37,14 +37,10 @@ int height(Node root)
return 0;
else
{
- /* compute height of each subtree */
- int lheight = height(root.left);
- int rheight = height(root.right);
-
- /* use the larger one */
- if (lheight > rheight)
- return(lheight+1);
- else return(rheight+1);
+ /**
+ * Return the height of larger subtree
+ */
+ return Math.max(height(root.left),height(root.right)) + 1;
}
}
@@ -75,4 +71,4 @@ public static void main(String args[])
System.out.println("Level order traversal of binary tree is ");
tree.printLevelOrder();
}
-}
\ No newline at end of file
+}
diff --git a/Dynamic Programming/CoinChange.java b/Dynamic Programming/CoinChange.java
index f4cda7203b7c..e9d3689d9952 100644
--- a/Dynamic Programming/CoinChange.java
+++ b/Dynamic Programming/CoinChange.java
@@ -10,9 +10,11 @@ public class CoinChange {
public static void main(String[] args) {
int amount = 12;
- int[] coins = {1, 2, 5};
+ int[] coins = {2, 4, 5};
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
+ System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount));
+
}
/**
@@ -29,7 +31,7 @@ public static int change(int[] coins, int amount) {
for (int coin : coins) {
for (int i=coin; i map = new HashMap();
+ private static Map map = new HashMap<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
- System.out.println(fibMemo(n)); // Returns 8 for n = 6
- System.out.println(fibBotUp(n)); // Returns 8 for n = 6
+ // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
+ System.out.println(fibMemo(n));
+ System.out.println(fibBotUp(n));
}
/**
* This method finds the nth fibonacci number using memoization technique
*
* @param n The input n for which we have to determine the fibonacci number
- * Outputs the nth fibonacci number
+ * Outputs the nth fibonacci number
**/
-
private static int fibMemo(int n) {
if (map.containsKey(n)) {
return map.get(n);
@@ -36,14 +35,12 @@ private static int fibMemo(int n) {
int f;
- if (n <= 2) {
- f = 1;
- }
- else {
- f = fibMemo(n-1) + fibMemo(n-2);
- map.put(n,f);
+ if (n <= 1) {
+ f = n;
+ } else {
+ f = fibMemo(n - 1) + fibMemo(n - 2);
+ map.put(n, f);
}
-
return f;
}
@@ -51,25 +48,50 @@ private static int fibMemo(int n) {
* This method finds the nth fibonacci number using bottom up
*
* @param n The input n for which we have to determine the fibonacci number
- * Outputs the nth fibonacci number
+ * Outputs the nth fibonacci number
**/
-
private static int fibBotUp(int n) {
- Map fib = new HashMap();
+ Map fib = new HashMap<>();
- for (int i=1;i
+ * This is optimized version of Fibonacci Program. Without using Hashmap and recursion.
+ * It saves both memory and time.
+ * Space Complexity will be O(1)
+ * Time Complexity will be O(n)
+ *
+ * Whereas , the above functions will take O(n) Space.
+ * @author Shoaib Rayeen (https://github.com/shoaibrayeen)
+ **/
+ private static int fibOptimized(int n) {
+ if (n == 0) {
+ return 0;
+ }
+ int prev = 0, res = 1, next;
+ for (int i = 2; i < n; i++) {
+ next = prev + res;
+ prev = res;
+ res = next;
+ }
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/Dynamic Programming/Ford_Fulkerson.java b/Dynamic Programming/Ford_Fulkerson.java
new file mode 100644
index 000000000000..534a9dc9a7df
--- /dev/null
+++ b/Dynamic Programming/Ford_Fulkerson.java
@@ -0,0 +1,71 @@
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.Scanner;
+import java.util.Vector;
+
+public class Ford_Fulkerson {
+ Scanner scan = new Scanner(System.in);
+ final static int INF = 987654321;
+ static int V; // edges
+ static int[][] capacity, flow;
+
+ public static void main(String[] args) {
+ System.out.println("V : 6");
+ V = 6;
+ capacity = new int[V][V];
+
+ capacity[0][1] = 12;
+ capacity[0][3] = 13;
+ capacity[1][2] = 10;
+ capacity[2][3] = 13;
+ capacity[2][4] = 3;
+ capacity[2][5] = 15;
+ capacity[3][2] = 7;
+ capacity[3][4] = 15;
+ capacity[4][5] = 17;
+
+ System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
+ }
+
+ private static int networkFlow(int source, int sink) {
+ flow = new int[V][V];
+ int totalFlow = 0;
+ while (true) {
+ Vector parent = new Vector<>(V);
+ for (int i = 0; i < V; i++)
+ parent.add(-1);
+ Queue q = new LinkedList<>();
+ parent.set(source, source);
+ q.add(source);
+ while (!q.isEmpty() && parent.get(sink) == -1) {
+ int here = q.peek();
+ q.poll();
+ for (int there = 0; there < V; ++there)
+ if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
+ q.add(there);
+ parent.set(there, here);
+ }
+ }
+ if (parent.get(sink) == -1)
+ break;
+
+ int amount = INF;
+ String printer = "path : ";
+ StringBuilder sb = new StringBuilder();
+ for (int p = sink; p != source; p = parent.get(p)) {
+ amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
+ sb.append(p + "-");
+ }
+ sb.append(source);
+ for (int p = sink; p != source; p = parent.get(p)) {
+ flow[parent.get(p)][p] += amount;
+ flow[p][parent.get(p)] -= amount;
+ }
+ totalFlow += amount;
+ printer += sb.reverse() + " / max flow : " + totalFlow;
+ System.out.println(printer);
+ }
+
+ return totalFlow;
+ }
+}
diff --git a/Dynamic Programming/LevenshteinDistance.java b/Dynamic Programming/LevenshteinDistance.java
index be0e7c43f112..a196c0fe5139 100644
--- a/Dynamic Programming/LevenshteinDistance.java
+++ b/Dynamic Programming/LevenshteinDistance.java
@@ -1,55 +1,54 @@
/**
- *
* @author Kshitij VERMA (github.com/kv19971)
* LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
- *
- *
*/
-public class LevenshteinDistance{
- private static int minimum(int a, int b, int c){
- if(a < b && a < c){
- return a;
- }else if(b < a && b < c){
- return b;
- }else{
- return c;
- }
- }
- private static int calculate_distance(String a, String b){
- int len_a = a.length() + 1;
- int len_b = b.length() + 1;
- int [][] distance_mat = new int[len_a][len_b];
- for(int i = 0; i < len_a; i++){
- distance_mat[i][0] = i;
- }
- for(int j = 0; j < len_b; j++){
- distance_mat[0][j] = j;
- }
- for(int i = 0; i < len_a; i++){
- for(int j = 0; i < len_b; j++){
- int cost;
- if (a.charAt(i) == b.charAt(j)){
- cost = 0;
- }else{
- cost = 1;
- }
- distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost;
-
-
- }
-
- }
- return distance_mat[len_a-1][len_b-1];
-
- }
- public static void main(String [] args){
- String a = ""; // enter your string here
- String b = ""; // enter your string here
-
- System.out.print("Levenshtein distance between "+a + " and "+b+ " is: ");
- System.out.println(calculate_distance(a,b));
-
-
- }
+public class LevenshteinDistance {
+ private static int minimum(int a, int b, int c) {
+ if (a < b && a < c) {
+ return a;
+ } else if (b < a && b < c) {
+ return b;
+ } else {
+ return c;
+ }
+ }
+
+ private static int calculate_distance(String a, String b) {
+ int len_a = a.length() + 1;
+ int len_b = b.length() + 1;
+ int[][] distance_mat = new int[len_a][len_b];
+ for (int i = 0; i < len_a; i++) {
+ distance_mat[i][0] = i;
+ }
+ for (int j = 0; j < len_b; j++) {
+ distance_mat[0][j] = j;
+ }
+ for (int i = 0; i < len_a; i++) {
+ for (int j = 0; i < len_b; j++) {
+ int cost;
+ if (a.charAt(i) == b.charAt(j)) {
+ cost = 0;
+ } else {
+ cost = 1;
+ }
+ distance_mat[i][j] = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + cost;
+
+
+ }
+
+ }
+ return distance_mat[len_a - 1][len_b - 1];
+
+ }
+
+ public static void main(String[] args) {
+ String a = ""; // enter your string here
+ String b = ""; // enter your string here
+
+ System.out.print("Levenshtein distance between " + a + " and " + b + " is: ");
+ System.out.println(calculate_distance(a, b));
+
+
+ }
}
diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java
index eaa574a40989..ccbb88468bd3 100644
--- a/Dynamic Programming/LongestIncreasingSubsequence.java
+++ b/Dynamic Programming/LongestIncreasingSubsequence.java
@@ -1,12 +1,11 @@
import java.util.Scanner;
/**
- *
* @author Afrizal Fikri (https://github.com/icalF)
- *
+ * @author Libin Yang (https://github.com/yanglbme)
*/
public class LongestIncreasingSubsequence {
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
@@ -20,7 +19,7 @@ public static void main(String[] args) throws Exception {
}
private static int upperBound(int[] ar, int l, int r, int key) {
- while (l < r-1) {
+ while (l < r - 1) {
int m = (l + r) / 2;
if (ar[m] >= key)
r = m;
@@ -35,10 +34,12 @@ private static int LIS(int[] array) {
int N = array.length;
if (N == 0)
return 0;
-
+
int[] tail = new int[N];
- int length = 1; // always points empty slot in tail
-
+
+ // always points empty slot in tail
+ int length = 1;
+
tail[0] = array[0];
for (int i = 1; i < N; i++) {
@@ -46,17 +47,17 @@ private static int LIS(int[] array) {
if (array[i] < tail[0])
tail[0] = array[i];
- // array[i] extends largest subsequence
- else if (array[i] > tail[length-1])
+ // array[i] extends largest subsequence
+ else if (array[i] > tail[length - 1])
tail[length++] = array[i];
- // array[i] will become end candidate of an existing subsequence or
- // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
- // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
+ // array[i] will become end candidate of an existing subsequence or
+ // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
+ // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
else
- tail[upperBound(tail, -1, length-1, array[i])] = array[i];
+ tail[upperBound(tail, -1, length - 1, array[i])] = array[i];
}
-
+
return length;
}
}
\ No newline at end of file
diff --git a/Dynamic Programming/LongestValidParentheses.java b/Dynamic Programming/LongestValidParentheses.java
new file mode 100644
index 000000000000..1a42b258d144
--- /dev/null
+++ b/Dynamic Programming/LongestValidParentheses.java
@@ -0,0 +1,59 @@
+import java.util.Scanner;
+
+/**
+ * Given a string containing just the characters '(' and ')', find the length of
+ * the longest valid (well-formed) parentheses substring.
+ *
+ * @author Libin Yang (https://github.com/yanglbme)
+ * @since 2018/10/5
+ */
+
+public class LongestValidParentheses {
+
+ public static int getLongestValidParentheses(String s) {
+ if (s == null || s.length() < 2) {
+ return 0;
+ }
+ char[] chars = s.toCharArray();
+ int n = chars.length;
+ int[] res = new int[n];
+ res[0] = 0;
+ res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0;
+
+ int max = res[1];
+
+ for (int i = 2; i < n; ++i) {
+ if (chars[i] == ')') {
+ if (chars[i - 1] == '(') {
+ res[i] = res[i - 2] + 2;
+ } else {
+ int index = i - res[i - 1] - 1;
+ if (index >= 0 && chars[index] == '(') {
+ // ()(())
+ res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
+ }
+ }
+ }
+ max = Math.max(max, res[i]);
+ }
+
+ return max;
+
+ }
+
+ public static void main(String[] args) {
+ Scanner sc = new Scanner(System.in);
+
+ while (true) {
+ String str = sc.nextLine();
+ if ("quit".equals(str)) {
+ break;
+ }
+ int len = getLongestValidParentheses(str);
+ System.out.println(len);
+
+ }
+
+ sc.close();
+ }
+}
diff --git a/Dynamic Programming/MatrixChainMultiplication.java b/Dynamic Programming/MatrixChainMultiplication.java
new file mode 100644
index 000000000000..d84ecf2299b6
--- /dev/null
+++ b/Dynamic Programming/MatrixChainMultiplication.java
@@ -0,0 +1,134 @@
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Scanner;
+
+public class MatrixChainMultiplication {
+ private static Scanner scan = new Scanner(System.in);
+ private static ArrayList mArray = new ArrayList<>();
+ private static int size;
+ private static int[][] m;
+ private static int[][] s;
+ private static int[] p;
+
+ public static void main(String[] args) {
+ int count = 1;
+ while (true) {
+ String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : ");
+ int col = Integer.parseInt(mSize[0]);
+ if (col == 0) break;
+ int row = Integer.parseInt(mSize[1]);
+
+ Matrix matrix = new Matrix(count, col, row);
+ mArray.add(matrix);
+ count++;
+ }
+ for (Matrix m : mArray) {
+ System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row());
+ }
+
+ size = mArray.size();
+ m = new int[size + 1][size + 1];
+ s = new int[size + 1][size + 1];
+ p = new int[size + 1];
+
+ for (int i = 0; i < size + 1; i++) {
+ Arrays.fill(m[i], -1);
+ Arrays.fill(s[i], -1);
+ }
+
+ for (int i = 0; i < p.length; i++) {
+ p[i] = i == 0 ? mArray.get(i).col() : mArray.get(i - 1).row();
+ }
+
+ matrixChainOrder();
+ for (int i = 0; i < size; i++) {
+ System.out.print("-------");
+ }
+ System.out.println();
+ printArray(m);
+ for (int i = 0; i < size; i++) {
+ System.out.print("-------");
+ }
+ System.out.println();
+ printArray(s);
+ for (int i = 0; i < size; i++) {
+ System.out.print("-------");
+ }
+ System.out.println();
+
+ System.out.println("Optimal solution : " + m[1][size]);
+ System.out.print("Optimal parens : ");
+ printOptimalParens(1, size);
+ }
+
+ private static void printOptimalParens(int i, int j) {
+ if (i == j) {
+ System.out.print("A" + i);
+ } else {
+ System.out.print("(");
+ printOptimalParens(i, s[i][j]);
+ printOptimalParens(s[i][j] + 1, j);
+ System.out.print(")");
+ }
+ }
+
+ private static void printArray(int[][] array) {
+ for (int i = 1; i < size + 1; i++) {
+ for (int j = 1; j < size + 1; j++) {
+ System.out.print(String.format("%7d", array[i][j]));
+ }
+ System.out.println();
+ }
+ }
+
+ private static void matrixChainOrder() {
+ for (int i = 1; i < size + 1; i++) {
+ m[i][i] = 0;
+ }
+
+ for (int l = 2; l < size + 1; l++) {
+ for (int i = 1; i < size - l + 2; i++) {
+ int j = i + l - 1;
+ m[i][j] = Integer.MAX_VALUE;
+
+ for (int k = i; k < j; k++) {
+ int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
+ if (q < m[i][j]) {
+ m[i][j] = q;
+ s[i][j] = k;
+ }
+ }
+ }
+ }
+ }
+
+ private static String[] input(String string) {
+ System.out.print(string);
+ return (scan.nextLine().split(" "));
+ }
+
+}
+
+class Matrix {
+ private int count;
+ private int col;
+ private int row;
+
+ Matrix(int count, int col, int row) {
+ this.count = count;
+ this.col = col;
+ this.row = row;
+ }
+
+ int count() {
+ return count;
+ }
+
+ int col() {
+ return col;
+ }
+
+ int row() {
+ return row;
+ }
+}
diff --git a/Dynamic Programming/RodCutting.java b/Dynamic Programming/RodCutting.java
index cd2512059ae2..5ee38e0ced33 100644
--- a/Dynamic Programming/RodCutting.java
+++ b/Dynamic Programming/RodCutting.java
@@ -1,32 +1,31 @@
-/* A Dynamic Programming solution for Rod cutting problem
- Returns the best obtainable price for a rod of
- length n and price[] as prices of different pieces */
-
+/**
+ * A Dynamic Programming solution for Rod cutting problem
+ * Returns the best obtainable price for a rod of
+ * length n and price[] as prices of different pieces
+ *
+ */
public class RodCutting {
-
- private static int cutRod(int price[],int n)
- {
- int val[] = new int[n+1];
- val[0] = 0;
- for (int i = 1; i<=n; i++)
- {
- int max_val = Integer.MIN_VALUE;
- for (int j = 0; j < i; j++)
- max_val = Math.max(max_val,price[j] + val[i-j-1]);
-
- val[i] = max_val;
- }
+ private static int cutRod(int[] price, int n) {
+ int val[] = new int[n + 1];
+ val[0] = 0;
+
+ for (int i = 1; i <= n; i++) {
+ int max_val = Integer.MIN_VALUE;
+ for (int j = 0; j < i; j++)
+ max_val = Math.max(max_val, price[j] + val[i - j - 1]);
+
+ val[i] = max_val;
+ }
- return val[n];
- }
+ return val[n];
+ }
- //main function to test
- public static void main(String args[])
- {
- int arr[] = new int[] {2, 5, 13, 19, 20};
- int size = arr.length;
- System.out.println("Maximum Obtainable Value is " +
- cutRod(arr, size));
- }
+ // main function to test
+ public static void main(String args[]) {
+ int[] arr = new int[]{2, 5, 13, 19, 20};
+ int size = arr.length;
+ System.out.println("Maximum Obtainable Value is " +
+ cutRod(arr, size));
+ }
}
diff --git a/Misc/MedianOfRunningArray.java b/Misc/MedianOfRunningArray.java
new file mode 100644
index 000000000000..113f19c72b9b
--- /dev/null
+++ b/Misc/MedianOfRunningArray.java
@@ -0,0 +1,50 @@
+import java.util.Collections;
+import java.util.PriorityQueue;
+
+/**********************
+author: shrutisheoran
+***********************/
+
+public class MedianOfRunningArray {
+ private PriorityQueue p1;
+ private PriorityQueue p2;
+
+ //Constructor
+ public MedianOfRunningArray() {
+ this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap
+ this.p2 = new PriorityQueue<>(); //Min Heap
+ }
+
+ /*
+ Inserting lower half of array to max Heap
+ and upper half to min heap
+ */
+ public void insert(Integer e) {
+ p2.add(e);
+ if(p2.size() - p1.size() > 1)
+ p1.add(p2.remove());
+ }
+
+ /*
+ Returns median at any given point
+ */
+ public Integer median() {
+ if(p1.size()==p2.size())
+ return (p1.peek() + p2.peek())/2;
+ return p1.size()>p2.size() ? p1.peek() : p2.peek();
+ }
+
+ public static void main(String[] args) {
+ /*
+ Testing the median function
+ */
+
+ MedianOfRunningArray p = new MedianOfRunningArray();
+ int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
+ for(int i = 0 ; i < 9 ; i++) {
+ p.insert(arr[i]);
+ System.out.print(p.median() + " ");
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/Misc/PalindromicPrime.java b/Misc/PalindromicPrime.java
index 866467206456..bb2c82480634 100644
--- a/Misc/PalindromicPrime.java
+++ b/Misc/PalindromicPrime.java
@@ -1,15 +1,16 @@
import java.util.Scanner;
+
public class PalindromePrime {
public static void main(String[] args) { // Main funtion
Scanner in = new Scanner(System.in);
System.out.println("Enter the quantity of First Palindromic Primes you want");
- int n = in.nextInt(); // Input of how mant first pallindromic prime we want
- funtioning(n); // calling funtion - functioning
+ int n = in.nextInt(); // Input of how many first pallindromic prime we want
+ functioning(n); // calling function - functioning
}
public static boolean prime(int num) { // checking if number is prime or not
- for (int divisor = 2; divisor <= num / 2; divisor++) {
+ for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) {
if (num % divisor == 0) {
return false; // false if not prime
}
@@ -17,25 +18,27 @@ public static boolean prime(int num) { // checking if number is prime or not
return true; // True if prime
}
- public static int reverse(int n){ // Returns the reverse of the number
+ public static int reverse(int n) { // Returns the reverse of the number
int reverse = 0;
- while(n!=0){
- reverse = reverse * 10;
- reverse = reverse + n%10;
- n = n/10;
+ while(n != 0) {
+ reverse *= 10;
+ reverse += n%10;
+ n /= 10;
}
return reverse;
}
- public static void funtioning(int y){
- int count =0;
- int num = 2;
- while(count < y){
- if(prime(num) && num == reverse(num)){ // number is prime and it's reverse is same
- count++; // counts check when to terminate while loop
- System.out.print(num + "\n"); // Print the Palindromic Prime
- }
- num++; // inrease iterator value by one
+ public static void functioning(int y) {
+ if (y == 0) return;
+ System.out.print(2 + "\n"); // print the first Palindromic Prime
+ int count = 1;
+ int num = 3;
+ while(count < y) {
+ if(num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
+ count++; // counts check when to terminate while loop
+ System.out.print(num + "\n"); // print the Palindromic Prime
}
+ num += 2; // inrease iterator value by two
+ }
}
-};
+}
diff --git a/Others/Armstrong.java b/Others/Armstrong.java
index 9267d9eaf648..9bdb31918d19 100644
--- a/Others/Armstrong.java
+++ b/Others/Armstrong.java
@@ -9,10 +9,10 @@
*
*/
public class Armstrong {
+ static Scanner scan;
public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.println("please enter the number");
- int n = scan.nextInt();
+ scan = new Scanner(System.in);
+ int n = inputInt("please enter the number");
boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n);
if (isArmstrong) {
System.out.println("the number is armstrong");
@@ -42,6 +42,9 @@ public static boolean checkIfANumberIsAmstrongOrNot(int number) {
} else {
return false;
}
-
+ }
+ private static int inputInt(String string) {
+ System.out.print(string);
+ return Integer.parseInt(scan.nextLine());
}
}
\ No newline at end of file
diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java
new file mode 100644
index 000000000000..d53e3a02c2e3
--- /dev/null
+++ b/Others/CRCAlgorithm.java
@@ -0,0 +1,203 @@
+package Others;
+
+import java.util.ArrayList;
+import java.util.Random;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * @author dimgrichr
+ */
+public class CRCAlgorithm {
+
+ private int correctMess;
+
+ private int wrongMess;
+
+ private int wrongMessCaught;
+
+ private int wrongMessNotCaught;
+
+ private int messSize;
+
+ private double ber;
+
+ private boolean messageChanged;
+
+ private ArrayList message;
+
+ private ArrayList dividedMessage;
+
+ private ArrayList p;
+
+ private Random randomGenerator;
+
+
+ /**
+ * The algorithm's main constructor.
+ * The most significant variables, used in the algorithm,
+ * are set in their initial values.
+ *
+ * @param str The binary number P, in a string form, which is used by the CRC algorithm
+ * @param size The size of every transmitted message
+ * @param ber The Bit Error Rate
+ */
+ public CRCAlgorithm(String str, int size, double ber) {
+ messageChanged = false;
+ message = new ArrayList<>();
+ messSize = size;
+ dividedMessage = new ArrayList<>();
+ p = new ArrayList<>();
+ for (int i = 0; i < str.length(); i++) {
+ p.add(Character.getNumericValue(str.charAt(i)));
+ }
+ randomGenerator = new Random();
+ correctMess = 0;
+ wrongMess = 0;
+ wrongMessCaught = 0;
+ wrongMessNotCaught = 0;
+ this.ber = ber;
+ }
+
+
+ /**
+ * Returns the counter wrongMess
+ *
+ * @return wrongMess, the number of Wrong Messages
+ */
+ public int getWrongMess() {
+ return wrongMess;
+ }
+
+ /**
+ * Returns the counter wrongMessCaught
+ *
+ * @return wrongMessCaught, the number of wrong messages, which are caught by the CRC algoriithm
+ */
+ public int getWrongMessCaught() {
+ return wrongMessCaught;
+ }
+
+ /**
+ * Returns the counter wrongMessNotCaught
+ *
+ * @return wrongMessNotCaught, the number of wrong messages, which are not caught by the CRC algorithm
+ */
+ public int getWrongMessNotCaught() {
+ return wrongMessNotCaught;
+ }
+
+ /**
+ * Returns the counter correctMess
+ *
+ * @return correctMess, the number of the Correct Messages
+ */
+ public int getCorrectMess() {
+ return correctMess;
+ }
+
+ /**
+ * Resets some of the object's values, used on the main function,
+ * so that it can be re-used, in order not to waste too much memory and time,
+ * by creating new objects.
+ */
+ public void refactor() {
+ messageChanged = false;
+ message = new ArrayList<>();
+ dividedMessage = new ArrayList<>();
+ }
+
+ /**
+ * Random messages, consisted of 0's and 1's,
+ * are generated, so that they can later be transmitted
+ */
+ public void generateRandomMess() {
+ for (int i = 0; i < messSize; i++) {
+ int x = ThreadLocalRandom.current().nextInt(0, 2);
+ message.add(x);
+ }
+ }
+
+ /**
+ * The most significant part of the CRC algorithm.
+ * The message is divided by P, so the dividedMessage ArrayList is created.
+ * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's.
+ * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes.
+ * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes.
+ * If check == false, the diviided Message is added at the end of the ArrayList message.
+ *
+ * @param check the variable used to determine, if the message is going to be checked from the receiver
+ * if true, it is checked
+ * otherwise, it is not
+ */
+ public void divideMessageWithP(boolean check) {
+ ArrayList x = new ArrayList<>();
+ ArrayList k = (ArrayList) message.clone();
+ if (!check) {
+ for (int i = 0; i < p.size() - 1; i++) {
+ k.add(0);
+ }
+ }
+ while (!k.isEmpty()) {
+ while (x.size() < p.size() && !k.isEmpty()) {
+ x.add(k.get(0));
+ k.remove(0);
+ }
+ if (x.size() == p.size()) {
+ for (int i = 0; i < p.size(); i++) {
+ if (x.get(i) == p.get(i)) {
+ x.set(i, 0);
+ } else {
+ x.set(i, 1);
+ }
+ }
+ for (int i = 0; i < x.size() && x.get(i) != 1; i++) {
+ x.remove(0);
+ }
+ }
+ }
+ dividedMessage = (ArrayList) x.clone();
+ if (!check) {
+ for (int z : dividedMessage) {
+ message.add(z);
+ }
+ } else {
+ if (dividedMessage.contains(1) && messageChanged) {
+ wrongMessCaught++;
+ } else if (!dividedMessage.contains(1) && messageChanged) {
+ wrongMessNotCaught++;
+ } else if (!messageChanged) {
+ correctMess++;
+ }
+ }
+ }
+
+ /**
+ * Once the message is transmitted, some of it's elements,
+ * is possible to change from 1 to 0, or from 0 to 1,
+ * because of the Bit Error Rate (ber).
+ * For every element of the message, a random double number is created.
+ * If that number is smaller than ber, then the spesific element changes.
+ * On the other hand, if it's bigger than ber, it does not.
+ * Based on these changes. the boolean variable messageChanged, gets the value:
+ * true, or false.
+ */
+ public void changeMess() {
+ for (int y : message) {
+ double x = randomGenerator.nextDouble();
+ while (x < 0.0000 || x > 1.00000) {
+ x = randomGenerator.nextDouble();
+ }
+ if (x < ber) {
+ messageChanged = true;
+ if (y == 1) {
+ message.set(message.indexOf(y), 0);
+ } else {
+ message.set(message.indexOf(y), 1);
+ }
+ }
+ }
+ if (messageChanged) {
+ wrongMess++;
+ }
+ }
+}
diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java
index 05011dd4212f..17f8391777aa 100644
--- a/Others/Dijkshtra.java
+++ b/Others/Dijkshtra.java
@@ -1,61 +1,82 @@
-/*
-@author : Mayank K Jha
+/**
+ * @author Mayank K Jha
+ */
-*/
-
-
-import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
public class Dijkshtra {
-public static void main(String[] args) throws IOException {
- Scanner in =new Scanner(System.in);
-
- int n=in.nextInt(); //n = Number of nodes or vertices
- int m=in.nextInt(); //m = Number of Edges
- long w[][]=new long [n+1][n+1]; //Adjacency Matrix
-
- //Initializing Matrix with Certain Maximum Value for path b/w any two vertices
- for (long[] row: w)
- Arrays.fill(row, 1000000l);
- //From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
- //For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l .
-
- //Taking Input as Edge Location b/w a pair of vertices
- for(int i=0;icmp){ //Comparing previous edge value with current value - Cycle Case
- w[x][y]=cmp; w[y][x]=cmp;
- }
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+
+ // n = Number of nodes or vertices
+ int n = in.nextInt();
+ // m = Number of Edges
+ int m = in.nextInt();
+
+ // Adjacency Matrix
+ long[][] w = new long[n + 1][n + 1];
+
+ // Initializing Matrix with Certain Maximum Value for path b/w any two vertices
+ for (long[] row : w) {
+ Arrays.fill(row, 1000000L);
+ }
+
+ /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
+ For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */
+
+ // Taking Input as Edge Location b/w a pair of vertices
+ for (int i = 0; i < m; i++) {
+ int x = in.nextInt(), y = in.nextInt();
+ long cmp = in.nextLong();
+
+ // Comparing previous edge value with current value - Cycle Case
+ if (w[x][y] > cmp) {
+ w[x][y] = cmp;
+ w[y][x] = cmp;
+ }
+ }
+
+ // Implementing Dijkshtra's Algorithm
+ Stack t = new Stack<>();
+ int src = in.nextInt();
+
+ for (int i = 1; i <= n; i++) {
+ if (i != src) {
+ t.push(i);
+ }
+ }
+
+ Stack p = new Stack<>();
+ p.push(src);
+ w[src][src] = 0;
+
+ while (!t.isEmpty()) {
+ int min = 989997979;
+ int loc = -1;
+
+ for (int i = 0; i < t.size(); i++) {
+ w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]);
+ if (w[src][t.elementAt(i)] <= min) {
+ min = (int) w[src][t.elementAt(i)];
+ loc = i;
+ }
+ }
+ p.push(t.elementAt(loc));
+ t.removeElementAt(loc);
+ }
+
+ // Printing shortest path from the given source src
+ for (int i = 1; i <= n; i++) {
+ if (i != src && w[src][i] != 1000000L) {
+ System.out.print(w[src][i] + " ");
+ }
+ // Printing -1 if there is no path b/w given pair of edges
+ else if (i != src) {
+ System.out.print("-1" + " ");
+ }
+ }
}
-
- //Implementing Dijkshtra's Algorithm
-
- Stack t=new Stack();
- int src=in.nextInt();
- for(int i=1;i<=n;i++){
- if(i!=src){t.push(i);}}
- Stack p=new Stack();
- p.push(src);
- w[src][src]=0;
- while(!t.isEmpty()){int min=989997979,loc=-1;
- for(int i=0;i
+ * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
+ * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
+ *
+ * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
+ * Also most of the comments are from RosettaCode.
+ */
+
+import java.util.*;
+
+public class Dijkstra {
+ private static final Graph.Edge[] GRAPH = {
+ // Distance from node "a" to node "b" is 7.
+ // In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
+ // a new edge would be needed for that
+ new Graph.Edge("a", "b", 7),
+ new Graph.Edge("a", "c", 9),
+ new Graph.Edge("a", "f", 14),
+ new Graph.Edge("b", "c", 10),
+ new Graph.Edge("b", "d", 15),
+ new Graph.Edge("c", "d", 11),
+ new Graph.Edge("c", "f", 2),
+ new Graph.Edge("d", "e", 6),
+ new Graph.Edge("e", "f", 9),
+ };
+ private static final String START = "a";
+ private static final String END = "e";
+
+ /**
+ * main function
+ * Will run the code with "GRAPH" that was defined above.
+ */
+ public static void main(String[] args) {
+ Graph g = new Graph(GRAPH);
+ g.dijkstra(START);
+ g.printPath(END);
+ //g.printAllPaths();
+ }
+}
+
+class Graph {
+ // mapping of vertex names to Vertex objects, built from a set of Edges
+ private final Map graph;
+
+ /** One edge of the graph (only used by Graph constructor) */
+ public static class Edge {
+ public final String v1, v2;
+ public final int dist;
+
+ public Edge(String v1, String v2, int dist) {
+ this.v1 = v1;
+ this.v2 = v2;
+ this.dist = dist;
+ }
+ }
+
+ /** One vertex of the graph, complete with mappings to neighbouring vertices */
+ public static class Vertex implements Comparable {
+ public final String name;
+ // MAX_VALUE assumed to be infinity
+ public int dist = Integer.MAX_VALUE;
+ public Vertex previous = null;
+ public final Map neighbours = new HashMap<>();
+
+ public Vertex(String name) {
+ this.name = name;
+ }
+
+ private void printPath() {
+ if (this == this.previous) {
+ System.out.printf("%s", this.name);
+ } else if (this.previous == null) {
+ System.out.printf("%s(unreached)", this.name);
+ } else {
+ this.previous.printPath();
+ System.out.printf(" -> %s(%d)", this.name, this.dist);
+ }
+ }
+
+ public int compareTo(Vertex other) {
+ if (dist == other.dist)
+ return name.compareTo(other.name);
+
+ return Integer.compare(dist, other.dist);
+ }
+
+ @Override
+ public String toString() {
+ return "(" + name + ", " + dist + ")";
+ }
+ }
+
+ /** Builds a graph from a set of edges */
+ public Graph(Edge[] edges) {
+ graph = new HashMap<>(edges.length);
+
+ // one pass to find all vertices
+ for (Edge e : edges) {
+ if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
+ if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
+ }
+
+ // another pass to set neighbouring vertices
+ for (Edge e : edges) {
+ graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
+ // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
+ }
+ }
+
+ /** Runs dijkstra using a specified source vertex */
+ public void dijkstra(String startName) {
+ if (!graph.containsKey(startName)) {
+ System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
+ return;
+ }
+ final Vertex source = graph.get(startName);
+ NavigableSet q = new TreeSet<>();
+
+ // set-up vertices
+ for (Vertex v : graph.values()) {
+ v.previous = v == source ? source : null;
+ v.dist = v == source ? 0 : Integer.MAX_VALUE;
+ q.add(v);
+ }
+
+ dijkstra(q);
+ }
+
+ /** Implementation of dijkstra's algorithm using a binary heap. */
+ private void dijkstra(final NavigableSet q) {
+ Vertex u, v;
+ while (!q.isEmpty()) {
+ // vertex with shortest distance (first iteration will return source)
+ u = q.pollFirst();
+ if (u.dist == Integer.MAX_VALUE)
+ break; // we can ignore u (and any other remaining vertices) since they are unreachable
+
+ // look at distances to each neighbour
+ for (Map.Entry a : u.neighbours.entrySet()) {
+ v = a.getKey(); // the neighbour in this iteration
+
+ final int alternateDist = u.dist + a.getValue();
+ if (alternateDist < v.dist) { // shorter path to neighbour found
+ q.remove(v);
+ v.dist = alternateDist;
+ v.previous = u;
+ q.add(v);
+ }
+ }
+ }
+ }
+
+ /** Prints a path from the source to the specified vertex */
+ public void printPath(String endName) {
+ if (!graph.containsKey(endName)) {
+ System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
+ return;
+ }
+
+ graph.get(endName).printPath();
+ System.out.println();
+ }
+
+ /** Prints the path from the source to every vertex (output order is not guaranteed) */
+ public void printAllPaths() {
+ for (Vertex v : graph.values()) {
+ v.printPath();
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Others/EulersFunction.java b/Others/EulersFunction.java
new file mode 100644
index 000000000000..01b7575d4dc5
--- /dev/null
+++ b/Others/EulersFunction.java
@@ -0,0 +1,21 @@
+// You can read more about Euler's totient function
+// https://en.wikipedia.org/wiki/Euler%27s_totient_function
+public class EulersFunction {
+ // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity;
+ public static int getEuler(int n) {
+ int result = n;
+ for (int i = 2; i * i <= n; i++) {
+ if(n % i == 0) {
+ while (n % i == 0) n /= i;
+ result -= result / i;
+ }
+ }
+ if (n > 1) result -= result / n;
+ return result;
+ }
+ public static void main(String[] args) {
+ for (int i = 1; i < 100; i++) {
+ System.out.println(getEuler(i));
+ }
+ }
+}
diff --git a/Others/FibToN.java b/Others/FibToN.java
index 1d1efdc1e753..ae2de417aa50 100644
--- a/Others/FibToN.java
+++ b/Others/FibToN.java
@@ -1,14 +1,22 @@
+/**
+ *
+ * Fibonacci sequence, and characterized by the fact that every number
+ * after the first two is the sum of the two preceding ones.
+ *
+ * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,...
+ *
+ * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number
+ */
+
import java.util.Scanner;
public class FibToN {
-
public static void main(String[] args) {
//take input
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
- // print fibonacci sequence less than N
+ // print all Fibonacci numbers that are smaller than your given input N
int first = 0, second = 1;
- //first fibo and second fibonacci are 0 and 1 respectively
scn.close();
while(first <= N){
//print first fibo 0 then add second fibo into it while updating second as well
diff --git a/Others/GCD.java b/Others/GCD.java
index 08da3805e9d8..58a2b5eef5aa 100644
--- a/Others/GCD.java
+++ b/Others/GCD.java
@@ -2,29 +2,37 @@
//This is Euclid's algorithm which is used to find the greatest common denominator
//Overide function name gcd
-public class GCD{
-
- public static int gcd(int num1, int num2) {
-
- int gcdValue = num1 % num2;
- while (gcdValue != 0) {
- num2 = gcdValue;
- gcdValue = num2 % gcdValue;
+public class GCD {
+
+ public static int gcd(int num1, int num2) {
+
+ if (num1 == 0)
+ return num2;
+
+ while (num2 != 0) {
+ if (num1 > num2)
+ num1 -= num2;
+ else
+ num2 -= num1;
}
- return num2;
+
+ return num1;
}
- public static int gcd(int[] number) {
- int result = number[0];
- for(int i = 1; i < number.length; i++)
- //call gcd function (input two value)
- result = gcd(result, number[i]);
-
- return result;
- }
-
- public static void main(String[] args) {
- int[] myIntArray = {4,16,32};
- //call gcd function (input array)
- System.out.println(gcd(myIntArray));
+
+ public static int gcd(int[] number) {
+ int result = number[0];
+ for (int i = 1; i < number.length; i++)
+ // call gcd function (input two value)
+ result = gcd(result, number[i]);
+
+ return result;
+ }
+
+ public static void main(String[] args) {
+ int[] myIntArray = { 4, 16, 32 };
+
+ // call gcd function (input array)
+ System.out.println(gcd(myIntArray)); // => 4
+ System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8
}
}
diff --git a/Others/GuassLengendre.java b/Others/GuassLegendre.java
similarity index 100%
rename from Others/GuassLengendre.java
rename to Others/GuassLegendre.java
diff --git a/Others/Huffman.java b/Others/Huffman.java
index f3ab6c6b5800..0d937271112f 100644
--- a/Others/Huffman.java
+++ b/Others/Huffman.java
@@ -1,4 +1,3 @@
-
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
@@ -14,24 +13,24 @@
Enter number of distinct letters
6
-Enter letters with its frequncy to encode
+Enter letters with its frequency to encode
Enter letter : a
-Enter frequncy : 45
+Enter frequency : 45
Enter letter : b
-Enter frequncy : 13
+Enter frequency : 13
Enter letter : c
-Enter frequncy : 12
+Enter frequency : 12
Enter letter : d
-Enter frequncy : 16
+Enter frequency : 16
Enter letter : e
-Enter frequncy : 9
+Enter frequency : 9
Enter letter : f
-Enter frequncy : 5
+Enter frequency : 5
Letter Encoded Form
a 0
@@ -64,17 +63,17 @@ public class Huffman {
// A simple function to print a given list
//I just made it for debugging
- public static void print_list(List li){
+ public static void print_list(List li){
Iterator it=li.iterator();
while(it.hasNext()){Node n=it.next();System.out.print(n.freq+" ");}System.out.println();
}
//Function for making tree (Huffman Tree)
- public static Node make_huffmann_tree(List li){
+ public static Node make_huffmann_tree(List li){
//Sorting list in increasing order of its letter frequency
li.sort(new comp());
Node temp=null;
- Iterator it=li.iterator();
+ Iterator it=li.iterator();
//System.out.println(li.size());
//Loop for making huffman tree till only single node remains in list
while(true){
@@ -89,7 +88,7 @@ public static Node make_huffmann_tree(List li){
//Below condition is to check either list has 2nd node or not to combine
//If this condition will be false, then it means construction of huffman tree is completed
if(it.hasNext()){b=(Node)it.next();}
- //Combining first two smallest nodes in list to make its parent whose frequncy
+ //Combining first two smallest nodes in list to make its parent whose frequency
//will be equals to sum of frequency of these two nodes
if(b!=null){
temp.freq=a.freq+b.freq;a.data=0;b.data=1;//assigining 0 and 1 to left and right nodes
@@ -109,7 +108,7 @@ public static Node make_huffmann_tree(List li){
//Function for finding path between root and given letter ch
public static void dfs(Node n,String ch){
- Stack st=new Stack(); // stack for storing path
+ Stack st=new Stack(); // stack for storing path
int freq=n.freq; // recording root freq to avoid it adding in path encoding
find_path_and_encode(st,n,ch,freq);
}
@@ -140,15 +139,16 @@ public static void main(String args[]){
System.out.println("Enter number of distinct letters ");
int n=in.nextInt();
String s[]=new String[n];
- System.out.print("Enter letters with its frequncy to encode\n");
+ System.out.print("Enter letters with its frequency to encode\n");
for(int i=0;i 0 && T.charAt(i) != P.charAt(q)) {
+ while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
q = pi[q - 1];
}
- if (T.charAt(i) == P.charAt(q)) {
+ if (haystack.charAt(i) == needle.charAt(q)) {
q++;
}
@@ -28,11 +29,9 @@ public void KMPmatcher(final String T, final String P) {
q = pi[q - 1];
}
}
-
}
-
// return the prefix function
- private int[] computePrefixFunction(final String P) {
+ private static int[] computePrefixFunction(final String P) {
final int n = P.length();
final int[] pi = new int[n];
pi[0] = 0;
@@ -49,7 +48,6 @@ private int[] computePrefixFunction(final String P) {
pi[i] = q;
}
-
return pi;
}
-}
+}
\ No newline at end of file
diff --git a/Others/Palindrome.java b/Others/Palindrome.java
index 0bbddb7544c8..d482dfd01bce 100644
--- a/Others/Palindrome.java
+++ b/Others/Palindrome.java
@@ -1,26 +1,23 @@
class Palindrome {
-
- private String reverseString(String x){ //*helper method
- String output = "";
- for(int i=x.length()-1; i>=0; i--){
- output += x.charAt(i); //addition of chars create String
- }
- return output;
- }
-
-
- public Boolean FirstWay(String x){ //*palindrome method, returns true if palindrome
- return (x.equalsIgnoreCase(reverseString(x)));
- }
-
- public boolean SecondWay(String x)
- {
- if (x.length() == 0 || x.length() == 1)
- return true;
- if (x.charAt(0) != x.charAt(x.length() - 1))
- return false;
+ private String reverseString(String x) { // *helper method
+ StringBuilder output = new StringBuilder(x);
+ return output.reverse().toString();
+ }
- return SecondWay(x.substring(1 , x.length() - 1));
- }
- }
+ public boolean FirstWay(String x) { // *palindrome method, returns true if palindrome
+ if (x == null || x.length() <= 1)
+ return true;
+ return x.equalsIgnoreCase(reverseString(x));
+ }
+
+ public boolean SecondWay(String x) {
+ if (x.length() == 0 || x.length() == 1)
+ return true;
+
+ if (x.charAt(0) != x.charAt(x.length() - 1))
+ return false;
+
+ return SecondWay(x.substring(1, x.length() - 1));
+ }
+}
diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java
index b792d692f675..3e3b73b82836 100644
--- a/Others/RootPrecision.java
+++ b/Others/RootPrecision.java
@@ -1,33 +1,32 @@
-import java.io.*;
-import java.util.*;
-import java.text.*;
-import java.math.*;
-import java.util.regex.*;
+import java.util.Scanner;
public class RootPrecision {
public static void main(String[] args) {
- //take input
- Scanner scn = new Scanner(System.in);
-
- int N = scn.nextInt(); //N is the input number
- int P = scn.nextInt(); //P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
-
- System.out.println(squareRoot(N, P));
- }
-
- public static double squareRoot(int N, int P) {
- double rv = 0; //rv means return value
-
+ // take input
+ Scanner scn = new Scanner(System.in);
+
+ // N is the input number
+ int N = scn.nextInt();
+
+ // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
+ int P = scn.nextInt();
+ System.out.println(squareRoot(N, P));
+ }
+
+ public static double squareRoot(int N, int P) {
+ // rv means return value
+ double rv;
+
double root = Math.pow(N, 0.5);
-
- //calculate precision to power of 10 and then multiply it with root value.
- int precision = (int) Math.pow(10, P);
- root = root * precision;
- /*typecast it into integer then divide by precision and again typecast into double
- so as to have decimal points upto P precision */
-
- rv = (int)root;
- return (double)rv/precision;
- }
-}
+
+ // calculate precision to power of 10 and then multiply it with root value.
+ int precision = (int) Math.pow(10, P);
+ root = root * precision;
+ /*typecast it into integer then divide by precision and again typecast into double
+ so as to have decimal points upto P precision */
+
+ rv = (int) root;
+ return rv / precision;
+ }
+}
\ No newline at end of file
diff --git a/Others/SJF.java b/Others/SJF.java
new file mode 100644
index 000000000000..923ece654939
--- /dev/null
+++ b/Others/SJF.java
@@ -0,0 +1,179 @@
+/**
+* Shortest job first.
+* Shortest job first (SJF) or shortest job next, is a scheduling policy
+* that selects the waiting process with the smallest execution time to execute next
+* Shortest Job first has the advantage of having minimum average waiting time among all scheduling algorithms.
+* It is a Greedy Algorithm.
+* It may cause starvation if shorter processes keep coming.
+* This problem has been solved using the concept of aging.
+* @author shivg7706
+* @since 2018/10/27
+*/
+
+import java.util.Scanner;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.*;
+
+class Process {
+
+ public int pid;
+ public int arrivalTime;
+ public int burstTime;
+ public int priority;
+ public int turnAroundTime;
+ public int waitTime;
+ public int remainingTime;
+}
+
+class Schedule {
+
+ private int noOfProcess;
+ private int timer = 0;
+ private ArrayList processes;
+ private ArrayList remainingProcess;
+ private ArrayList gantChart;
+ private float burstAll;
+ private Map> arrivals;
+
+ Schedule() {
+ Scanner in = new Scanner(System.in);
+
+ processes = new ArrayList();
+ remainingProcess = new ArrayList();
+
+ gantChart = new ArrayList<>();
+ arrivals = new HashMap<>();
+
+ System.out.print("Enter the no. of processes: ");
+ noOfProcess = in.nextInt();
+ System.out.println("Enter the arrival, burst and priority of processes");
+ for (int i = 0; i < noOfProcess; i++) {
+ Process p = new Process();
+ p.pid = i;
+ p.arrivalTime = in.nextInt();
+ p.burstTime = in.nextInt();
+ p.priority = in.nextInt();
+ p.turnAroundTime = 0;
+ p.waitTime = 0;
+ p.remainingTime = p.burstTime;
+
+ if (arrivals.get(p.arrivalTime) == null) {
+ arrivals.put(p.arrivalTime, new ArrayList());
+ }
+ arrivals.get(p.arrivalTime).add(p);
+ processes.add(p);
+ burstAll += p.burstTime;
+ }
+
+ }
+
+
+ void startScheduling() {
+
+
+ processes.sort(new Comparator() {
+ @Override
+ public int compare (Process a, Process b) {
+ return a.arrivalTime - b.arrivalTime;
+ }
+ });
+
+ while(!(arrivals.size() == 0 && remainingProcess.size() == 0)) {
+ removeFinishedProcess();
+ if(arrivals.get(timer) != null) {
+ remainingProcess.addAll(arrivals.get(timer));
+ arrivals.remove(timer);
+ }
+
+ remainingProcess.sort(new Comparator() {
+ private int alpha = 6;
+ private int beta = 1;
+
+ @Override
+ public int compare (Process a, Process b) {
+ int aRem = a.remainingTime;
+ int bRem = b.remainingTime;
+ int aprior = a.priority;
+ int bprior = b.priority;
+ return (alpha*aRem + beta*aprior) - (alpha*bRem + beta*bprior);
+ }
+ });
+
+ int k = timeElapsed(timer);
+ ageing(k);
+ timer++;
+ }
+
+ System.out.println("Total time required: " + (timer-1));
+ }
+
+ void removeFinishedProcess() {
+ ArrayList completed = new ArrayList();
+ for (int i = 0; i < remainingProcess.size(); i++) {
+ if(remainingProcess.get(i).remainingTime == 0) {
+ completed.add(i);
+ }
+ }
+
+ for (int i = 0; i < completed.size(); i++) {
+ int pid = remainingProcess.get(completed.get(i)).pid;
+ processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime;
+ remainingProcess.remove(remainingProcess.get(completed.get(i)));
+ }
+
+
+ }
+
+ public int timeElapsed(int i) {
+ if(!remainingProcess.isEmpty()) {
+ gantChart.add(i, remainingProcess.get(0).pid);
+ remainingProcess.get(0).remainingTime--;
+ return 1;
+ }
+ return 0;
+ }
+
+ public void ageing(int k) {
+ for (int i = k; i < remainingProcess.size(); i++) {
+ remainingProcess.get(i).waitTime++;
+ if (remainingProcess.get(i).waitTime % 7 == 0) {
+ remainingProcess.get(i).priority--;
+ }
+ }
+ }
+
+
+ public void solve() {
+ System.out.println("Gant chart ");
+ for (int i = 0; i < gantChart.size(); i++) {
+ System.out.print(gantChart.get(i) + " ");
+ }
+ System.out.println();
+
+ float waitTimeTot = 0;
+ float tatTime = 0;
+
+ for (int i = 0; i < noOfProcess; i++) {
+ processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime;
+
+ waitTimeTot += processes.get(i).waitTime;
+ tatTime += processes.get(i).turnAroundTime;
+
+ System.out.println("Process no.: " + i + " Wait time: " + processes.get(i).waitTime + " Turn Around Time: " + processes.get(i).turnAroundTime);
+ }
+
+ System.out.println("Average Waiting Time: " + waitTimeTot/noOfProcess);
+ System.out.println("Average TAT Time: " + tatTime/noOfProcess);
+ System.out.println("Throughput: " + (float)noOfProcess/(timer - 1));
+ }
+
+}
+
+public class SJF {
+ public static void main(String[] args) {
+ Schedule s = new Schedule();
+ s.startScheduling();
+ s.solve();
+ }
+}
\ No newline at end of file
diff --git a/Others/countwords.java b/Others/countwords.java
index a93aa1a33833..da871047dd58 100644
--- a/Others/countwords.java
+++ b/Others/countwords.java
@@ -1,26 +1,26 @@
import java.util.Scanner;
/**
- * You enter a string into this program, and it will return how
- * many words were in that particular string
- *
- * @author Marcus
+ * You enter a string into this program, and it will return how many words were
+ * in that particular string
*
+ * @author Marcus
*/
- public class countwords{
+public class CountWords {
- public static void main(String[] args){
- Scanner input = new Scanner(System.in);
- System.out.println("Enter your text: ");
- String str = input.nextLine();
-
- System.out.println("Your text has " + wordCount(str) + " word(s)");
- input.close();
- }
+ public static void main(String[] args) {
+ Scanner input = new Scanner(System.in);
+ System.out.println("Enter your text: ");
+ String str = input.nextLine();
- private static int wordCount(String s){
- if(s.isEmpty() || s == null) return 0;
- return s.trim().split("[\\s]+").length;
- }
-
+ System.out.println("Your text has " + wordCount(str) + " word(s)");
+ input.close();
}
+
+ private static int wordCount(String s) {
+ if (s == null || s.isEmpty())
+ return 0;
+ return s.trim().split("[\\s]+").length;
+ }
+
+}
diff --git a/Others/crc32.java b/Others/crc32.java
index e27c247062d4..de98e4198c9b 100644
--- a/Others/crc32.java
+++ b/Others/crc32.java
@@ -1,27 +1,29 @@
import java.util.BitSet;
-//Generates a crc32 checksum for a given string or byte array
-public class crc32 {
-
+/**
+ * Generates a crc32 checksum for a given string or byte array
+ */
+public class CRC32 {
+
public static void main(String[] args) {
System.out.println(Integer.toHexString(crc32("Hello World")));
}
-
+
public static int crc32(String str) {
return crc32(str.getBytes());
}
-
+
public static int crc32(byte[] data) {
BitSet bitSet = BitSet.valueOf(data);
- int crc32 = 0xFFFFFFFF; //initial value
- for(int i=0;i>>31)&1) != (bitSet.get(i)?1:0))
- crc32 = (crc32 << 1) ^ 0x04C11DB7; //xoring with polynomial
+ int crc32 = 0xFFFFFFFF; // initial value
+ for (int i = 0; i < data.length * 8; i++) {
+ if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
+ crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
else
crc32 = (crc32 << 1);
}
- crc32 = Integer.reverse(crc32); //result reflect
- return crc32 ^ 0xFFFFFFFF; //final xor value
+ crc32 = Integer.reverse(crc32); // result reflect
+ return crc32 ^ 0xFFFFFFFF; // final xor value
}
}
diff --git a/README-ko.md b/README-ko.md
new file mode 100644
index 000000000000..c53868cc1310
--- /dev/null
+++ b/README-ko.md
@@ -0,0 +1,187 @@
+# 알고리즘 - 자바
+
+## 이 [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)는 기존 프로젝트를 Java 프로젝트 구조로 재개발하기 위해 작성되었다. 기여도를 위해 개발 지사로 전환할 수 있다. 자세한 내용은 이 문제를 참조하십시오. 컨트리뷰션을 위해 [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)로 전환할 수 있다. 자세한 내용은 [이 이슈](https://github.com/TheAlgorithms/Java/issues/474)를 참고하십시오.
+
+### 자바로 구현된 모든 알고리즘들 (교육용)
+
+이것들은 단지 시범을 위한 것이다. 표준 자바 라이브러리에는 성능상의 이유로 더 나은 것들이 구현되어있다
+
+## 정렬 알고리즘
+
+
+### Bubble(버블 정렬)
+![alt text][bubble-image]
+
+From [Wikipedia][bubble-wiki]: 버블 소트(sinking sor라고도 불리움)는 리스트를 반복적인 단계로 접근하여 정렬한다. 각각의 짝을 비교하며, 순서가 잘못된 경우 그접한 아이템들을 스왑하는 알고리즘이다. 더 이상 스왑할 것이 없을 때까지 반복하며, 반복이 끝남음 리스트가 정렬되었음을 의미한다.
+
+__속성__
+* 최악의 성능 O(n^2)
+* 최고의 성능 O(n)
+* 평균 성능 O(n^2)
+
+###### View the algorithm in [action][bubble-toptal]
+
+
+
+### Insertion(삽입 정렬)
+![alt text][insertion-image]
+
+From [Wikipedia][insertion-wiki]: 삽입 정렬은 최종 정렬된 배열(또는 리스트)을 한번에 하나씩 구축하는 알고리즘이다. 이것은 큰 리스트에서 더 나은 알고리즘인 퀵 소트, 힙 소트, 또는 머지 소트보다 훨씬 안좋은 효율을 가진다. 그림에서 각 막대는 정렬해야 하는 배열의 요소를 나타낸다. 상단과 두 번째 상단 막대의 첫 번째 교차점에서 발생하는 것은 두 번째 요소가 첫 번째 요소보다 더 높은 우선 순위를 가지기 떄문에 막대로 표시되는 이러한 요소를 교환한 것이다. 이 방법을 반복하면 삽입 정렬이 완료된다.
+
+__속성__
+* 최악의 성능 O(n^2)
+* 최고의 성능 O(n)
+* 평균 O(n^2)
+
+###### View the algorithm in [action][insertion-toptal]
+
+
+### Merge(합병 정렬)
+![alt text][merge-image]
+
+From [Wikipedia][merge-wiki]: 컴퓨터 과학에서, 합병 정렬은 효율적인, 범용적인, 비교 기반 정렬 알고리즘이다. 대부분의 구현은 안정적인 분류를 이루는데, 이것은 구현이 정렬된 출력에 동일한 요소의 입력 순서를 유지한다는 것을 의미한다. 합병 정렬은 1945년에 John von Neumann이 발명한 분할 정복 알고리즘이다.
+
+__속성__
+* 최악의 성능 O(n log n) (일반적)
+* 최고의 성능 O(n log n)
+* 평균 O(n log n)
+
+
+###### View the algorithm in [action][merge-toptal]
+
+### Quick(퀵 정렬)
+![alt text][quick-image]
+
+From [Wikipedia][quick-wiki]: 퀵 정렬sometimes called partition-exchange sort)은 효율적인 정렬 알고리즘으로, 배열의 요소를 순서대로 정렬하는 체계적인 방법 역활을 한다.
+
+__속성__
+* 최악의 성능 O(n^2)
+* 최고의 성능 O(n log n) or O(n) with three-way partition
+* 평균 O(n log n)
+
+###### View the algorithm in [action][quick-toptal]
+
+### Selection(선택 정렬)
+![alt text][selection-image]
+
+From [Wikipedia][selection-wiki]: 알고리즘 입력 리스트를 두 부분으로 나눈다 : 첫 부분은 아이템들이 이미 왼쪽에서 오른쪽으로 정렬되었다. 그리고 남은 부분의 아이템들은 나머지 항목을 차지하는 리스트이다. 처음에는 정렬된 리스트는 공백이고 나머지가 전부이다. 오르차순(또는 내림차순) 알고리즘은 가장 작은 요소를 정렬되지 않은 리스트에서 찾고 정렬이 안된 가장 왼쪽(정렬된 리스트) 리스트와 바꾼다. 이렇게 오른쪽으로 나아간다.
+
+__속성__
+* 최악의 성능 O(n^2)
+* 최고의 성능 O(n^2)
+* 평균 O(n^2)
+
+###### View the algorithm in [action][selection-toptal]
+
+### Shell(쉘 정렬)
+![alt text][shell-image]
+
+From [Wikipedia][shell-wiki]: 쉘 정렬은 멀리 떨어져 있는 항목의 교환을 허용하는 삽입 종류의 일반화이다. 그 아이디어는 모든 n번째 요소가 정렬된 목록을 제공한다는 것을 고려하여 어느 곳에서든지 시작하도록 요소의 목록을 배열하는 것이다. 이러한 목록은 h-sorted로 알려져 있다. 마찬가지로, 각각 개별적으로 정렬된 h 인터리브 목록으로 간주될 수 있다.
+
+__속성__
+* 최악의 성능 O(nlog2 2n)
+* 최고의 성능 O(n log n)
+* Average case performance depends on gap sequence
+
+###### View the algorithm in [action][shell-toptal]
+
+### 시간 복잡성 그래프
+
+정렬 알고리즘의 복잡성 비교 (버블 정렬, 삽입 정렬, 선택 정렬)
+
+[복잡성 그래프](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png)
+
+----------------------------------------------------------------------------------
+
+## 검색 알고리즘
+
+### Linear (선형 탐색)
+![alt text][linear-image]
+
+From [Wikipedia][linear-wiki]: 선형 탐색 또는 순차 탐색은 목록 내에서 목표값을 찾는 방법이다. 일치 항목이 발견되거나 모든 요소가 탐색될 때까지 목록의 각 요소에 대해 목표값을 순차적으로 검사한다.
+ 선형 검색은 최악의 선형 시간으로 실행되며 최대 n개의 비교에서 이루어진다. 여기서 n은 목록의 길이다.
+
+__속성__
+* 최악의 성능 O(n)
+* 최고의 성능 O(1)
+* 평균 O(n)
+* 최악의 경우 공간 복잡성 O(1) iterative
+
+### Binary (이진 탐색)
+![alt text][binary-image]
+
+From [Wikipedia][binary-wiki]: 이진 탐색, (also known as half-interval search or logarithmic search), 은 정렬된 배열 내에서 목표값의 위치를 찾는 검색 알고리즘이다. 목표값을 배열의 중간 요소와 비교한다; 만약 목표값이 동일하지 않으면, 목표물의 절반이 제거되고 검색이 성공할 때까지 나머지 절반에서 게속된다.
+
+__속성__
+* 최악의 성능 O(log n)
+* 최고의 성능 O(1)
+* 평균 O(log n)
+* 최악의 경우 공간 복잡성 O(1)
+
+
+[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
+[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort
+[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort"
+
+[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort
+[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort
+[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort"
+
+[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort
+[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort
+[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort"
+
+[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort
+[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort
+[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort"
+
+[selection-toptal]: https://www.toptal.com/developers/sorting-algorithms/selection-sort
+[selection-wiki]: https://en.wikipedia.org/wiki/Selection_sort
+[selection-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Selection_sort_animation.gif/250px-Selection_sort_animation.gif "Selection Sort Sort"
+
+[shell-toptal]: https://www.toptal.com/developers/sorting-algorithms/shell-sort
+[shell-wiki]: https://en.wikipedia.org/wiki/Shellsort
+[shell-image]: https://upload.wikimedia.org/wikipedia/commons/d/d8/Sorting_shellsort_anim.gif "Shell Sort"
+
+[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search
+[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif
+
+[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm
+[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png
+
+
+--------------------------------------------------------------------
+## 나머지 알고리즘에 대한 링크
+
+전환 | 다이나믹프로그래밍(DP) |암호|그 외 것들|
+----------- |----------------------------------------------------------------|-------|-------------|
+[Any Base to Any Base](Conversions/AnyBaseToAnyBase.java)| [Coin Change](Dynamic%20Programming/CoinChange.java)|[Caesar](ciphers/Caesar.java)|[Heap Sort](misc/heap_sort.java)|
+[Any Base to Decimal](Conversions/AnyBaseToDecimal.java)|[Egg Dropping](Dynamic%20Programming/EggDropping.java)|[Columnar Transposition Cipher](ciphers/ColumnarTranspositionCipher.java)|[Palindromic Prime Checker](misc/PalindromicPrime.java)|
+[Binary to Decimal](Conversions/BinaryToDecimal.java)|[Fibonacci](Dynamic%20Programming/Fibonacci.java)|[RSA](ciphers/RSA.java)|More soon...|
+[Binary to HexaDecimal](Conversions/BinaryToHexadecimal.java)|[Kadane Algorithm](Dynamic%20Programming/KadaneAlgorithm.java)|more coming soon...|
+[Binary to Octal](Conversions/BinaryToOctal.java)|[Knapsack](Dynamic%20Programming/Knapsack.java)|
+[Decimal To Any Base](Conversions/DecimalToAnyBase.java)|[Longest Common Subsequence](Dynamic%20Programming/LongestCommonSubsequence.java)|
+[Decimal To Binary](Conversions/DecimalToBinary.java)|[Longest Increasing Subsequence](Dynamic%20Programming/LongestIncreasingSubsequence.java)|
+[Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java)|[Rod Cutting](Dynamic%20Programming/RodCutting.java)|
+and much more...| and more...|
+
+### 자료 구조
+그래프|힙|리스트|큐|
+------|-----|-----|------|
+[너비우선탐색](DataStructures/Graphs/BFS.java)|[빈 힙 예외처리](DataStructures/Heaps/EmptyHeapException.java)|[원형 연결리스트](DataStructures/Lists/CircleLinkedList.java)|[제너릭 어레이 리스트 큐](DataStructures/Queues/GenericArrayListQueue.java)|
+[깊이우선탐색](DataStructures/Graphs/DFS.java)|[힙](DataStructures/Heaps/Heap.java)|[이중 연결리스트](DataStructures/Lists/DoublyLinkedList.java)|[큐](DataStructures/Queues/Queues.java)|
+[그래프](DataStructures/Graphs/Graphs.java)|[힙 요소](DataStructures/Heaps/HeapElement.java)|[단순 연결리스트](DataStructures/Lists/SinglyLinkedList.java)|
+[크루스칼 알고리즘](DataStructures/Graphs/KruskalsAlgorithm.java)|[최대힙](Data%Structures/Heaps/MaxHeap.java)|
+[행렬 그래프](DataStructures/Graphs/MatrixGraphs.java)|[최소힙](DataStructures/Heaps/MinHeap.java)|
+[프림 최소신장트리](DataStructures/Graphs/PrimMST.java)|
+
+스택|트리|
+------|-----|
+[노드 스택](DataStructures/Stacks/NodeStack.java)|[AVL 트리](DataStructures/Trees/AVLTree.java)|
+[연결리스트 스택](DataStructures/Stacks/StackOfLinkedList.java)|[이진 트리](DataStructures/Trees/BinaryTree.java)|
+[스택](DataStructures/Stacks)|And much more...|
+
+* [Bags](DataStructures/Bags/Bag.java)
+* [Buffer](DataStructures/Buffers/CircularBuffer.java)
+* [HashMap](DataStructures/HashMap/HashMap.java)
+* [Matrix](DataStructures/Matrix/Matrix.java)
diff --git a/README.md b/README.md
index ce2cdec5e76a..522a80e1b083 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,6 @@
-# The Algorithms - Java [](https://travis-ci.org/TheAlgorithms/Java)
+# The Algorithms - Java
+
+NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we are trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info.
### All algorithms implemented in Java (for education)
@@ -17,7 +19,7 @@ __Properties__
* Best case performance O(n)
* Average case performance O(n^2)
-###### View the algorithm in [action][bubble-toptal]
+##### View the algorithm in [action][bubble-toptal]
@@ -32,7 +34,7 @@ __Properties__
* Best case performance O(n)
* Average case performance O(n^2)
-###### View the algorithm in [action][insertion-toptal]
+##### View the algorithm in [action][insertion-toptal]
### Merge
@@ -46,7 +48,7 @@ __Properties__
* Average case performance O(n log n)
-###### View the algorithm in [action][merge-toptal]
+##### View the algorithm in [action][merge-toptal]
### Quick
![alt text][quick-image]
@@ -56,9 +58,9 @@ From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sor
__Properties__
* Worst case performance O(n^2)
* Best case performance O(n log n) or O(n) with three-way partition
-* Average case performance O(n^2)
+* Average case performance O(n log n)
-###### View the algorithm in [action][quick-toptal]
+##### View the algorithm in [action][quick-toptal]
### Selection
![alt text][selection-image]
@@ -70,7 +72,7 @@ __Properties__
* Best case performance O(n^2)
* Average case performance O(n^2)
-###### View the algorithm in [action][selection-toptal]
+##### View the algorithm in [action][selection-toptal]
### Shell
![alt text][shell-image]
@@ -82,9 +84,9 @@ __Properties__
* Best case performance O(n log n)
* Average case performance depends on gap sequence
-###### View the algorithm in [action][shell-toptal]
+##### View the algorithm in [action][shell-toptal]
-### Time-Compexity Graphs
+### Time-Complexity Graphs
Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort)
@@ -117,14 +119,7 @@ __Properties__
* Average case performance O(log n)
* Worst case space complexity O(1)
-From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted.
-
-__Properties__
-* Worst case performance O(nlog2 2n)
-* Best case performance O(n log n)
-* Average case performance depends on gap sequence
-
-###### View the algorithm in [action][shell-toptal]
+##### View the algorithm in [action][shell-toptal]
[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort
@@ -175,20 +170,22 @@ and much more...| and more...
### Data Structures
Graphs|Heaps|Lists|Queues|
------|-----|-----|------|
-[BFS](Data%20Structures/Graphs/BFS.java)|[Empty Heap Exception](Data%20Structures/Heaps/EmptyHeapException.java)|[Circle Linked List](Data%20Structures/Lists/CircleLinkedList.java)|[Generic Array List Queue](Data%20Structures/Queues/GenericArrayListQueue.java)|
-[DFS](Data%20Structures/Graphs/DFS.java)|[Heap](Data%20Structures/Heaps/Heap.java)|[Doubly Linked List](Data%20Structures/Lists/DoublyLinkedList.java)|[Queues](Data%20Structures/Queues/Queues.java)|
-[Graphs](Data%20Structures/Graphs/Graphs.java)|[Heap Element](Data%20Structures/Heaps/HeapElement.java)|[Singly Linked List](Data%20Structures/Lists/SinglyLinkedList.java)|
-[Kruskals Algorithm](Data%20Structures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)|
-[Matrix Graphs](Data%20Structures/Graphs/MatrixGraphs.java)|[Min Heap](Data%20Structures/Heaps/MinHeap.java)|
-[PrimMST](Data%20Structures/Graphs/PrimMST.java)|
+[BFS](DataStructures/Graphs/BFS.java)|[Empty Heap Exception](DataStructures/Heaps/EmptyHeapException.java)|[Circle Linked List](DataStructures/Lists/CircleLinkedList.java)|[Generic Array List Queue](DataStructures/Queues/GenericArrayListQueue.java)|
+[DFS](DataStructures/Graphs/DFS.java)|[Heap](DataStructures/Heaps/Heap.java)|[Doubly Linked List](DataStructures/Lists/DoublyLinkedList.java)|[Queues](DataStructures/Queues/Queues.java)|
+[Graphs](DataStructures/Graphs/Graphs.java)|[Heap Element](DataStructures/Heaps/HeapElement.java)|[Singly Linked List](DataStructures/Lists/SinglyLinkedList.java)|
+[Kruskals Algorithm](DataStructures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)|
+[CursorLinkedList](DataStructures/Lists/CursorLinkedList.java)|
+[Matrix Graphs](DataStructures/Graphs/MatrixGraphs.java)|[Min Heap](DataStructures/Heaps/MinHeap.java)|
+[PrimMST](DataStructures/Graphs/PrimMST.java)|
Stacks|Trees|
------|-----|
-[Node Stack](Data%20Structures/Stacks/NodeStack.java)|[AVL Tree](Data%20Structures/Trees/AVLTree.java)|
-[Stack of Linked List](Data%20Structures/Stacks/StackOfLinkedList.java)|[Binary Tree](Data%20Structures/Trees/BinaryTree.java)|
-[Stacks](Data%20Structures/Stacks/Stacks.java)|And much more...|
-
-* [Bags](Data%20Structures/Bags/Bag.java)
-* [Buffer](Data%20Structures/Buffers/CircularBuffer.java)
-* [HashMap](Data%20Structures/HashMap/HashMap.java)
-* [Matrix](Data%20Structures/Matrix/Matrix.java)
+[Node Stack](DataStructures/Stacks/NodeStack.java)|[AVL Tree](DataStructures/Trees/AVLTree.java)|
+[Stack of Linked List](DataStructures/Stacks/StackOfLinkedList.java)|[Binary Tree](DataStructures/Trees/BinaryTree.java)|
+[Array Stack](DataStructures/Stacks/StackArray.java)|And much more...|
+[ArrayList Stack](DataStructures/Stacks/StackArrayList.java)||
+
+* [Bags](DataStructures/Bags/Bag.java)
+* [Buffer](DataStructures/Buffers/CircularBuffer.java)
+* [HashMap](DataStructures/HashMap/Hashing/HashMap.java)
+* [Matrix](DataStructures/Matrix/Matrix.java)
diff --git a/Searches/src/search/BinarySearch.java b/Searches/BinarySearch.java
similarity index 78%
rename from Searches/src/search/BinarySearch.java
rename to Searches/BinarySearch.java
index c560ca1a1220..6877a55f1d95 100644
--- a/Searches/src/search/BinarySearch.java
+++ b/Searches/BinarySearch.java
@@ -1,8 +1,9 @@
-package search;
+package Searches;
import java.util.Arrays;
import java.util.Random;
-import java.util.stream.Stream;
+import java.util.concurrent.ThreadLocalRandom
+import java.util.stream.IntStream;
import static java.lang.String.format;
@@ -70,23 +71,24 @@ private > int search(T array[], T key, int left, int rig
// Driver Program
public static void main(String[] args) {
-
- //just generate data
- Random r = new Random();
+ // Just generate data
+ Random r = ThreadLocalRandom.current();
+
int size = 100;
int maxElement = 100000;
- Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new);
-
+
+ int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray();
- //the element that should be found
- Integer shouldBeFound = integers[r.nextInt(size - 1)];
+ // The element that should be found
+ int shouldBeFound = integers[r.nextInt(size - 1)];
BinarySearch search = new BinarySearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
- , shouldBeFound, integers[atIndex], atIndex, size));
-
+ System.out.println(format(
+ "Should be found: %d. Found %d at index %d. An array length %d",
+ shouldBeFound, integers[atIndex], atIndex, size
+ ));
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
diff --git a/Searches/src/search/InterpolationSearch.java b/Searches/InterpolationSearch.java
similarity index 99%
rename from Searches/src/search/InterpolationSearch.java
rename to Searches/InterpolationSearch.java
index 06313d13ce9c..b2395797c207 100644
--- a/Searches/src/search/InterpolationSearch.java
+++ b/Searches/InterpolationSearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Arrays;
import java.util.Random;
diff --git a/Searches/src/search/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java
similarity index 99%
rename from Searches/src/search/IterativeBinarySearch.java
rename to Searches/IterativeBinarySearch.java
index 17bfe3950e94..c6f8e7f1a8d9 100644
--- a/Searches/src/search/IterativeBinarySearch.java
+++ b/Searches/IterativeBinarySearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Arrays;
import java.util.Random;
diff --git a/Searches/src/search/IterativeTernarySearch.java b/Searches/IterativeTernarySearch.java
similarity index 99%
rename from Searches/src/search/IterativeTernarySearch.java
rename to Searches/IterativeTernarySearch.java
index c3538e69f00a..598b3b3eb366 100644
--- a/Searches/src/search/IterativeTernarySearch.java
+++ b/Searches/IterativeTernarySearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Arrays;
import java.util.Random;
diff --git a/Searches/src/search/LinearSearch.java b/Searches/LinearSearch.java
similarity index 98%
rename from Searches/src/search/LinearSearch.java
rename to Searches/LinearSearch.java
index 6e96da0f43bb..7664d7debb99 100644
--- a/Searches/src/search/LinearSearch.java
+++ b/Searches/LinearSearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Random;
import java.util.stream.Stream;
diff --git a/Searches/src/search/SaddlebackSearch.java b/Searches/SaddlebackSearch.java
similarity index 99%
rename from Searches/src/search/SaddlebackSearch.java
rename to Searches/SaddlebackSearch.java
index 68779db8f79f..ed9c9108c480 100644
--- a/Searches/src/search/SaddlebackSearch.java
+++ b/Searches/SaddlebackSearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Scanner;
diff --git a/Searches/src/search/SearchAlgorithm.java b/Searches/SearchAlgorithm.java
similarity index 96%
rename from Searches/src/search/SearchAlgorithm.java
rename to Searches/SearchAlgorithm.java
index ca3bf59ba552..d1a93fb7eacc 100644
--- a/Searches/src/search/SearchAlgorithm.java
+++ b/Searches/SearchAlgorithm.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
/**
* The common interface of most searching algorithms
diff --git a/Searches/src/search/TernarySearch.java b/Searches/TernarySearch.java
similarity index 99%
rename from Searches/src/search/TernarySearch.java
rename to Searches/TernarySearch.java
index 7e60edf3aad7..cefd374098cc 100644
--- a/Searches/src/search/TernarySearch.java
+++ b/Searches/TernarySearch.java
@@ -1,4 +1,4 @@
-package search;
+package Searches;
import java.util.Arrays;
diff --git a/SkylineProblem/SkylineProblem.java b/SkylineProblem/SkylineProblem.java
deleted file mode 100644
index a0b70631a527..000000000000
--- a/SkylineProblem/SkylineProblem.java
+++ /dev/null
@@ -1,131 +0,0 @@
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Scanner;
-
-public class SkylineProblem {
- Building[] building;
- int count;
-
- public void run() {
- Scanner sc = new Scanner(System.in);
-
- int num = sc.nextInt();
- this.building = new Building[num];
-
- for(int i = 0; i < num; i++) {
- String input = sc.next();
- String[] data = input.split(",");
- this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
- }
- this.print(this.findSkyline(0, num - 1));
-
- sc.close();
- }
-
- public void add(int left, int height, int right) {
- building[count++] = new Building(left, height, right);
- }
-
- public void print(ArrayList skyline) {
- Iterator it = skyline.iterator();
-
- while(it.hasNext()) {
- Skyline temp = it.next();
- System.out.print(temp.coordinates + "," + temp.height);
- if(it.hasNext()) {
- System.out.print(",");
- }
- }
-
- }
-
- public ArrayList findSkyline(int start, int end) {
- if(start == end) {
- ArrayList list = new ArrayList<>();
- list.add(new Skyline(building[start].left, building[start].height));
- list.add(new Skyline(building[end].right, 0));
-
- return list;
- }
-
- int mid = (start + end) / 2;
-
- ArrayList sky1 = this.findSkyline(start, mid);
- ArrayList sky2 = this.findSkyline(mid + 1, end);
-
- return this.mergeSkyline(sky1, sky2);
- }
-
- public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) {
- int currentH1 = 0, currentH2 = 0;
- ArrayList skyline = new ArrayList<>();
- int maxH = 0;
-
- while(!sky1.isEmpty() && !sky2.isEmpty()) {
- if(sky1.get(0).coordinates < sky2.get(0).coordinates) {
- int currentX = sky1.get(0).coordinates;
- currentH1 = sky1.get(0).height;
-
- if(currentH1 < currentH2) {
- sky1.remove(0);
- if(maxH != currentH2) skyline.add(new Skyline(currentX, currentH2));
- } else {
- maxH = currentH1;
- sky1.remove(0);
- skyline.add(new Skyline(currentX, currentH1));
- }
- } else {
- int currentX = sky2.get(0).coordinates;
- currentH2 = sky2.get(0).height;
-
- if(currentH2 < currentH1) {
- sky2.remove(0);
- if(maxH != currentH1) skyline.add(new Skyline(currentX, currentH1));
- } else {
- maxH = currentH2;
- sky2.remove(0);
- skyline.add(new Skyline(currentX, currentH2));
- }
- }
- }
-
- while(!sky1.isEmpty()) {
- skyline.add(sky1.get(0));
- sky1.remove(0);
- }
-
- while(!sky2.isEmpty()) {
- skyline.add(sky2.get(0));
- sky2.remove(0);
- }
-
- return skyline;
- }
-
- public class Skyline {
- public int coordinates;
- public int height;
-
- public Skyline(int coordinates, int height) {
- this.coordinates = coordinates;
- this.height = height;
- }
- }
-
- public class Building {
- public int left;
- public int height;
- public int right;
-
- public Building(int left, int height, int right) {
- this.left = left;
- this.height = height;
- this.right = right;
- }
- }
-
- public static void main(String[] args) {
- SkylineProblem skylineProblem = new SkylineProblem();
- skylineProblem.run();
- }
-}
diff --git a/Sorts/src/sort/BinaryTreeSort.java b/Sorts/BinaryTreeSort.java
similarity index 95%
rename from Sorts/src/sort/BinaryTreeSort.java
rename to Sorts/BinaryTreeSort.java
index 59d58ab61987..26942754f910 100644
--- a/Sorts/src/sort/BinaryTreeSort.java
+++ b/Sorts/BinaryTreeSort.java
@@ -1,7 +1,7 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.less;
-import static sort.SortUtils.print;
+import static Sorts.SortUtils.less;
+import static Sorts.SortUtils.print;
/**
*
diff --git a/Sorts/src/sort/BogoSort.java b/Sorts/BogoSort.java
similarity index 82%
rename from Sorts/src/sort/BogoSort.java
rename to Sorts/BogoSort.java
index 1079ca21c27a..f3f923d32edf 100644
--- a/Sorts/src/sort/BogoSort.java
+++ b/Sorts/BogoSort.java
@@ -1,9 +1,7 @@
-package sort;
+package Sorts;
import java.util.Random;
-import static sort.SortUtils.*;
-
/**
*
@@ -19,7 +17,7 @@ public class BogoSort implements SortAlgorithm {
private static > boolean isSorted(T array[]){
for(int i = 0; i void nextPermutation(T array[]){
for (int i = 0; i < array.length; i++) {
int randomIndex = i + random.nextInt(length - i);
- swap(array, randomIndex, i);
+ SortUtils.swap(array, randomIndex, i);
}
}
@@ -49,11 +47,11 @@ public static void main(String[] args) {
BogoSort bogoSort = new BogoSort();
// print a sorted array
- print(bogoSort.sort(integers));
+ SortUtils.print(bogoSort.sort(integers));
// String Input
String[] strings = {"c", "a", "e", "b","d"};
- print(bogoSort.sort(strings));
+ SortUtils.print(bogoSort.sort(strings));
}
}
diff --git a/Sorts/src/sort/BubbleSort.java b/Sorts/BubbleSort.java
similarity index 96%
rename from Sorts/src/sort/BubbleSort.java
rename to Sorts/BubbleSort.java
index 1173245fcabf..274979a456b1 100644
--- a/Sorts/src/sort/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
*
diff --git a/Sorts/src/sort/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java
similarity index 79%
rename from Sorts/src/sort/CocktailShakerSort.java
rename to Sorts/CocktailShakerSort.java
index 7982b8fcfcae..5f4b89942645 100644
--- a/Sorts/src/sort/CocktailShakerSort.java
+++ b/Sorts/CocktailShakerSort.java
@@ -1,6 +1,4 @@
-package sort;
-
-import static sort.SortUtils.*;
+package Sorts;
/**
*
@@ -29,8 +27,8 @@ public > T[] sort(T[] array) {
// front
swappedRight = 0;
for (int i = left; i < right; i++) {
- if (less(array[i + 1], array[i])) {
- swap(array, i, i + 1);
+ if (SortUtils.less(array[i + 1], array[i])) {
+ SortUtils.swap(array, i, i + 1);
swappedRight = i;
}
}
@@ -38,8 +36,8 @@ public > T[] sort(T[] array) {
right = swappedRight;
swappedLeft = length - 1;
for (int j = right; j > left; j--) {
- if (less(array[j], array[j - 1])) {
- swap(array, j - 1, j);
+ if (SortUtils.less(array[j], array[j - 1])) {
+ SortUtils.swap(array, j - 1, j);
swappedLeft = j;
}
}
@@ -56,11 +54,11 @@ public static void main(String[] args) {
CocktailShakerSort shakerSort = new CocktailShakerSort();
// Output => 1 4 6 9 12 23 54 78 231
- print(shakerSort.sort(integers));
+ SortUtils.print(shakerSort.sort(integers));
// String Input
String[] strings = { "c", "a", "e", "b", "d" };
- print(shakerSort.sort(strings));
+ SortUtils.print(shakerSort.sort(strings));
}
diff --git a/Sorts/src/sort/CombSort.java b/Sorts/CombSort.java
similarity index 97%
rename from Sorts/src/sort/CombSort.java
rename to Sorts/CombSort.java
index 492605ca56e7..83e24edaec9c 100644
--- a/Sorts/src/sort/CombSort.java
+++ b/Sorts/CombSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
diff --git a/Sorts/src/sort/CountingSort.java b/Sorts/CountingSort.java
similarity index 98%
rename from Sorts/src/sort/CountingSort.java
rename to Sorts/CountingSort.java
index 39442a00fbb8..7243a27a9dd4 100644
--- a/Sorts/src/sort/CountingSort.java
+++ b/Sorts/CountingSort.java
@@ -1,4 +1,4 @@
-package sort;
+package Sorts;
import java.util.*;
import java.util.stream.IntStream;
@@ -6,7 +6,7 @@
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
-import static sort.SortUtils.print;
+import static Sorts.SortUtils.print;
/**
*
diff --git a/Sorts/src/sort/CycleSort.java b/Sorts/CycleSort.java
similarity index 95%
rename from Sorts/src/sort/CycleSort.java
rename to Sorts/CycleSort.java
index ea4f05535c7a..eba541a061e8 100644
--- a/Sorts/src/sort/CycleSort.java
+++ b/Sorts/CycleSort.java
@@ -1,7 +1,7 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.less;
-import static sort.SortUtils.print;
+import static Sorts.SortUtils.less;
+import static Sorts.SortUtils.print;
/**
* @author Podshivalov Nikita (https://github.com/nikitap492)
diff --git a/Sorts/src/sort/GnomeSort.java b/Sorts/GnomeSort.java
similarity index 95%
rename from Sorts/src/sort/GnomeSort.java
rename to Sorts/GnomeSort.java
index 14af67c65bb6..ef5dca141436 100644
--- a/Sorts/src/sort/GnomeSort.java
+++ b/Sorts/GnomeSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
* Implementation of gnome sort
diff --git a/Sorts/src/sort/HeapSort.java b/Sorts/HeapSort.java
similarity index 98%
rename from Sorts/src/sort/HeapSort.java
rename to Sorts/HeapSort.java
index 6fab3747fd2f..9be2c2e70345 100644
--- a/Sorts/src/sort/HeapSort.java
+++ b/Sorts/HeapSort.java
@@ -1,10 +1,10 @@
-package sort;
+package Sorts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
* Heap Sort Algorithm
diff --git a/Sorts/src/sort/InsertionSort.java b/Sorts/InsertionSort.java
similarity index 93%
rename from Sorts/src/sort/InsertionSort.java
rename to Sorts/InsertionSort.java
index 593614304c5b..f29c3537ce0d 100644
--- a/Sorts/src/sort/InsertionSort.java
+++ b/Sorts/InsertionSort.java
@@ -1,7 +1,7 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.less;
-import static sort.SortUtils.print;
+import static Sorts.SortUtils.less;
+import static Sorts.SortUtils.print;
/**
*
diff --git a/Sorts/src/sort/MergeSort.java b/Sorts/MergeSort.java
similarity index 90%
rename from Sorts/src/sort/MergeSort.java
rename to Sorts/MergeSort.java
index 2c7a141bdc32..e14334b163bf 100644
--- a/Sorts/src/sort/MergeSort.java
+++ b/Sorts/MergeSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.print;
+import static Sorts.SortUtils.print;
/**
* This method implements the Generic Merge Sort
@@ -70,26 +70,19 @@ private static > void merge(T[] arr, T[] temp, int left,
while (i <= mid && j <= right) {
if (temp[i].compareTo(temp[j]) <= 0) {
- arr[k] = temp[i];
- i++;
+ arr[k++] = temp[i++];
}
else {
- arr[k] = temp[j];
- j++;
+ arr[k++] = temp[j++];
}
- k++;
}
while (i <= mid) {
- arr[k] = temp[i];
- i++;
- k++;
+ arr[k++] = temp[i++];
}
while (j <= right) {
- arr[k] = temp[j];
- j++;
- k++;
+ arr[k++] = temp[j++];
}
}
diff --git a/Sorts/src/sort/PancakeSort.java b/Sorts/PancakeSort.java
similarity index 95%
rename from Sorts/src/sort/PancakeSort.java
rename to Sorts/PancakeSort.java
index 902db4b39cb8..395b75f93a75 100644
--- a/Sorts/src/sort/PancakeSort.java
+++ b/Sorts/PancakeSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
* Implementation of gnome sort
diff --git a/Sorts/src/sort/QuickSort.java b/Sorts/QuickSort.java
similarity index 97%
rename from Sorts/src/sort/QuickSort.java
rename to Sorts/QuickSort.java
index 4159fc829881..36b042c13821 100644
--- a/Sorts/src/sort/QuickSort.java
+++ b/Sorts/QuickSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
*
diff --git a/Sorts/src/sort/RadixSort.java b/Sorts/RadixSort.java
similarity index 98%
rename from Sorts/src/sort/RadixSort.java
rename to Sorts/RadixSort.java
index 0d1e6966101a..9fd1ab7b8356 100644
--- a/Sorts/src/sort/RadixSort.java
+++ b/Sorts/RadixSort.java
@@ -1,4 +1,4 @@
-package sort;
+package Sorts;
import java.util.Arrays;
diff --git a/Sorts/src/sort/SelectionSort.java b/Sorts/SelectionSort.java
similarity index 87%
rename from Sorts/src/sort/SelectionSort.java
rename to Sorts/SelectionSort.java
index 960215a686d2..7ab599f943f2 100644
--- a/Sorts/src/sort/SelectionSort.java
+++ b/Sorts/SelectionSort.java
@@ -1,6 +1,4 @@
-package sort;
-
-import static sort.SortUtils.*;
+package Sorts;
/**
*
@@ -27,14 +25,14 @@ public > T[] sort(T[] arr) {
int min = i;
for (int j = i +1 ; j < n; j++) {
- if (less(arr[j], arr[min])) {
+ if (SortUtils.less(arr[j], arr[min])) {
min = j;
}
}
// Swapping if index of min is changed
if (min != i) {
- swap(arr, i , min);
+ SortUtils.swap(arr, i , min);
}
}
@@ -51,13 +49,13 @@ public static void main(String[] args) {
Integer[] sorted = selectionSort.sort(arr);
// Output => 1 4 6 9 12 23 54 78 231
- print(sorted);
+ SortUtils.print(sorted);
// String Input
String[] strings = {"c", "a", "e", "b","d"};
String[] sortedStrings = selectionSort.sort(strings);
//Output => a b c d e
- print(sortedStrings);
+ SortUtils.print(sortedStrings);
}
}
diff --git a/Sorts/src/sort/ShellSort.java b/Sorts/ShellSort.java
similarity index 94%
rename from Sorts/src/sort/ShellSort.java
rename to Sorts/ShellSort.java
index bafd19b145d7..31c2c6077897 100644
--- a/Sorts/src/sort/ShellSort.java
+++ b/Sorts/ShellSort.java
@@ -1,6 +1,6 @@
-package sort;
+package Sorts;
-import static sort.SortUtils.*;
+import static Sorts.SortUtils.*;
/**
diff --git a/Sorts/src/sort/SortAlgorithm.java b/Sorts/SortAlgorithm.java
similarity index 98%
rename from Sorts/src/sort/SortAlgorithm.java
rename to Sorts/SortAlgorithm.java
index 46b1f58e128f..e6004156559b 100644
--- a/Sorts/src/sort/SortAlgorithm.java
+++ b/Sorts/SortAlgorithm.java
@@ -1,4 +1,4 @@
-package sort;
+package Sorts;
import java.util.Arrays;
import java.util.List;
diff --git a/Sorts/src/sort/SortUtils.java b/Sorts/SortUtils.java
similarity index 99%
rename from Sorts/src/sort/SortUtils.java
rename to Sorts/SortUtils.java
index 8766e9d0e4d7..b3392352becd 100644
--- a/Sorts/src/sort/SortUtils.java
+++ b/Sorts/SortUtils.java
@@ -1,4 +1,4 @@
-package sort;
+package Sorts;
import java.util.Arrays;
import java.util.List;
diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java
new file mode 100644
index 000000000000..93a5d164dd88
--- /dev/null
+++ b/divideconquer/ClosestPair.java
@@ -0,0 +1,348 @@
+package divideconquer;
+
+/**
+
+* For a set of points in a coordinates system (10000 maximum),
+* ClosestPair class calculates the two closest points.
+
+* @author: anonymous
+* @author: Marisa Afuera
+*/
+
+ public final class ClosestPair {
+
+
+ /** Number of points */
+ int numberPoints = 0;
+ /** Input data, maximum 10000. */
+ private Location[] array;
+ /** Minimum point coordinate. */
+ Location point1 = null;
+ /** Minimum point coordinate. */
+ Location point2 = null;
+ /** Minimum point length. */
+ private static double minNum = Double.MAX_VALUE;
+ /** secondCount */
+ private static int secondCount = 0;
+
+ /**
+ * Constructor.
+ */
+ ClosestPair(int points) {
+ numberPoints = points;
+ array = new Location[numberPoints];
+ }
+
+ /**
+ Location class is an auxiliary type to keep points coordinates.
+ */
+
+ public static class Location {
+
+ double x = 0;
+ double y = 0;
+
+ /**
+ * @param xpar (IN Parameter) x coordinate
+ * @param ypar (IN Parameter) y coordinate
+ */
+
+ Location(final double xpar, final double ypar) { //Save x, y coordinates
+ this.x = xpar;
+ this.y = ypar;
+ }
+
+ }
+
+ public Location[] createLocation(int numberValues) {
+ return new Location[numberValues];
+
+ }
+
+ public Location buildLocation(double x, double y){
+ return new Location(x,y);
+ }
+
+
+ /** xPartition function: arrange x-axis.
+ * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index
+ */
+
+ public int xPartition(
+ final Location[] a, final int first, final int last) {
+
+ Location pivot = a[last]; // pivot
+ int pIndex = last;
+ int i = first - 1;
+ Location temp; // Temporarily store value for position transformation
+ for (int j = first; j <= last - 1; j++) {
+ if (a[j].x <= pivot.x) { // Less than or less than pivot
+ i++;
+ temp = a[i]; // array[i] <-> array[j]
+ a[i] = a[j];
+ a[j] = temp;
+ }
+ }
+ i++;
+ temp = a[i]; // array[pivot] <-> array[i]
+ a[i] = a[pIndex];
+ a[pIndex] = temp;
+ return i; // pivot index
+ }
+
+ /** yPartition function: arrange y-axis.
+ * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index
+ */
+
+ public int yPartition(
+ final Location[] a, final int first, final int last) {
+
+ Location pivot = a[last]; // pivot
+ int pIndex = last;
+ int i = first - 1;
+ Location temp; // Temporarily store value for position transformation
+ for (int j = first; j <= last - 1; j++) {
+ if (a[j].y <= pivot.y) { // Less than or less than pivot
+ i++;
+ temp = a[i]; // array[i] <-> array[j]
+ a[i] = a[j];
+ a[j] = temp;
+ }
+ }
+ i++;
+ temp = a[i]; // array[pivot] <-> array[i]
+ a[i] = a[pIndex];
+ a[pIndex] = temp;
+ return i; // pivot index
+ }
+
+ /** xQuickSort function: //x-axis Quick Sorting.
+ * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */
+
+ public void xQuickSort(
+ final Location[] a, final int first, final int last) {
+
+ if (first < last) {
+ int q = xPartition(a, first, last); // pivot
+ xQuickSort(a, first, q - 1); // Left
+ xQuickSort(a, q + 1, last); // Right
+ }
+ }
+
+ /** yQuickSort function: //y-axis Quick Sorting.
+ * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */
+
+ public void yQuickSort(
+ final Location[] a, final int first, final int last) {
+
+ if (first < last) {
+ int q = yPartition(a, first, last); // pivot
+ yQuickSort(a, first, q - 1); // Left
+ yQuickSort(a, q + 1, last); // Right
+ }
+ }
+
+ /** closestPair function: find closest pair.
+ * @param a (IN Parameter) array stored before divide
+ * @param indexNum (IN Parameter) number coordinates divideArray
+ * @return minimum distance
+ */
+
+ public double closestPair(final Location[] a, final int indexNum) {
+
+ Location[] divideArray = new Location[indexNum];
+ System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array
+ int totalNum = indexNum; // number of coordinates in the divideArray
+ int divideX = indexNum / 2; // Intermediate value for divide
+ Location[] leftArray = new Location[divideX]; //divide - left array
+ //divide-right array
+ Location[] rightArray = new Location[totalNum - divideX];
+ if (indexNum <= 3) { // If the number of coordinates is 3 or less
+ return bruteForce(divideArray);
+ }
+ //divide-left array
+ System.arraycopy(divideArray, 0, leftArray, 0, divideX);
+ //divide-right array
+ System.arraycopy(
+ divideArray, divideX, rightArray, 0, totalNum - divideX);
+
+ double minLeftArea = 0; //Minimum length of left array
+ double minRightArea = 0; //Minimum length of right array
+ double minValue = 0; //Minimum lengt
+
+ minLeftArea = closestPair(leftArray, divideX); // recursive closestPair
+ minRightArea = closestPair(rightArray, totalNum - divideX);
+ // window size (= minimum length)
+ minValue = Math.min(minLeftArea, minRightArea);
+
+ // Create window. Set the size for creating a window
+ // and creating a new array for the coordinates in the window
+ for (int i = 0; i < totalNum; i++) {
+ double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x);
+ if (xGap < minValue) {
+ secondCount++; // size of the array
+ } else {
+ if (divideArray[i].x > divideArray[divideX].x) {
+ break;
+ }
+ }
+ }
+ // new array for coordinates in window
+ Location[] firstWindow = new Location[secondCount];
+ int k = 0;
+ for (int i = 0; i < totalNum; i++) {
+ double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x);
+ if (xGap < minValue) { // if it's inside a window
+ firstWindow[k] = divideArray[i]; // put in an array
+ k++;
+ } else {
+ if (divideArray[i].x > divideArray[divideX].x) {
+ break;
+ }
+ }
+ }
+ yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates
+ /* Coordinates in Window */
+ double length = 0;
+ // size comparison within window
+ for (int i = 0; i < secondCount - 1; i++) {
+ for (int j = (i + 1); j < secondCount; j++) {
+ double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x);
+ double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y);
+ if (yGap < minValue) {
+ length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2));
+ // If measured distance is less than current min distance
+ if (length < minValue) {
+ // Change minimum distance to current distance
+ minValue = length;
+ // Conditional for registering final coordinate
+ if (length < minNum) {
+ minNum = length;
+ point1 = firstWindow[i];
+ point2 = firstWindow[j];
+ }
+ }
+ }
+ else {
+ break;
+ }
+ }
+ }
+ secondCount = 0;
+ return minValue;
+ }
+
+ /** bruteForce function: When the number of coordinates is less than 3.
+ * @param arrayParam (IN Parameter) array stored before divide
+ * @return
+ */
+
+ public double bruteForce(final Location[] arrayParam) {
+
+ double minValue = Double.MAX_VALUE; // minimum distance
+ double length = 0;
+ double xGap = 0; // Difference between x coordinates
+ double yGap = 0; // Difference between y coordinates
+ double result = 0;
+
+ if (arrayParam.length == 2) {
+ // Difference between x coordinates
+ xGap = (arrayParam[0].x - arrayParam[1].x);
+ // Difference between y coordinates
+ yGap = (arrayParam[0].y - arrayParam[1].y);
+ // distance between coordinates
+ length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2));
+ // Conditional statement for registering final coordinate
+ if (length < minNum) {
+ minNum = length;
+
+ }
+ point1 = arrayParam[0];
+ point2 = arrayParam[1];
+ result = length;
+ }
+ if (arrayParam.length == 3) {
+ for (int i = 0; i < arrayParam.length - 1; i++) {
+ for (int j = (i + 1); j < arrayParam.length; j++) {
+ // Difference between x coordinates
+ xGap = (arrayParam[i].x - arrayParam[j].x);
+ // Difference between y coordinates
+ yGap = (arrayParam[i].y - arrayParam[j].y);
+ // distance between coordinates
+ length =
+ Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2));
+ // If measured distance is less than current min distance
+ if (length < minValue) {
+ // Change minimum distance to current distance
+ minValue = length;
+ if (length < minNum) {
+ // Registering final coordinate
+ minNum = length;
+ point1 = arrayParam[i];
+ point2 = arrayParam[j];
+ }
+ }
+ }
+ }
+ result = minValue;
+
+ }
+ return result; // If only one point returns 0.
+ }
+
+ /** main function: execute class.
+ * @param args (IN Parameter)
+ * @throws IOException If an input or output
+ * exception occurred
+ */
+
+ public static void main(final String[] args) {
+
+ //Input data consists of one x-coordinate and one y-coordinate
+
+ ClosestPair cp = new ClosestPair(12);
+ cp.array[0]=cp.buildLocation(2,3);
+ cp.array[1]=cp.buildLocation(2,16);
+ cp.array[2]=cp.buildLocation(3,9);
+ cp.array[3]=cp.buildLocation(6,3);
+ cp.array[4]=cp.buildLocation(7,7);
+ cp.array[5]=cp.buildLocation(19,4);
+ cp.array[6]=cp.buildLocation(10,11);
+ cp.array[7]=cp.buildLocation(15,2);
+ cp.array[8]=cp.buildLocation(15,19);
+ cp.array[9]=cp.buildLocation(16,11);
+ cp.array[10]=cp.buildLocation(17,13);
+ cp.array[11]=cp.buildLocation(9,12);
+
+ System.out.println("Input data");
+ System.out.println("Number of points: "+ cp.array.length);
+ for (int i=0;i
+ * Space complexity: O(n)
+ * Time complexity: O(nlogn), because it is a divide and conquer algorithm
+ */
+public class SkylineAlgorithm {
+ private ArrayList points;
+
+ /**
+ * Main constructor of the application.
+ * ArrayList points gets created, which represents the sum of all edges.
+ */
+ public SkylineAlgorithm() {
+ points = new ArrayList<>();
+ }
+
+
+ /**
+ * @return points, the ArrayList that includes all points.
+ */
+ public ArrayList getPoints() {
+ return points;
+ }
+
+
+ /**
+ * The main divide and conquer, and also recursive algorithm.
+ * It gets an ArrayList full of points as an argument.
+ * If the size of that ArrayList is 1 or 2,
+ * the ArrayList is returned as it is, or with one less point
+ * (if the initial size is 2 and one of it's points, is dominated by the other one).
+ * On the other hand, if the ArrayList's size is bigger than 2,
+ * the function is called again, twice,
+ * with arguments the corresponding half of the initial ArrayList each time.
+ * Once the flashback has ended, the function produceFinalSkyLine gets called,
+ * in order to produce the final skyline, and return it.
+ *
+ * @param list, the initial list of points
+ * @return leftSkyLine, the combination of first half's and second half's skyline
+ * @see Point
+ * @see produceFinalSkyLine
+ */
+ public ArrayList produceSubSkyLines(ArrayList list) {
+
+ // part where function exits flashback
+ int size = list.size();
+ if (size == 1) {
+ return list;
+ } else if (size == 2) {
+ if (list.get(0).dominates(list.get(1))) {
+ list.remove(1);
+ } else {
+ if (list.get(1).dominates(list.get(0))) {
+ list.remove(0);
+ }
+ }
+ return list;
+ }
+
+ // recursive part of the function
+ ArrayList leftHalf = new ArrayList<>();
+ ArrayList rightHalf = new ArrayList<>();
+ for (int i = 0; i < list.size(); i++) {
+ if (i < list.size() / 2) {
+ leftHalf.add(list.get(i));
+ } else {
+ rightHalf.add(list.get(i));
+ }
+ }
+ ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf);
+ ArrayList rightSubSkyLine= produceSubSkyLines(rightHalf);
+
+ // skyline is produced
+ return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine);
+ }
+
+
+ /**
+ * The first half's skyline gets cleared
+ * from some points that are not part of the final skyline
+ * (Points with same x-value and different y=values. The point with the smallest y-value is kept).
+ * Then, the minimum y-value of the points of first half's skyline is found.
+ * That helps us to clear the second half's skyline, because, the points
+ * of second half's skyline that have greater y-value of the minimum y-value that we found before,
+ * are dominated, so they are not part of the final skyline.
+ * Finally, the "cleaned" first half's and second half's skylines, are combined,
+ * producing the final skyline, which is returned.
+ *
+ * @param left the skyline of the left part of points
+ * @param right the skyline of the right part of points
+ * @return left the final skyline
+ */
+ public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) {
+
+ // dominated points of ArrayList left are removed
+ for (int i = 0; i < left.size() - 1; i++) {
+ if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) {
+ left.remove(i);
+ i--;
+ }
+ }
+
+ // minimum y-value is found
+ int min = left.get(0).y;
+ for (int i = 1; i < left.size(); i++) {
+ if (min > left.get(i).y) {
+ min = left.get(i).y;
+ if (min == 1) {
+ i = left.size();
+ }
+ }
+ }
+
+ // dominated points of ArrayList right are removed
+ for (int i = 0; i < right.size(); i++) {
+ if (right.get(i).y >= min) {
+ right.remove(i);
+ i--;
+ }
+ }
+
+ // final skyline found and returned
+ left.addAll(right);
+ return left;
+ }
+
+
+ public static class Point {
+ private int x;
+ private int y;
+
+ /**
+ * The main constructor of Point Class, used to represent the 2 Dimension points.
+ *
+ * @param x the point's x-value.
+ * @param y the point's y-value.
+ */
+ public Point(int x, int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ /**
+ * @return x, the x-value
+ */
+ public int getX() {
+ return x;
+ }
+
+ /**
+ * @return y, the y-value
+ */
+ public int getY() {
+ return y;
+ }
+
+ /**
+ * Based on the skyline theory,
+ * it checks if the point that calls the function dominates the argument point.
+ *
+ * @param p1 the point that is compared
+ * @return true if the point wich calls the function dominates p1
+ * false otherwise.
+ */
+ public boolean dominates(Point p1) {
+ // checks if p1 is dominated
+ return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y);
+ }
+ }
+
+ /**
+ * It is used to compare the 2 Dimension points,
+ * based on their x-values, in order get sorted later.
+ */
+ class XComparator implements Comparator {
+ @Override
+ public int compare(Point a, Point b) {
+ return Integer.compare(a.x, b.x);
+ }
+ }
+}
diff --git a/myfile.txt b/myfile.txt
deleted file mode 100644
index d1b1c0a7ad80..000000000000
--- a/myfile.txt
+++ /dev/null
@@ -1 +0,0 @@
-~
\ No newline at end of file