Heaps are tree-like data structures that allow storing elements in a specific
- * way. Each node corresponds to an element and has one parent node (except for the root) and
- * at most two children nodes. Every element contains a key, and those keys
- * indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall
- * be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a
- * max-heap).
- *
All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in
- * O(log n) time.
- * @author Nicolas Renard
- *
- *
- */
-public interface Heap {
-
- /**
- *
- * @return the top element in the heap, the one with lowest key for min-heap or with
- * the highest key for max-heap
- * @throws Exception if heap is empty
- */
- public abstract HeapElement getElement() throws EmptyHeapException;
- /**
- * Inserts an element in the heap. Adds it to then end and toggle it until it finds its
- * right position.
- *
- * @param element an instance of the HeapElement class.
- */
- public abstract void insertElement(HeapElement element);
-
- /**
- * Delete an element in the heap.
- *
- * @param elementIndex int containing the position in the heap of the element to be deleted.
- */
- public abstract void deleteElement(int elementIndex);
-
-}
diff --git a/Data Structures/Heaps/HeapElement.java b/Data Structures/Heaps/HeapElement.java
deleted file mode 100644
index e0cc93ccbfe0..000000000000
--- a/Data Structures/Heaps/HeapElement.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- *
- */
-package heaps;
-
-import java.lang.Double;
-import java.lang.Object;
-
-/**
- * Class for heap elements.
- *
A heap element contains two attributes: a key which will be used to build the tree (int
- * or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit
- * to carry any information he/she likes. Be aware that the use of a mutable object might
- * jeopardize the integrity of this information.
- * @author Nicolas Renard
- *
- */
-public class HeapElement {
- private final double key;
- private final Object additionalInfo;
-
- // Constructors
-
- /**
- *
- * @param key : a number of primitive type 'double'
- * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
- * additional information of use for the user
- */
- public HeapElement(double key, Object info) {
- this.key = key;
- this.additionalInfo = info;
- }
-
- /**
- *
- * @param key : a number of primitive type 'int'
- * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
- * additional information of use for the user
- */
- public HeapElement(int key, Object info) {
- this.key = key;
- this.additionalInfo = info;
- }
-
- /**
- *
- * @param key : a number of object type 'Integer'
- * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
- * additional information of use for the user
- */
- public HeapElement(Integer key, Object info) {
- this.key = key;
- this.additionalInfo = info;
- }
-
- /**
- *
- * @param key : a number of object type 'Double'
- * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
- * additional information of use for the user
- */
- public HeapElement(Double key, Object info) {
- this.key = key;
- this.additionalInfo = info;
- }
-
- /**
- *
- * @param key : a number of primitive type 'double'
- */
- public HeapElement(double key) {
- this.key = key;
- this.additionalInfo = null;
- }
-
- /**
- *
- * @param key : a number of primitive type 'int'
- */
- public HeapElement(int key) {
- this.key = key;
- this.additionalInfo = null;
- }
-
- /**
- *
- * @param key : a number of object type 'Integer'
- */
- public HeapElement(Integer key) {
- this.key = key;
- this.additionalInfo = null;
- }
-
- /**
- *
- * @param key : a number of object type 'Double'
- */
- public HeapElement(Double key) {
- this.key = key;
- this.additionalInfo = null;
- }
-
- // Getters
- /**
- * @return the object containing the additional info provided by the user.
- */
- public Object getInfo() {
- return additionalInfo;
- }
- /**
- * @return the key value of the element
- */
- public double getKey() {
- return key;
- }
-
- // Overridden object methods
-
- public String toString() {
- return "Key: " + key + " - " +additionalInfo.toString();
- }
- /**
- *
- * @param otherHeapElement
- * @return true if the keys on both elements are identical and the additional info objects
- * are identical.
- */
- public boolean equals(HeapElement otherHeapElement) {
- return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
- }
-}
diff --git a/Data Structures/Heaps/MaxHeap.java b/Data Structures/Heaps/MaxHeap.java
deleted file mode 100644
index 5f774e3534a8..000000000000
--- a/Data Structures/Heaps/MaxHeap.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package heaps;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
- * to its children's.
- * @author Nicolas Renard
- *
- */
-public class MaxHeap implements Heap {
-
- private final List maxHeap;
-
- public MaxHeap(List listElements) throws Exception {
- maxHeap = new ArrayList();
- for (HeapElement heapElement : listElements) {
- if (heapElement != null) insertElement(heapElement);
- else System.out.println("Null element. Not added to heap");
- }
- if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
- }
-
- // Get the element at a given index. The key for the list is equal to index value - 1
- public HeapElement getElement(int elementIndex) {
- if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
- return maxHeap.get(elementIndex - 1);
- }
-
- // Get the key of the element at a given index
- private double getElementKey(int elementIndex) {
- return maxHeap.get(elementIndex - 1).getKey();
- }
-
- // Swaps two elements in the heap
- private void swap(int index1, int index2) {
- HeapElement temporaryElement = maxHeap.get(index1 - 1);
- maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
- maxHeap.set(index2 - 1, temporaryElement);
- }
-
- // Toggle an element up to its right place as long as its key is lower than its parent's
- private void toggleUp(int elementIndex) {
- double key = maxHeap.get(elementIndex - 1).getKey();
- while (getElementKey((int) Math.floor(elementIndex/2)) < key) {
- swap(elementIndex, (int) Math.floor(elementIndex/2));
- elementIndex = (int) Math.floor(elementIndex/2);
- }
- }
-
- // Toggle an element down to its right place as long as its key is higher
- // than any of its children's
- private void toggleDown(int elementIndex) {
- double key = maxHeap.get(elementIndex - 1).getKey();
- boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
- while ((2*elementIndex <= maxHeap.size()) && wrongOrder) {
- // Check whether it shall swap the element with its left child or its right one if any.
- if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) {
- swap(elementIndex, 2*elementIndex + 1);
- elementIndex = 2*elementIndex + 1;
- }
- else {
- swap(elementIndex, 2*elementIndex);
- elementIndex = 2*elementIndex;
- }
- wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
-
- }
- }
-
- private HeapElement extractMax() {
- HeapElement result = maxHeap.get(0);
- deleteElement(0);
- return result;
- }
-
- @Override
- public void insertElement(HeapElement element) {
- maxHeap.add(element);
- toggleUp(maxHeap.size());
-
- }
-
- @Override
- public void deleteElement(int elementIndex) {
- if (maxHeap.isEmpty())
- try {
- throw new EmptyHeapException("Attempt to delete an element from an empty heap");
- } catch (EmptyHeapException e) {
- e.printStackTrace();
- }
- if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
- // The last element in heap replaces the one to be deleted
- maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
- maxHeap.remove(maxHeap.size());
- // Shall the new element be moved up...
- if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
- // ... or down ?
- else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) ||
- ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex);
- }
-
- @Override
- public HeapElement getElement() throws EmptyHeapException {
- try {
- return extractMax();
- } catch (Exception e) {
- throw new EmptyHeapException("Heap is empty. Error retrieving element");
- }
- }
-
-}
-
-
diff --git a/Data Structures/Heaps/MinHeap.java b/Data Structures/Heaps/MinHeap.java
deleted file mode 100644
index fbf2b86ffc3e..000000000000
--- a/Data Structures/Heaps/MinHeap.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- *
- */
-package heaps;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
- * to its children's.
- * @author Nicolas Renard
- *
- */
-public class MinHeap implements Heap {
-
- private final List minHeap;
-
- public MinHeap(List listElements) throws Exception {
- minHeap = new ArrayList();
- for (HeapElement heapElement : listElements) {
- if (heapElement != null) insertElement(heapElement);
- else System.out.println("Null element. Not added to heap");
- }
- if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
- }
-
- // Get the element at a given index. The key for the list is equal to index value - 1
- public HeapElement getElement(int elementIndex) {
- if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
- return minHeap.get(elementIndex - 1);
- }
-
- // Get the key of the element at a given index
- private double getElementKey(int elementIndex) {
- return minHeap.get(elementIndex - 1).getKey();
- }
-
- // Swaps two elements in the heap
- private void swap(int index1, int index2) {
- HeapElement temporaryElement = minHeap.get(index1 - 1);
- minHeap.set(index1 - 1, minHeap.get(index2 - 1));
- minHeap.set(index2 - 1, temporaryElement);
- }
-
- // Toggle an element up to its right place as long as its key is lower than its parent's
- private void toggleUp(int elementIndex) {
- double key = minHeap.get(elementIndex - 1).getKey();
- while (getElementKey((int) Math.floor(elementIndex/2)) > key) {
- swap(elementIndex, (int) Math.floor(elementIndex/2));
- elementIndex = (int) Math.floor(elementIndex/2);
- }
- }
-
- // Toggle an element down to its right place as long as its key is higher
- // than any of its children's
- private void toggleDown(int elementIndex) {
- double key = minHeap.get(elementIndex - 1).getKey();
- boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
- while ((2*elementIndex <= minHeap.size()) && wrongOrder) {
- // Check whether it shall swap the element with its left child or its right one if any.
- if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) {
- swap(elementIndex, 2*elementIndex + 1);
- elementIndex = 2*elementIndex + 1;
- }
- else {
- swap(elementIndex, 2*elementIndex);
- elementIndex = 2*elementIndex;
- }
- wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
-
- }
- }
-
- private HeapElement extractMin() {
- HeapElement result = minHeap.get(0);
- deleteElement(0);
- return result;
- }
-
- @Override
- public void insertElement(HeapElement element) {
- minHeap.add(element);
- toggleUp(minHeap.size());
-
- }
-
- @Override
- public void deleteElement(int elementIndex) {
- if (minHeap.isEmpty())
- try {
- throw new EmptyHeapException("Attempt to delete an element from an empty heap");
- } catch (EmptyHeapException e) {
- e.printStackTrace();
- }
- if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
- // The last element in heap replaces the one to be deleted
- minHeap.set(elementIndex - 1, getElement(minHeap.size()));
- minHeap.remove(minHeap.size());
- // Shall the new element be moved up...
- if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
- // ... or down ?
- else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) ||
- ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex);
- }
-
- @Override
- public HeapElement getElement() throws EmptyHeapException {
- try {
- return extractMin();
- } catch (Exception e) {
- throw new EmptyHeapException("Heap is empty. Error retrieving element");
- }
- }
-}
diff --git a/Data Structures/Lists/CircleLinkedList.java b/Data Structures/Lists/CircleLinkedList.java
deleted file mode 100644
index 1f9a49e1ae90..000000000000
--- a/Data Structures/Lists/CircleLinkedList.java
+++ /dev/null
@@ -1,54 +0,0 @@
-public class CircleLinkedList{
- private static class Node{
- Node next;
- E value;
- private Node(E value, Node next){
- this.value = value;
- this.next = next;
- }
- }
- //For better O.O design this should be private allows for better black box design
- private int size;
- //this will point to dummy node;
- private Node head;
- //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
- public CircleLinkedList(){
- //creation of the dummy node
- head = new Node(null,head);
- size = 0;
- }
- // getter for the size... needed because size is private.
- public int getSize(){ return size;}
- // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
- public void append(E value){
- if(value == null){
- // we do not want to add null elements to the list.
- throw new NullPointerException("Cannot add null element to the list");
- }
- //head.next points to the last element;
- head.next = new Node(value,head);
- size++;}
- public E remove(int pos){
- if(pos>size || pos< 0){
- //catching errors
- throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
- }
- Node iterator = head.next;
- //we need to keep track of the element before the element we want to remove we can see why bellow.
- Node before = head;
- for(int i = 1; i<=pos; i++){
- iterator = iterator.next;
- before = before.next;
- }
- E saved = iterator.value;
- // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
- before.next = iterator.next;
- // scrubbing
- iterator.next = null;
- iterator.value = null;
- return saved;
-
- }
-
- }
-
diff --git a/Data Structures/Lists/DoublyLinkedList.java b/Data Structures/Lists/DoublyLinkedList.java
deleted file mode 100644
index c3229d9c336d..000000000000
--- a/Data Structures/Lists/DoublyLinkedList.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * This class implements a DoublyLinkedList. This is done using the classes
- * LinkedList and Link.
- *
- * A linked list is simplar to an array, it holds values. However,
- * links in a linked list do not have indees. With a linked list
- * you do not need to predetermine it's size as it grows and shrinks
- * as it is edited. This is an example of a double ended, doubly
- * linked list. Each link references the next link and the previous
- * one.
- *
- * @author Unknown
- *
- */
-
-class DoublyLinkedList{
- /** Head refers to the front of the list */
- private Link head;
- /** Tail refers to the back of the list */
- private Link tail;
-
- /**
- * Constructor
- */
- public DoublyLinkedList(){
- head = null;
- tail = null;
- }
-
- /**
- * Insert an element at the head
- *
- * @param x Element to be inserted
- */
- public void insertHead(int x){
- Link newLink = new Link(x); //Create a new link with a value attached to it
- if(isEmpty()) //Set the first element added to be the tail
- tail = newLink;
- else
- head.previous = newLink; // newLink <-- currenthead(head)
- newLink.next = head; // newLink <--> currenthead(head)
- head = newLink; // newLink(head) <--> oldhead
- }
-
- /**
- * Insert an element at the tail
- *
- * @param x Element to be inserted
- */
- public void insertTail(int x){
- Link newLink = new Link(x);
- newLink.next = null; // currentTail(tail) newlink -->
- tail.next = newLink; // currentTail(tail) --> newLink -->
- newLink.previous = tail; // currentTail(tail) <--> newLink -->
- tail = newLink; // oldTail <--> newLink(tail) -->
- }
-
- /**
- * Delete the element at the head
- *
- * @return The new head
- */
- public Link 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;
- }
-
- /**
- * Delete the element at the tail
- *
- * @return The new tail
- */
- public Link deleteTail(){
- Link temp = tail;
- tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
- tail.next = null; // 2ndLast(tail) --> null
- return temp;
- }
-
- /**
- * Delete the element from somewhere in the list
- *
- * @param x element to be deleted
- * @return Link deleted
- */
- public Link delete(int x){
- Link current = head;
-
- while(current.value != x) //Find the position to delete
- current = current.next;
-
- if(current == head)
- deleteHead();
-
- else if(current == tail)
- deleteTail();
-
- else{ //Before: 1 <--> 2(current) <--> 3
- current.previous.next = current.next; // 1 --> 3
- current.next.previous = current.previous; // 1 <--> 3
- }
- return current;
- }
-
- /**
- * Inserts element and reorders
- *
- * @param x Element to be added
- */
- public void insertOrdered(int x){
- Link newLink = new Link(x);
- Link current = head;
- while(current != null && x > current.value) //Find the position to insert
- current = current.next;
-
- if(current == head)
- insertHead(x);
-
- else if(current == null)
- insertTail(x);
-
- else{ //Before: 1 <--> 2(current) <--> 3
- newLink.previous = current.previous; // 1 <-- newLink
- current.previous.next = newLink; // 1 <--> newLink
- newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
- current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
- }
- }
-
- /**
- * Returns true if list is empty
- *
- * @return true if list is empty
- */
- public boolean isEmpty(){
- return(head == null);
- }
-
- /**
- * Prints contents of the list
- */
- public void display(){ //Prints contents of the list
- Link current = head;
- while(current!=null){
- current.displayLink();
- current = current.next;
- }
- System.out.println();
- }
-}
-
-/**
- * This class is used to implement the nodes of the
- * linked list.
- *
- * @author Unknown
- *
- */
-class Link{
- /** Value of node */
- public int value;
- /** This points to the link in front of the new link */
- public Link next;
- /** This points to the link behind the new link */
- public Link previous;
-
- /**
- * Constructor
- *
- * @param value Value of node
- */
- public Link(int value){
- this.value = value;
- }
-
- /**
- * Displays the node
- */
- public void displayLink(){
- System.out.print(value+" ");
- }
-
- /**
- * Main Method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]){
- DoublyLinkedList myList = new DoublyLinkedList();
-
- myList.insertHead(13);
- myList.insertHead(7);
- myList.insertHead(10);
- myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
-
- myList.insertTail(11);
- myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
-
- myList.deleteTail();
- myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
-
- myList.delete(7);
- myList.display(); // <-- 10(head) <--> 13(tail) -->
-
- myList.insertOrdered(23);
- myList.insertOrdered(67);
- myList.insertOrdered(3);
- myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
- }
-}
\ No newline at end of file
diff --git a/Data Structures/Lists/SinglyLinkedList.java b/Data Structures/Lists/SinglyLinkedList.java
deleted file mode 100644
index 32747cf2830f..000000000000
--- a/Data Structures/Lists/SinglyLinkedList.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * 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.
- * 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
- * a singly linked list. Elements can only be added/removed
- * at the head/front of the list.
- *
- * @author Unknown
- *
- */
-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
- }
-
-
- /**
- * 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;
- }
-
- Node current = head;
-
- while (--position > 0) {
- current = current.next;
- }
-
- newNode.next = current.next;
- current.next = newNode;
- return head;
- }
-
- /**
- * 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
- * after them.
- *
- * @author Unknown
- *
- */
-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;
- }
-
-}
diff --git a/Data Structures/Matrix/Matrix.java b/Data Structures/Matrix/Matrix.java
deleted file mode 100644
index 6b055362ce69..000000000000
--- a/Data Structures/Matrix/Matrix.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/**
-* Matrix data-type.
-*
-* @author Kyler Smith, 2017
-*/
-
-
-public class Matrix {
-
- public static void main(String[] args) {
-
- int[][] data1 = new int[0][0];
- int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
- int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
-
- Matrix m1 = new Matrix(data1);
- Matrix m2 = new Matrix(data2);
- Matrix m3 = new Matrix(data3);
-
- System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns());
- System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns());
- System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns());
-
- //check for reference issues
- System.out.println("m2 -->\n" + m2);
- data2[1][1] = 101;
- System.out.println("m2 -->\n" + m2);
-
- //test equals
- System.out.println("m2==null: " + m2.equals(null)); //false
- System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false
- System.out.println("m2==m1: " + m2.equals(m1)); //false
- System.out.println("m2==m2: " + m2.equals(m2)); //true
- System.out.println("m2==m3: " + m2.equals(m3)); //false
-
- //test operations (valid)
- System.out.println("2 * m2:\n" + m2.scale(2));
- System.out.println("m2 / 2:\n" + m2.divide(2));
- System.out.println("m2 + m3:\n" + m2.plus(m3));
- System.out.println("m2 - m3:\n" + m2.minus(m3));
- System.out.println("m2 * m3: \n"+m2.multiply(m3));
- }
-
-
- /**
- * Data needs to be a deep copy as not to change the original state.
- */
- private 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;
- }
-
- /**
- * Returns this matrix scaled by a factor. That is, computes sA where s is a
- * constant and A is a matrix (this object).
- *
- * @param scalar : value to scale by
- * @return A new matrix scaled by the scalar value
- */
- public Matrix scale(int scalar) {
-
- int[][] newData = new int[this.data.length][this.data[0].length];
-
- for (int i = 0; i < this.getRows(); ++i)
- for(int j = 0; j < this.getColumns(); ++j)
- newData[i][j] = this.data[i][j] * scalar;
-
- return new Matrix(newData);
- }
-
- /**
- * Returns this matrix divided by a factor. That is, computes sA where s is a
- * constant and A is a matrix (this object).
- *
- * @param scalar : value to divide by
- * @return A new matrix scaled by the scalar value
- */
- public Matrix divide(int scalar) {
-
- int[][] newData = new int[this.data.length][this.data[0].length];
-
- for (int i = 0; i < this.getRows(); ++i)
- for(int j = 0; j < this.getColumns(); ++j)
- newData[i][j] = this.data[i][j] / scalar;
-
- return new Matrix(newData);
- }
-
- /**
- * Adds this matrix to another matrix.
- *
- * @param other : Matrix to be added
- * @return addend
- */
- public Matrix plus(Matrix other) throws RuntimeException {
-
- int[][] newData = new int[this.data.length][this.data[0].length];
-
- if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
- throw new RuntimeException("Not the same size matrix.");
-
- for (int i = 0; i < this.getRows(); ++i)
- for(int j = 0; j < this.getColumns(); ++j)
- newData[i][j] = this.data[i][j] + other.getElement(i, j);
-
- return new Matrix(newData);
- }
-
- /**
- * Subtracts this matrix from another matrix.
- *
- * @param other : Matrix to be subtracted
- * @return difference
- */
- public Matrix minus(Matrix other) throws RuntimeException {
-
- int[][] newData = new int[this.data.length][this.data[0].length];
-
- if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
- throw new RuntimeException("Not the same size matrix.");
-
- for (int i = 0; i < this.getRows(); ++i)
- for(int j = 0; j < this.getColumns(); ++j)
- newData[i][j] = this.data[i][j] - other.getElement(i, j);
-
- return new Matrix(newData);
- }
-
- /**
- * 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 {
- ArrayList _queue = new ArrayList();
-
- private boolean hasElements() {
- return !_queue.isEmpty();
- }
-
- public T peek() {
- T result = null;
- if(this.hasElements()) { result = _queue.get(0); }
- return result;
- }
-
- public boolean add(T element) {
- return _queue.add(element);
- }
-
- public T poll() {
- T result = null;
- if(this.hasElements()) { result = _queue.remove(0); }
- return result;
- }
-
- public static void main(String[] args) {
- GenericArrayListQueue queue = new GenericArrayListQueue();
- System.out.println("Running...");
- assert queue.peek() == null;
- assert queue.poll() == null;
- assert queue.add(1) == true;
- assert queue.peek() == 1;
- assert queue.add(2) == true;
- assert queue.peek() == 1;
- assert queue.poll() == 1;
- assert queue.peek() == 2;
- assert queue.poll() == 2;
- assert queue.peek() == null;
- assert queue.poll() == null;
- System.out.println("Finished.");
- }
-}
diff --git a/Data Structures/Queues/PriorityQueues.java b/Data Structures/Queues/PriorityQueues.java
deleted file mode 100644
index acb6b552537e..000000000000
--- a/Data Structures/Queues/PriorityQueues.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * 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;
-
- /**
- * 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++;
- }
-
- /**
- * 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];
- }
-
- /**
- * 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 implements the PriorityQueue class above.
- *
- * @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
-
- 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
diff --git a/Data Structures/Queues/Queues.java b/Data Structures/Queues/Queues.java
deleted file mode 100644
index 84638cb24751..000000000000
--- a/Data Structures/Queues/Queues.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * 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
- *
- */
-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
- *
- */
-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
diff --git a/Data Structures/Stacks/NodeStack.java b/Data Structures/Stacks/NodeStack.java
deleted file mode 100644
index c598bb8fcba1..000000000000
--- a/Data Structures/Stacks/NodeStack.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/**
-* Implementation of a stack using nodes.
-* Unlimited size, no arraylist.
-*
-* @author Kyler Smith, 2017
-*/
-
-
-public class NodeStack {
-
- /**
- * Entry point for the program.
- */
- public static void main(String[] args) {
- NodeStack Stack = new NodeStack();
-
- Stack.push(3);
- Stack.push(4);
- Stack.push(5);
- System.out.println("Testing :");
- Stack.print(); // prints : 5 4 3
-
- Integer x = Stack.pop(); // x = 5
- Stack.push(1);
- Stack.push(8);
- Integer y = Stack.peek(); // y = 8
- System.out.println("Testing :");
- Stack.print(); // prints : 8 1 4 3
-
- System.out.println("Testing :");
- System.out.println("x : " + x);
- System.out.println("y : " + y);
- }
-
- /**
- * Information each node should contain.
- * @value data : information of the value in the node
- * @value head : the head of the stack
- * @value next : the next value from this node
- * @value previous : the last value from this node
- * @value size : size of the stack
- */
- private Item data;
- private static NodeStack> head;
- private NodeStack> next;
- private NodeStack> previous;
- private static int size = 0;
-
-
- /**
- * Constructors for the NodeStack.
- */
- public NodeStack() {
- }
-
- private NodeStack(Item item) {
- this.data = item;
- }
-
- /**
- * Put a value onto the stack.
- *
- * @param item : value to be put on the stack.
- */
- public void push(Item item) {
-
- NodeStack newNs = new NodeStack(item);
-
- if(this.isEmpty()) {
- NodeStack.setHead(new NodeStack<>(item));
- newNs.setNext(null);
- newNs.setPrevious(null);
- } else {
- newNs.setPrevious(NodeStack.head);
- NodeStack.head.setNext(newNs);
- NodeStack.head = newNs;
- }
-
- NodeStack.setSize(NodeStack.getSize() + 1);
- }
-
- /**
- * Value to be taken off the stack.
- *
- * @return item : value that is returned.
- */
- public Item pop() {
-
- Item item = (Item) NodeStack.head.getData();
-
- NodeStack.head = NodeStack.head.getPrevious();
- NodeStack.head.setNext(null);
-
- NodeStack.setSize(NodeStack.getSize() - 1);
-
- return item;
- }
-
- /**
- * Value that is next to be taken off the stack.
- *
- * @return item : the next value that would be popped off the stack.
- */
- public Item peek() {
- return (Item) NodeStack.head.getData();
- }
-
- /**
- * If the stack is empty or there is a value in.
- *
- * @return boolean : whether or not the stack has anything in it.
- */
- public boolean isEmpty() {
- return NodeStack.getSize() == 0;
- }
-
- /**
- * Returns the size of the stack.
- *
- * @return int : number of values in the stack.
- */
- public int size() {
- return NodeStack.getSize();
- }
-
- /**
- * Print the contents of the stack in the following format.
- *
- * x <- head (next out)
- * y
- * z <- tail (first in)
- * .
- * .
- * .
- *
- */
- public void print() {
- for(NodeStack> n = NodeStack.head; n != null; n = n.previous) {
- System.out.println(n.getData().toString());
- }
- }
-
- /** Getters and setters (private) */
- private NodeStack> getHead() {
- return NodeStack.head;
- }
-
- private static void setHead(NodeStack> ns) {
- NodeStack.head = ns;
- }
-
- private NodeStack> getNext() {
- return next;
- }
-
- private void setNext(NodeStack> next) {
- this.next = next;
- }
-
- private NodeStack> getPrevious() {
- return previous;
- }
-
- private void setPrevious(NodeStack> previous) {
- this.previous = previous;
- }
-
- private static int getSize() {
- return size;
- }
-
- private static void setSize(int size) {
- NodeStack.size = size;
- }
-
- private Item getData() {
- return this.data;
- }
-
- private void setData(Item item) {
- this.data = item;
- }
-}
diff --git a/Data Structures/Stacks/StackOfLinkedList.java b/Data Structures/Stacks/StackOfLinkedList.java
deleted file mode 100644
index 8903e52f0e72..000000000000
--- a/Data Structures/Stacks/StackOfLinkedList.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-// An implementation of a Stack using a Linked List
-
-class StackOfLinkedList {
-
- public static void main(String[] args) {
-
- LinkedListStack stack = new LinkedListStack();
- stack.push(1);
- stack.push(2);
- stack.push(3);
- stack.push(4);
-
- stack.printStack();
-
- System.out.println("Size of stack currently is: " + stack.getSize());
-
- stack.pop();
- stack.pop();
-
- }
-
-}
-
-// A node class
-
-class Node {
- public int data;
- public Node next;
-
- public Node(int data) {
- this.data = data;
- this.next = null;
- }
-}
-
-/**
- * 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) {
- head = n;
- }
- else {
- Node temp = head;
- n.next = temp;
- head = n;
- }
- size++;
- }
-
- public void pop() {
- if (getSize() == 0) {
- System.out.println("Empty stack. Nothing to pop");
- }
-
- Node temp = head;
- head = head.next;
- size--;
-
- System.out.println("Popped element is: " + temp.data);
- }
-
- public void printStack() {
-
- Node temp = head;
- System.out.println("Stack is printed as below: ");
- while (temp != null) {
- System.out.print(temp.data + " ");
- temp = temp.next;
- }
- System.out.println();
-
- }
-
- public boolean isEmpty() {
- return getSize() == 0;
- }
-
- public int getSize() {
- return size;
- }
-
-}
diff --git a/Data Structures/Stacks/Stacks.java b/Data Structures/Stacks/Stacks.java
deleted file mode 100644
index 2861ef5c17e8..000000000000
--- a/Data Structures/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/Data Structures/Trees/AVLTree.java b/Data Structures/Trees/AVLTree.java
deleted file mode 100644
index 4bcf402dc0b7..000000000000
--- a/Data Structures/Trees/AVLTree.java
+++ /dev/null
@@ -1,212 +0,0 @@
-public class AVLTree {
-
- private Node root;
-
- private class Node {
- private int key;
- private int balance;
- private int height;
- private Node left, right, parent;
-
- Node(int k, Node p) {
- key = k;
- parent = p;
- }
- }
-
- public boolean insert(int key) {
- if (root == null)
- root = new Node(key, null);
- else {
- Node n = root;
- Node parent;
- while (true) {
- if (n.key == key)
- return false;
-
- parent = n;
-
- boolean goLeft = n.key > key;
- n = goLeft ? n.left : n.right;
-
- if (n == null) {
- if (goLeft) {
- parent.left = new Node(key, parent);
- } else {
- parent.right = new Node(key, parent);
- }
- rebalance(parent);
- break;
- }
- }
- }
- return true;
- }
-
- private void delete(Node node){
- if(node.left == null && node.right == null){
- if(node.parent == null) root = null;
- else{
- Node parent = node.parent;
- if(parent.left == node){
- parent.left = null;
- }else parent.right = null;
- rebalance(parent);
- }
- return;
- }
- if(node.left!=null){
- Node child = node.left;
- while (child.right!=null) child = child.right;
- node.key = child.key;
- delete(child);
- }else{
- Node child = node.right;
- while (child.left!=null) child = child.left;
- node.key = child.key;
- delete(child);
- }
- }
-
- public void delete(int delKey) {
- if (root == null)
- return;
- Node node = root;
- Node child = root;
-
- while (child != null) {
- node = child;
- child = delKey >= node.key ? node.right : node.left;
- if (delKey == node.key) {
- delete(node);
- return;
- }
- }
- }
-
- private void rebalance(Node n) {
- setBalance(n);
-
- if (n.balance == -2) {
- if (height(n.left.left) >= height(n.left.right))
- n = rotateRight(n);
- else
- n = rotateLeftThenRight(n);
-
- } else if (n.balance == 2) {
- if (height(n.right.right) >= height(n.right.left))
- n = rotateLeft(n);
- else
- n = rotateRightThenLeft(n);
- }
-
- if (n.parent != null) {
- rebalance(n.parent);
- } else {
- root = n;
- }
- }
-
- private Node rotateLeft(Node a) {
-
- Node b = a.right;
- b.parent = a.parent;
-
- a.right = b.left;
-
- if (a.right != null)
- a.right.parent = a;
-
- b.left = a;
- a.parent = b;
-
- if (b.parent != null) {
- if (b.parent.right == a) {
- b.parent.right = b;
- } else {
- b.parent.left = b;
- }
- }
-
- setBalance(a, b);
-
- return b;
- }
-
- private Node rotateRight(Node a) {
-
- Node b = a.left;
- b.parent = a.parent;
-
- a.left = b.right;
-
- if (a.left != null)
- a.left.parent = a;
-
- b.right = a;
- a.parent = b;
-
- if (b.parent != null) {
- if (b.parent.right == a) {
- b.parent.right = b;
- } else {
- b.parent.left = b;
- }
- }
-
- setBalance(a, b);
-
- return b;
- }
-
- private Node rotateLeftThenRight(Node n) {
- n.left = rotateLeft(n.left);
- return rotateRight(n);
- }
-
- private Node rotateRightThenLeft(Node n) {
- n.right = rotateRight(n.right);
- return rotateLeft(n);
- }
-
- private int height(Node n) {
- if (n == null)
- return -1;
- return n.height;
- }
-
- private void setBalance(Node... nodes) {
- for (Node n : nodes)
- reheight(n);
- n.balance = height(n.right) - height(n.left);
- }
-
- public void printBalance() {
- printBalance(root);
- }
-
- private void printBalance(Node n) {
- if (n != null) {
- printBalance(n.left);
- System.out.printf("%s ", n.balance);
- printBalance(n.right);
- }
- }
-
- private void reheight(Node node){
- if(node!=null){
- node.height=1 + Math.max(height(node.left), height(node.right));
- }
- }
-
- public static void main(String[] args) {
- AVLTree tree = new AVLTree();
-
- System.out.println("Inserting values 1 to 10");
- for (int i = 1; i < 10; i++)
- tree.insert(i);
-
- System.out.print("Printing balance: ");
- tree.printBalance();
- }
-}
diff --git a/Data Structures/Trees/BinaryTree.java b/Data Structures/Trees/BinaryTree.java
deleted file mode 100644
index a20d24eebc35..000000000000
--- a/Data Structures/Trees/BinaryTree.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/**
-* This entire class is used to build a Binary Tree data structure.
-* There is the Node Class and the Tree Class, both explained below.
-*
-* @author Unknown
-*
-*/
-
-
-/**
-* This class implements the nodes that will go on the Binary Tree.
-* They consist of the data in them, the node to the left, the node
-* to the right, and the parent from which they came from.
-*
-* @author Unknown
-*
-*/
-class Node{
- /** Data for the node */
- public int data;
- /** The Node to the left of this one */
- public Node left;
- /** The Node to the right of this one */
- public Node right;
- /** The parent of this node */
- public Node parent;
-
- /**
- * Constructor of Node
- *
- * @param value Value to put in the node
- */
- public Node(int value){
- data = value;
- left = null;
- right = null;
- parent = null;
- }
-}
-
-
-/**
-* A binary tree is a data structure in which an element
-* has two successors(children). The left child is usually
-* smaller than the parent, and the right child is usually
-* bigger.
-*
-* @author Unknown
-*
-*/
-class Tree{
- /** The root of the Binary Tree */
- private Node root;
-
- /**
- * Constructor
- */
- public Tree(){
- root = null;
- }
-
- /**
- * Method to find a Node with a certain value
- *
- * @param key Value being looked for
- * @return The node if it finds it, otherwise returns the parent
- */
- public Node find(int key) {
- Node current = root;
- while (current != null) {
- if(key < current.data) {
- current = current.left;
- } else if(key > current.data) {
- current = current.right;
- } else { // If you find the value return it
- return current;
- }
- }
- return null;
- }
-
- /**
- * Inserts certain value into the Binary Tree
- *
- * @param value Value to be inserted
- */
- public void put(int value){
- Node newNode = new Node(value);
- if(root == null)
- root = newNode;
- else{
- //This will return the soon to be parent of the value you're inserting
- Node parent = find(value);
-
- //This if/else assigns the new node to be either the left or right child of the parent
- if(value < parent.data){
- parent.left = newNode;
- parent.left.parent = parent;
- return;
- }
- else{
- parent.right = newNode;
- parent.right.parent = parent;
- return;
- }
- }
- }
-
- /**
- * Deletes a given value from the Binary Tree
- *
- * @param value Value to be deleted
- * @return If the value was deleted
- */
- public boolean remove(int value){
- //temp is the node to be deleted
- Node temp = find(value);
-
- //If the value doesn't exist
- if(temp.data != value)
- return false;
-
- //No children
- if(temp.right == null && temp.left == null){
- if(temp == root)
- root = null;
-
- //This if/else assigns the new node to be either the left or right child of the parent
- else if(temp.parent.data < temp.data)
- temp.parent.right = null;
- else
- temp.parent.left = null;
- return true;
- }
-
- //Two children
- else if(temp.left != null && temp.right != null){
- Node successor = findSuccessor(temp);
-
- //The left tree of temp is made the left tree of the successor
- successor.left = temp.left;
- successor.left.parent = successor;
-
- //If the successor has a right child, the child's grandparent is it's new parent
- if(successor.right != null && successor.parent != temp){
- successor.right.parent = successor.parent;
- successor.parent.left = successor.right;
- successor.right = temp.right;
- successor.right.parent = successor;
- }
- if(temp == root){
- successor.parent = null;
- root = successor;
- return true;
- }
-
- //If you're not deleting the root
- else{
- successor.parent = temp.parent;
-
- //This if/else assigns the new node to be either the left or right child of the parent
- if(temp.parent.data < temp.data)
- temp.parent.right = successor;
- else
- temp.parent.left = successor;
- return true;
- }
- }
- //One child
- else{
- //If it has a right child
- if(temp.right != null){
- if(temp == root){
- root = temp.right; return true;}
-
- temp.right.parent = temp.parent;
-
- //Assigns temp to left or right child
- if(temp.data < temp.parent.data)
- temp.parent.left = temp.right;
- else
- temp.parent.right = temp.right;
- return true;
- }
- //If it has a left child
- else{
- if(temp == root){
- root = temp.left; return true;}
-
- temp.left.parent = temp.parent;
-
- //Assigns temp to left or right side
- if(temp.data < temp.parent.data)
- temp.parent.left = temp.left;
- else
- temp.parent.right = temp.left;
- return true;
- }
- }
- }
-
- /**
- * This method finds the Successor to the Node given.
- * Move right once and go left down the tree as far as you can
- *
- * @param n Node that you want to find the Successor of
- * @return The Successor of the node
- */
- public Node findSuccessor(Node n){
- if(n.right == null)
- return n;
- Node current = n.right;
- Node parent = n.right;
- while(current != null){
- parent = current;
- current = current.left;
- }
- return parent;
- }
-
- /**
- * Returns the root of the Binary Tree
- *
- * @return the root of the Binary Tree
- */
- public Node getRoot(){
- return root;
- }
-
- /**
- * Prints leftChild - root - rightChild
- *
- * @param localRoot The local root of the binary tree
- */
- public void inOrder(Node localRoot){
- if(localRoot != null){
- inOrder(localRoot.left);
- System.out.print(localRoot.data + " ");
- inOrder(localRoot.right);
- }
- }
-
- /**
- * Prints root - leftChild - rightChild
- *
- * @param localRoot The local root of the binary tree
- */
- public void preOrder(Node localRoot){
- if(localRoot != null){
- System.out.print(localRoot.data + " ");
- preOrder(localRoot.left);
- preOrder(localRoot.right);
- }
- }
-
- /**
- * Prints rightChild - leftChild - root
- *
- * @param localRoot The local root of the binary tree
- */
- public void postOrder(Node localRoot){
- if(localRoot != null){
- postOrder(localRoot.left);
- postOrder(localRoot.right);
- System.out.print(localRoot.data + " ");
- }
- }
- }
diff --git a/Data Structures/Trees/FindHeightOfTree.java b/Data Structures/Trees/FindHeightOfTree.java
deleted file mode 100644
index 675b1e8b57cb..000000000000
--- a/Data Structures/Trees/FindHeightOfTree.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-import java.util.LinkedList;
-
-public class FindHeightOfTree {
-
- // Driver Program
- public static void main(String[] args) {
- Node tree = new Node(5);
- tree.insert(3);
- tree.insert(7);
- tree.insert(1);
- tree.insert(-1);
- tree.insert(29);
- tree.insert(93);
- tree.insert(6);
- tree.insert(0);
- tree.insert(-5);
- tree.insert(-6);
- tree.insert(-8);
- tree.insert(-1);
-
- // A level order representation of the tree
- tree.printLevelOrder();
- System.out.println();
-
- System.out.println("Height of the tree is: " + tree.findHeight());
- }
-}
-
-/**
- * The Node class which initializes a Node of a tree
- * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
- * findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf
- */
-class Node {
- Node left, right;
- int data;
-
- public Node(int data) {
- this.data = data;
- }
-
- public void insert (int value) {
- if (value < data) {
- if (left == null) {
- left = new Node(value);
- }
- else {
- left.insert(value);
- }
- }
- else {
- if (right == null) {
- right = new Node(value);
- }
- else {
- right.insert(value);
- }
- }
- }
-
- public void printLevelOrder() {
- LinkedList queue = new LinkedList<>();
- queue.add(this);
- while(!queue.isEmpty()) {
- Node n = queue.poll();
- System.out.print(n.data + " ");
- if (n.left != null) {
- queue.add(n.left);
- }
- if (n.right != null) {
- queue.add(n.right);
- }
- }
- }
-
- public int findHeight() {
- return findHeight(this);
- }
-
- private int findHeight(Node root) {
- if (root.left == null && root.right == null) {
- return 0;
- }
- else if (root.left != null && root.right != null) {
- return 1 + Math.max(findHeight(root.left), findHeight(root.right));
- }
- else if (root.left == null && root.right != null) {
- return 1 + findHeight(root.right);
- }
- else {
- return 1 + findHeight(root.left);
- }
- }
-}
-
diff --git a/Data Structures/Trees/GenericTree.Java b/Data Structures/Trees/GenericTree.Java
deleted file mode 100644
index 16ab5fb53b1e..000000000000
--- a/Data Structures/Trees/GenericTree.Java
+++ /dev/null
@@ -1,226 +0,0 @@
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.Scanner;
-
-public class treeclass {
- private class Node {
- int data;
- ArrayList child = new ArrayList<>();
- }
-
- private Node root;
- private int size;
-
- /*
- A generic tree is a tree which can have as many children as it can be
- It might be possible that every node present is directly connected to
- root node.
-
- In this code
- Every function has two copies: one function is helper function which can be called from
- main and from that function a private function is called which will do the actual work.
- I have done this, while calling from main one have to give minimum parameters.
-
- */
- public treeclass() { //Constructor
- Scanner scn = new Scanner(System.in);
- root = create_treeG(null, 0, scn);
- }
-
- private Node create_treeG(Node node, int childindx, Scanner scn) {
- // display
- if (node == null) {
- System.out.println("Enter root's data");
- } else {
- System.out.println("Enter data of parent of index " + node.data + " " + childindx);
- }
- // input
- node = new Node();
- node.data = scn.nextInt();
- System.out.println("number of children");
- int number = scn.nextInt();
- for (int i = 0; i < number; i++) {
- Node childd = create_treeG(node, i, scn);
- size++;
- node.child.add(childd);
- }
- return node;
- }
-
- /*
- Function to display the generic tree
- */
- public void display() { //Helper function
- display_1(root);
- return;
- }
-
- private void display_1(Node parent) {
- System.out.print(parent.data + "=>");
- for (int i = 0; i < parent.child.size(); i++) {
- System.out.print(parent.child.get(i).data + " ");
- }
- System.out.println(".");
- for (int i = 0; i < parent.child.size(); i++) {
- display_1(parent.child.get(i));
- }
- return;
- }
-
- /*
- One call store the size directly but if you are asked compute size this function to calcuate
- size goes as follows
- */
-
- public int size2call() {
- return size2(root);
- }
-
- public int size2(Node roott) {
- int sz = 0;
- for (int i = 0; i < roott.child.size(); i++) {
- sz += size2(roott.child.get(i));
- }
- return sz + 1;
- }
-
- /*
- Function to compute maximum value in the generic tree
- */
- public int maxcall() {
- int maxi = root.data;
- return max(root, maxi);
- }
-
- private int max(Node roott, int maxi) {
- if (maxi < roott.data)
- maxi = roott.data;
- for (int i = 0; i < roott.child.size(); i++) {
- maxi = max(roott.child.get(i), maxi);
- }
-
- return maxi;
- }
-
- /*
- Function to compute HEIGHT of the generic tree
- */
-
- public int heightcall() {
- return height(root) - 1;
- }
-
- private int height(Node node) {
- int h = 0;
- for (int i = 0; i < node.child.size(); i++) {
- int k = height(node.child.get(i));
- if (k > h)
- h = k;
- }
- return h + 1;
- }
-
- /*
- Function to find whether a number is present in the generic tree or not
- */
-
- public boolean findcall(int info) {
- return find(root, info);
- }
-
- private boolean find(Node node, int info) {
- if (node.data == info)
- return true;
- for (int i = 0; i < node.child.size(); i++) {
- if (find(node.child.get(i), info))
- return true;
- }
- return false;
- }
-
- /*
- Function to calculate depth of generic tree
- */
- public void depthcaller(int dep) {
- depth(root, dep);
- }
-
- public void depth(Node node, int dep) {
- if (dep == 0) {
- System.out.println(node.data);
- return;
- }
- for (int i = 0; i < node.child.size(); i++)
- depth(node.child.get(i), dep - 1);
- return;
- }
-
- /*
- Function to print generic tree in pre-order
- */
- public void preordercall() {
- preorder(root);
- System.out.println(".");
- }
-
- private void preorder(Node node) {
- System.out.print(node.data + " ");
- for (int i = 0; i < node.child.size(); i++)
- preorder(node.child.get(i));
- }
-
- /*
- Function to print generic tree in post-order
- */
- public void postordercall() {
- postorder(root);
- System.out.println(".");
- }
-
- private void postorder(Node node) {
- for (int i = 0; i < node.child.size(); i++)
- postorder(node.child.get(i));
- System.out.print(node.data + " ");
- }
-
- /*
- Function to print generic tree in level-order
- */
-
- public void levelorder() {
- LinkedList q = new LinkedList<>();
- q.addLast(root);
- while (!q.isEmpty()) {
- int k = q.getFirst().data;
- System.out.print(k + " ");
-
- for (int i = 0; i < q.getFirst().child.size(); i++) {
- q.addLast(q.getFirst().child.get(i));
- }
- q.removeFirst();
- }
- System.out.println(".");
- }
-
- /*
- Function to remove all leaves of generic tree
- */
- public void removeleavescall() {
- removeleaves(root);
- }
-
- private void removeleaves(Node node) {
- ArrayList arr = new ArrayList<>();
- for (int i = 0; i < node.child.size(); i++) {
- if (node.child.get(i).child.size() == 0) {
- arr.add(i);
- // node.child.remove(i);
- // i--;
- } else
- removeleaves(node.child.get(i));
- }
- for (int i = arr.size() - 1; i >= 0; i--) {
- node.child.remove(arr.get(i) + 0);
- }
- }
-
diff --git a/Data Structures/Trees/LevelOrderTraversal.java b/Data Structures/Trees/LevelOrderTraversal.java
deleted file mode 100644
index 8cb304f18c8f..000000000000
--- a/Data Structures/Trees/LevelOrderTraversal.java
+++ /dev/null
@@ -1,78 +0,0 @@
-class Node
-{
- int data;
- Node left, right;
- public Node(int item)
- {
- data = item;
- left = right = null;
- }
-}
-
-public class LevelOrderTraversal
-{
- // Root of the Binary Tree
- Node root;
-
- public LevelOrderTraversal()
- {
- root = null;
- }
-
- /* function to print level order traversal of tree*/
- void printLevelOrder()
- {
- int h = height(root);
- int i;
- for (i=1; i<=h; i++)
- printGivenLevel(root, i);
- }
-
- /* Compute the "height" of a tree -- the number of
- nodes along the longest path from the root node
- down to the farthest leaf node.*/
- int height(Node root)
- {
- if (root == null)
- 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);
- }
- }
-
- /* Print nodes at the given level */
- void printGivenLevel (Node root ,int level)
- {
- if (root == null)
- return;
- if (level == 1)
- System.out.print(root.data + " ");
- else if (level > 1)
- {
- printGivenLevel(root.left, level-1);
- printGivenLevel(root.right, level-1);
- }
- }
-
- /* Driver program to test above functions */
- public static void main(String args[])
- {
- LevelOrderTraversal tree = new LevelOrderTraversal();
- tree.root= new Node(1);
- tree.root.left= new Node(2);
- tree.root.right= new Node(3);
- tree.root.left.left= new Node(4);
- tree.root.left.right= new Node(5);
-
- System.out.println("Level order traversal of binary tree is ");
- tree.printLevelOrder();
- }
-}
\ No newline at end of file
diff --git a/Data Structures/Trees/LevelOrderTraversalQueue.java b/Data Structures/Trees/LevelOrderTraversalQueue.java
deleted file mode 100644
index ce7ad74542cf..000000000000
--- a/Data Structures/Trees/LevelOrderTraversalQueue.java
+++ /dev/null
@@ -1,62 +0,0 @@
-import java.util.Queue;
-import java.util.LinkedList;
-
-/* Class to represent Tree node */
-class Node {
- int data;
- Node left, right;
-
- public Node(int item) {
- data = item;
- left = null;
- right = null;
- }
-}
-
-/* Class to print Level Order Traversal */
-public class LevelOrderTraversalQueue {
-
- Node root;
-
- /* Given a binary tree. Print its nodes in level order
- using array for implementing queue */
- void printLevelOrder()
- {
- Queue queue = new LinkedList();
- queue.add(root);
- while (!queue.isEmpty())
- {
-
- /* poll() removes the present head.
- For more information on poll() visit
- http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
- Node tempNode = queue.poll();
- System.out.print(tempNode.data + " ");
-
- /*Enqueue left child */
- if (tempNode.left != null) {
- queue.add(tempNode.left);
- }
-
- /*Enqueue right child */
- if (tempNode.right != null) {
- queue.add(tempNode.right);
- }
- }
- }
-
- public static void main(String args[])
- {
- /* creating a binary tree and entering
- the nodes */
- LevelOrderTraversalQueue tree_level = new LevelOrderTraversalQueue();
- tree_level.root = new Node(1);
- tree_level.root.left = new Node(2);
- tree_level.root.right = new Node(3);
- tree_level.root.left.left = new Node(4);
- tree_level.root.left.right = new Node(5);
-
- System.out.println("Level order traversal of binary tree is - ");
- tree_level.printLevelOrder();
- }
-}
\ No newline at end of file
diff --git a/Data Structures/Trees/PrintTopViewofTree.java b/Data Structures/Trees/PrintTopViewofTree.java
deleted file mode 100644
index 27016ee2eee4..000000000000
--- a/Data Structures/Trees/PrintTopViewofTree.java
+++ /dev/null
@@ -1,105 +0,0 @@
-// Java program to print top view of Binary tree
-import java.util.*;
-
-// Class for a tree node
-class TreeNode
-{
- // Members
- int key;
- TreeNode left, right;
-
- // Constructor
- public TreeNode(int key)
- {
- this.key = key;
- left = right = null;
- }
-}
-
-// A class to represent a queue item. The queue is used to do Level
-// order traversal. Every Queue item contains node and horizontal
-// distance of node from root
-class QItem
-{
- TreeNode node;
- int hd;
- public QItem(TreeNode n, int h)
- {
- node = n;
- hd = h;
- }
-}
-
-// Class for a Binary Tree
-class Tree
-{
- TreeNode root;
-
- // Constructors
- public Tree() { root = null; }
- public Tree(TreeNode n) { root = n; }
-
- // This method prints nodes in top view of binary tree
- public void printTopView()
- {
- // base case
- if (root == null) { return; }
-
- // Creates an empty hashset
- HashSet set = new HashSet<>();
-
- // Create a queue and add root to it
- Queue Q = new LinkedList();
- Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
-
- // Standard BFS or level order traversal loop
- while (!Q.isEmpty())
- {
- // Remove the front item and get its details
- QItem qi = Q.remove();
- int hd = qi.hd;
- TreeNode n = qi.node;
-
- // If this is the first node at its horizontal distance,
- // then this node is in top view
- if (!set.contains(hd))
- {
- set.add(hd);
- System.out.print(n.key + " ");
- }
-
- // Enqueue left and right children of current node
- if (n.left != null)
- Q.add(new QItem(n.left, hd-1));
- if (n.right != null)
- Q.add(new QItem(n.right, hd+1));
- }
- }
-}
-
-// Driver class to test above methods
-public class PrintTopViewofTree
-{
- public static void main(String[] args)
- {
- /* Create following Binary Tree
- 1
- / \
- 2 3
- \
- 4
- \
- 5
- \
- 6*/
- TreeNode root = new TreeNode(1);
- root.left = new TreeNode(2);
- root.right = new TreeNode(3);
- root.left.right = new TreeNode(4);
- root.left.right.right = new TreeNode(5);
- root.left.right.right.right = new TreeNode(6);
- Tree t = new Tree(root);
- System.out.println("Following are nodes in top view of Binary Tree");
- t.printTopView();
- }
-}
\ No newline at end of file
diff --git a/Data Structures/Trees/TreeTraversal.java b/Data Structures/Trees/TreeTraversal.java
deleted file mode 100644
index bd0f2f7f5634..000000000000
--- a/Data Structures/Trees/TreeTraversal.java
+++ /dev/null
@@ -1,124 +0,0 @@
-import java.util.LinkedList;
-
-/**
-*
-* @author Varun Upadhyay (https://github.com/varunu28)
-*
-*/
-
-
-// Driver Program
-public class TreeTraversal {
- public static void main(String[] args) {
- Node tree = new Node(5);
- tree.insert(3);
- tree.insert(2);
- tree.insert(7);
- tree.insert(4);
- tree.insert(6);
- tree.insert(8);
-
- // Prints 5 3 2 4 7 6 8
- System.out.println("Pre order traversal:");
- tree.printPreOrder();
- System.out.println();
- // Prints 2 3 4 5 6 7 8
- System.out.println("In order traversal:");
- tree.printInOrder();
- System.out.println();
- // Prints 2 4 3 6 8 7 5
- System.out.println("Post order traversal:");
- tree.printPostOrder();
- System.out.println();
- // Prints 5 3 7 2 4 6 8
- System.out.println("Level order traversal:");
- tree.printLevelOrder();
- System.out.println();
- }
-}
-
-/**
-* The Node class which initializes a Node of a tree
-* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
-* printInOrder: LEFT -> ROOT -> RIGHT
-* printPreOrder: ROOT -> LEFT -> RIGHT
-* printPostOrder: LEFT -> RIGHT -> ROOT
-* printLevelOrder: Prints by level (starting at root), from left to right.
-*/
-class Node {
- Node left, right;
- int data;
-
- public Node(int data) {
- this.data = data;
- }
-
- public void insert (int value) {
- if (value < data) {
- if (left == null) {
- left = new Node(value);
- }
- else {
- left.insert(value);
- }
- }
- else {
- if (right == null) {
- right = new Node(value);
- }
- else {
- right.insert(value);
- }
- }
- }
-
- public void printInOrder() {
- if (left != null) {
- left.printInOrder();
- }
- System.out.print(data + " ");
- if (right != null) {
- right.printInOrder();
- }
- }
-
- public void printPreOrder() {
- System.out.print(data + " ");
- if (left != null) {
- left.printPreOrder();
- }
- if (right != null) {
- right.printPreOrder();
- }
- }
-
- public void printPostOrder() {
- if (left != null) {
- left.printPostOrder();
- }
- if (right != null) {
- right.printPostOrder();
- }
- System.out.print(data + " ");
- }
-
- /**
- * O(n) time algorithm.
- * Uses O(n) space to store nodes in a queue to aid in traversal.
- */
- public void printLevelOrder() {
- LinkedList queue = new LinkedList<>();
- queue.add(this);
- while (queue.size() > 0) {
- Node head = queue.remove();
- System.out.print(head.data + " ");
- // Add children of recently-printed node to queue, if they exist.
- if (head.left != null) {
- queue.add(head.left);
- }
- if (head.right != null) {
- queue.add(head.right);
- }
- }
- }
-}
diff --git a/Data Structures/Trees/TrieImp.java b/Data Structures/Trees/TrieImp.java
deleted file mode 100644
index c55586ff0065..000000000000
--- a/Data Structures/Trees/TrieImp.java
+++ /dev/null
@@ -1,135 +0,0 @@
-//Trie Data structure implementation without any libraries */
-
-/**
- *
- * @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
- *
- */
-import java.util.Scanner;
-
-public class TrieImp {
-
- public class TrieNode {
- TrieNode[] child;
- boolean end;
-
- public TrieNode(){
- child = new TrieNode[26];
- end = false;
- }
- }
- private final TrieNode root;
- public TrieImp(){
- root = new TrieNode();
- }
-
- public void insert(String word){
- TrieNode currentNode = root;
- for(int i=0; i < word.length();i++){
- TrieNode node = currentNode.child[word.charAt(i)-'a'];
- if(node == null){
- node = new TrieNode();
- currentNode.child[word.charAt(i)-'a']=node;
- }
- currentNode = node;
- }
- currentNode.end = true;
- }
- public boolean search(String word){
- TrieNode currentNode = root;
- for(int i=0;i= min and <= max. */
- boolean isBSTUtil(Node node, int min, int max)
- {
- /* an empty tree is BST */
- if (node == null)
- return true;
-
- /* false if this node violates the min/max constraints */
- if (node.data < min || node.data > max)
- return false;
-
- /* otherwise check the subtrees recursively
- tightening the min/max constraints */
- // Allow only distinct values
- return (isBSTUtil(node.left, min, node.data-1) &&
- isBSTUtil(node.right, node.data+1, max));
- }
-
- /* Driver program to test above functions */
- public static void main(String args[])
- {
- ValidBSTOrNot tree = new ValidBSTOrNot();
- tree.root = new Node(4);
- tree.root.left = new Node(2);
- tree.root.right = new Node(5);
- tree.root.left.left = new Node(1);
- tree.root.left.right = new Node(3);
-
- if (tree.isBST())
- System.out.println("IS BST");
- else
- System.out.println("Not a BST");
- }
-}
\ No newline at end of file
diff --git a/Dynamic Programming/CoinChange.java b/Dynamic Programming/CoinChange.java
deleted file mode 100644
index 51fc64a58a12..000000000000
--- a/Dynamic Programming/CoinChange.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-public class CoinChange {
-
- // Driver Program
- public static void main(String[] args) {
-
- int amount = 12;
- int[] coins = {1, 2, 5};
-
- System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
- }
-
- /**
- * This method finds the number of combinations of getting change for a given amount and change coins
- *
- * @param coins The list of coins
- * @param amount The amount for which we need to find the change
- * Finds the number of combinations of change
- **/
- public static int change(int[] coins, int amount) {
-
- int[] combinations = new int[amount+1];
- combinations[0] = 1;
-
- for (int coin : coins) {
- for (int i=coin; i=coin) {
- combinations[i] += combinations[i-coin];
- }
- }
- // Uncomment the below line to see the state of combinations for each coin
- // printAmount(combinations);
- }
-
- return combinations[amount];
- }
-
- // A basic print method which prints all the contents of the array
- public static void printAmount(int[] arr) {
-
- for (int i=0; i insert ? insert : replace;
- min = delete > min ? min : delete;
- dp[i + 1][j + 1] = min;
- }
- }
- }
- /* return the final answer , after traversing through both the strings*/
- return dp[len1][len2];
- }
-
-
- // Driver program to test above function
- public static void main(String args[])
- {
- Scanner input = new Scanner(System.in);
- String s1,s2;
- System.out.println("Enter the First String");
- s1 = input.nextLine();
- System.out.println("Enter the Second String");
- s2 = input.nextLine();
- //ans stores the final Edit Distance between the two strings
- int ans=0;
- ans=minDistance(s1,s2);
- System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 +"\" is "+ans);
- }
- }
diff --git a/Dynamic Programming/EggDropping.java b/Dynamic Programming/EggDropping.java
deleted file mode 100644
index 382d7ea86c2c..000000000000
--- a/Dynamic Programming/EggDropping.java
+++ /dev/null
@@ -1,53 +0,0 @@
-//Dynamic Programming solution for the Egg Dropping Puzzle
-public class EggDropping
-{
-
- // min trials with n eggs and m floors
-
- private static int minTrials(int n, int m)
- {
-
- int eggFloor[][] = new int[n+1][m+1];
- int result, x;
-
- for (int i = 1; i <= n; i++)
- {
- eggFloor[i][0] = 0; // Zero trial for zero floor.
- eggFloor[i][1] = 1; // One trial for one floor
- }
-
- // j trials for only 1 egg
-
- for (int j = 1; j <= m; j++)
- eggFloor[1][j] = j;
-
- // Using bottom-up approach in DP
-
- for (int i = 2; i <= n; i++)
- {
- for (int j = 2; j <= m; j++)
- {
- eggFloor[i][j] = Integer.MAX_VALUE;
- for (x = 1; x <= j; x++)
- {
- result = 1 + Math.max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
-
- //choose min of all values for particular x
- if (result < eggFloor[i][j])
- eggFloor[i][j] = result;
- }
- }
- }
-
- return eggFloor[n][m];
- }
-
- //testing program
- public static void main(String args[])
- {
- int n = 2, m = 4;
- //result outputs min no. of trials in worst case for n eggs and m floors
- int result = minTrials(n, m);
- System.out.println(result);
- }
-}
diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java
deleted file mode 100644
index b2524b4db471..000000000000
--- a/Dynamic Programming/Fibonacci.java
+++ /dev/null
@@ -1,75 +0,0 @@
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-public class Fibonacci {
-
- 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
- }
-
- /**
- * 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
- **/
-
- private static int fibMemo(int n) {
- if (map.containsKey(n)) {
- return map.get(n);
- }
-
- int f;
-
- if (n <= 2) {
- f = 1;
- }
- else {
- f = fibMemo(n-1) + fibMemo(n-2);
- map.put(n,f);
- }
-
- return f;
- }
-
- /**
- * 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
- **/
-
- private static int fibBotUp(int n) {
-
- Map fib = new HashMap();
-
- for (int i=1;imaxsum){
- maxsum=cursum;
- }
- if(cursum<=0){
- cursum=0;
- }
- }
- return maxsum;
- }
-
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- int n,arr[],i;
- n=sc.nextInt();
- arr=new int[n];
- for(i=0;i lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1];
- }
- }
- }
- return lcsString(str1, str2, lcsMatrix);
- }
-
- public static String lcsString (String str1, String str2, int[][] lcsMatrix) {
- StringBuilder lcs = new StringBuilder();
- int i = str1.length(),
- j = str2.length();
- while(i > 0 && j > 0) {
- if(str1.charAt(i-1) == str2.charAt(j-1)) {
- lcs.append(str1.charAt(i-1));
- i--;
- j--;
- } else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) {
- i--;
- } else {
- j--;
- }
- }
- return lcs.reverse().toString();
- }
-
- public static void main(String[] args) {
- String str1 = "DSGSHSRGSRHTRD";
- String str2 = "DATRGAGTSHS";
- String lcs = getLCS(str1, str2);
-
- //Print LCS
- if(lcs != null) {
- System.out.println("String 1: " + str1);
- System.out.println("String 2: " + str2);
- System.out.println("LCS: " + lcs);
- System.out.println("LCS length: " + lcs.length());
- }
- }
-}
\ No newline at end of file
diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java
deleted file mode 100644
index eaa574a40989..000000000000
--- a/Dynamic Programming/LongestIncreasingSubsequence.java
+++ /dev/null
@@ -1,62 +0,0 @@
-import java.util.Scanner;
-
-/**
- *
- * @author Afrizal Fikri (https://github.com/icalF)
- *
- */
-public class LongestIncreasingSubsequence {
- public static void main(String[] args) throws Exception {
-
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
-
- int ar[] = new int[n];
- for (int i = 0; i < n; i++) {
- ar[i] = sc.nextInt();
- }
-
- System.out.println(LIS(ar));
- }
-
- private static int upperBound(int[] ar, int l, int r, int key) {
- while (l < r-1) {
- int m = (l + r) / 2;
- if (ar[m] >= key)
- r = m;
- else
- l = m;
- }
-
- return r;
- }
-
- 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
-
- tail[0] = array[0];
- for (int i = 1; i < N; i++) {
-
- // new smallest value
- if (array[i] < tail[0])
- tail[0] = array[i];
-
- // 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)
- else
- tail[upperBound(tail, -1, length-1, array[i])] = array[i];
- }
-
- return length;
- }
-}
\ No newline at end of file
diff --git a/Dynamic Programming/RodCutting.java b/Dynamic Programming/RodCutting.java
deleted file mode 100644
index cd2512059ae2..000000000000
--- a/Dynamic Programming/RodCutting.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/* 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;
- }
-
- 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));
- }
-}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000000..f6bcf04e7773
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 The Algorithms
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Misc/PalindromicPrime.java b/Misc/PalindromicPrime.java
deleted file mode 100644
index 866467206456..000000000000
--- a/Misc/PalindromicPrime.java
+++ /dev/null
@@ -1,41 +0,0 @@
-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
- }
-
- public static boolean prime(int num) { // checking if number is prime or not
- for (int divisor = 2; divisor <= num / 2; divisor++) {
- if (num % divisor == 0) {
- return false; // false if not prime
- }
- }
- return true; // True if prime
- }
-
- 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;
- }
- 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
- }
- }
-};
diff --git a/Misc/heap_sort.java b/Misc/heap_sort.java
deleted file mode 100644
index 991d689ba70f..000000000000
--- a/Misc/heap_sort.java
+++ /dev/null
@@ -1,73 +0,0 @@
-public class heap_sort
-{
- public void sort(int arr[])
- {
- int n = arr.length;
-
- // Build heap (rearrange array)
- for (int i = n / 2 - 1; i >= 0; i--)
- heapify(arr, n, i);
-
- // One by one extract an element from heap
- for (int i=n-1; i>=0; i--)
- {
- // Move current root to end
- int temp = arr[0];
- arr[0] = arr[i];
- arr[i] = temp;
-
- // call max heapify on the reduced heap
- heapify(arr, i, 0);
- }
- }
-
- // To heapify a subtree rooted with node i which is
- // an index in arr[]. n is size of heap
- void heapify(int arr[], int n, int i)
- {
- int largest = i; // Initialize largest as root
- int l = 2*i + 1; // left = 2*i + 1
- int r = 2*i + 2; // right = 2*i + 2
-
- // If left child is larger than root
- if (l < n && arr[l] > arr[largest])
- largest = l;
-
- // If right child is larger than largest so far
- if (r < n && arr[r] > arr[largest])
- largest = r;
-
- // If largest is not root
- if (largest != i)
- {
- int swap = arr[i];
- arr[i] = arr[largest];
- arr[largest] = swap;
-
- // Recursively heapify the affected sub-tree
- heapify(arr, n, largest);
- }
- }
-
- /* A utility function to print array of size n */
- static void printArray(int arr[])
- {
- int n = arr.length;
- for (int i=0; i 0) {
- remainder = number % 10;
- sum = sum + (remainder * remainder * remainder);
- number = number / 10;
- }
- if (sum == temp) {
- return true;
- } else {
- return false;
- }
-
- }
-}
\ No newline at end of file
diff --git a/Others/BrianKernighanAlgorithm.java b/Others/BrianKernighanAlgorithm.java
deleted file mode 100644
index cb27eec150ef..000000000000
--- a/Others/BrianKernighanAlgorithm.java
+++ /dev/null
@@ -1,55 +0,0 @@
-import java.util.Scanner;
-
-/**
- *
- * @author Nishita Aggarwal
- *
- * Brian Kernighan’s Algorithm
- *
- * algorithm to count the number of set bits in a given number
- *
- * Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the
- * rightmost set bit).
- * So if we subtract a number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit.
- *
- * If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
- *
- *
- * Time Complexity: O(logn)
- *
- */
-
-
-public class BrianKernighanAlgorithm {
-
- /**
- * @param num: number in which we count the set bits
- *
- * @return int: Number of set bits
- * */
- static int countSetBits(int num)
- {
- int cnt = 0;
- while(num != 0)
- {
- num = num & (num-1);
- cnt++;
- }
- return cnt;
- }
-
-
- /**
- *
- * @param args : command line arguments
- *
- */
- public static void main(String args[])
- {
- Scanner sc = new Scanner(System.in);
- int num = sc.nextInt();
- int setBitCount = countSetBits(num);
- System.out.println(setBitCount);
- sc.close();
- }
-}
diff --git a/Others/CountChar.java b/Others/CountChar.java
deleted file mode 100644
index 6504aabb4929..000000000000
--- a/Others/CountChar.java
+++ /dev/null
@@ -1,43 +0,0 @@
-import java.util.Scanner;
-
-
-/**
- * @author Kyler Smith, 2017
- *
- * Implementation of a character count.
- * (Slow, could be improved upon, effectively O(n).
- * */
-
-public class CountChar {
-
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter your text: ");
- String str = input.nextLine();
- input.close();
- System.out.println("There are " + CountCharacters(str) + " characters.");
- }
-
- /**
- * @param str: String to count the characters
- *
- * @return int: Number of characters in the passed string
- * */
-
- private static int CountCharacters(String str) {
-
- int count = 0;
-
- if(str == "" || str == null) //Exceptions
- {
- return 0;
- }
-
- for(int i = 0; i < str.length(); i++) {
- if(!Character.isWhitespace(str.charAt(i))) {
- count++;
- }}
-
- return count;
- }
-}
diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java
deleted file mode 100644
index 05011dd4212f..000000000000
--- a/Others/Dijkshtra.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-@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;
- }
- }
-
- //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{
- @Override
- public int compare(Node o1, Node o2) {
- if(o1.freq>o2.freq){return 1;}
- else if(o1.freq 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){
- //Sorting list in increasing order of its letter frequency
- li.sort(new comp());
- Node temp=null;
- Iterator it=li.iterator();
- //System.out.println(li.size());
- //Loop for making huffman tree till only single node remains in list
- while(true){
- temp=new Node();
- //a and b are Node which are to be combine to make its parent
- Node a=new Node(),b=new Node();
- a=null;b=null;
- //checking if list is eligible for combining or not
- //here first assignment of it.next in a will always be true as list till end will
- //must have atleast one node
- a=(Node)it.next();
- //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
- //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
- temp.left=a;temp.right=b;
- //after combing, removing first two nodes in list which are already combined
- li.remove(0);//removes first element which is now combined -step1
- li.remove(0);//removes 2nd element which comes on 1st position after deleting first in step1
- li.add(temp);//adding new combined node to list
- //print_list(li); //For visualizing each combination step
- }
- //Sorting after combining to again repeat above on sorted frequency list
- li.sort(new comp());
- it=li.iterator();//resetting list pointer to first node (head/root of tree)
- if(li.size()==1){return (Node)it.next();} //base condition ,returning root of huffman tree
- }
-}
-
- //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
- int freq=n.freq; // recording root freq to avoid it adding in path encoding
- find_path_and_encode(st,n,ch,freq);
- }
-
- //A simple utility function to print stack (Used for printing path)
- public static void print_path(Stack st){
- for(int i=0;i st,Node root,String s,int f){
- //Base condition
- if(root!= null){
- if(root.freq!=f){st.push(root);} // avoiding root to add in path/encoding bits
- if(root.letr.equals(s)){print_path(st);return;} // Recursion stopping condition when path gets founded
- find_path_and_encode(st,root.left,s,f);
- find_path_and_encode(st,root.right,s,f);
- //Popping if path not found in right or left of this node,because we previously
- //pushed this node in taking a mindset that it might be in path
- st.pop();
- }
- }
-
- public static void main(String args[]){
- List li=new LinkedList<>();
- Scanner in=new Scanner(System.in);
- 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");
- for(int i=0;i 0 && T.charAt(i) != P.charAt(q)) {
- q = pi[q - 1];
- }
-
- if (T.charAt(i) == P.charAt(q)) {
- q++;
- }
-
- if (q == n) {
- System.out.println("Pattern starts: " + (i + 1 - n));
- q = pi[q - 1];
- }
- }
-
- }
-
- // return the prefix function
- private int[] computePrefixFunction(final String P) {
- final int n = P.length();
- final int[] pi = new int[n];
- pi[0] = 0;
- int q = 0;
- for (int i = 1; i < n; i++) {
- while (q > 0 && P.charAt(q) != P.charAt(i)) {
- q = pi[q - 1];
- }
-
- if (P.charAt(q) == P.charAt(i)) {
- q++;
- }
-
- pi[i] = q;
-
- }
-
- return pi;
- }
-}
diff --git a/Others/LinearCongruentialGenerator.java b/Others/LinearCongruentialGenerator.java
deleted file mode 100644
index b03c10daec2a..000000000000
--- a/Others/LinearCongruentialGenerator.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/***
- * A pseudorandom number generator.
- *
- * @author Tobias Carryer
- * Date: October 10, 2017
- */
-public class LinearCongruentialGenerator {
-
- private double a, c, m, previousValue;
-
- /***
- * These parameters are saved and used when nextNumber() is called.
- * The current timestamp in milliseconds is used as the seed.
- *
- * @param multiplier
- * @param increment
- * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
- */
- public LinearCongruentialGenerator( double multiplier, double increment, double modulo ) {
- this(System.currentTimeMillis(), multiplier, increment, modulo);
- }
-
- /***
- * These parameters are saved and used when nextNumber() is called.
- *
- * @param seed
- * @param multiplier
- * @param increment
- * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
- */
- public LinearCongruentialGenerator( double seed, double multiplier, double increment, double modulo ) {
- this.previousValue = seed;
- this.a = multiplier;
- this.c = increment;
- this.m = modulo;
- }
-
- /**
- * The smallest number that can be generated is zero.
- * The largest number that can be generated is modulo-1. modulo is set in the constructor.
- * @return a pseudorandom number.
- */
- public double nextNumber() {
- previousValue = (a * previousValue + c) % m;
- return previousValue;
- }
-
- public static void main( String[] args ) {
- // Show the LCG in action.
- // Decisive proof that the LCG works could be made by adding each number
- // generated to a Set while checking for duplicates.
- LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
- for( int i = 0; i < 512; i++ ) {
- System.out.println(lcg.nextNumber());
- }
- }
-}
diff --git a/Others/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java
deleted file mode 100644
index d0df5c30f511..000000000000
--- a/Others/LowestBasePalindrome.java
+++ /dev/null
@@ -1,144 +0,0 @@
-import java.util.InputMismatchException;
-import java.util.Scanner;
-
-/**
- * Class for finding the lowest base in which a given integer is a palindrome.
- * Includes auxiliary methods for converting between bases and reversing strings.
- *
- * NOTE: There is potential for error, see note at line 63.
- *
- * @author RollandMichael
- * @version 2017.09.28
- *
- */
-public class LowestBasePalindrome {
-
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n=0;
- while (true) {
- try {
- System.out.print("Enter number: ");
- n = in.nextInt();
- break;
- } catch (InputMismatchException e) {
- System.out.println("Invalid input!");
- in.next();
- }
- }
- System.out.println(n+" is a palindrome in base "+lowestBasePalindrome(n));
- System.out.println(base2base(Integer.toString(n),10, lowestBasePalindrome(n)));
- }
-
- /**
- * Given a number in base 10, returns the lowest base in which the
- * number is represented by a palindrome (read the same left-to-right
- * and right-to-left).
- * @param num A number in base 10.
- * @return The lowest base in which num is a palindrome.
- */
- public static int lowestBasePalindrome(int num) {
- int base, num2=num;
- int digit;
- char digitC;
- boolean foundBase=false;
- String newNum = "";
- String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- while (!foundBase) {
- // Try from bases 2 to num-1
- for (base=2; base0) {
- // Obtain the first digit of n in the current base,
- // which is equivalent to the integer remainder of (n/base).
- // The next digit is obtained by dividing n by the base and
- // continuing the process of getting the remainder. This is done
- // until n is <=0 and the number in the new base is obtained.
- digit = (num % base);
- num/=base;
- // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
- // form is just its value in ASCII.
-
- // NOTE: This may cause problems, as the capital letters are ASCII values
- // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
- // 'A' from the character array and the other is 65 and also assigned 'A'.
-
- // Regardless, the character is added to the representation of n
- // in the current base.
- if (digit>=digits.length()) {
- digitC=(char)(digit);
- newNum+=digitC;
- continue;
- }
- newNum+=digits.charAt(digit);
- }
- // Num is assigned back its original value for the next iteration.
- num=num2;
- // Auxiliary method reverses the number.
- String reverse = reverse(newNum);
- // If the number is read the same as its reverse, then it is a palindrome.
- // The current base is returned.
- if (reverse.equals(newNum)) {
- foundBase=true;
- return base;
- }
- }
- }
- // If all else fails, n is always a palindrome in base n-1. ("11")
- return num-1;
- }
-
- private static String reverse(String str) {
- String reverse = "";
- for(int i=str.length()-1; i>=0; i--) {
- reverse += str.charAt(i);
- }
- return reverse;
- }
-
- private static String base2base(String n, int b1, int b2) {
- // Declare variables: decimal value of n,
- // character of base b1, character of base b2,
- // and the string that will be returned.
- int decimalValue = 0, charB2;
- char charB1;
- String output="";
- // Go through every character of n
- for (int i=0; i9 and store it in charB2
- if (charB1 >= 'A' && charB1 <= 'Z')
- charB2 = 10 + (charB1 - 'A');
- // Else, store the integer value in charB2
- else
- charB2 = charB1 - '0';
- // Convert the digit to decimal and add it to the
- // decimalValue of n
- decimalValue = decimalValue * b1 + charB2;
- }
-
- // Converting the decimal value to base b2:
- // A number is converted from decimal to another base
- // by continuously dividing by the base and recording
- // the remainder until the quotient is zero. The number in the
- // new base is the remainders, with the last remainder
- // being the left-most digit.
-
- // While the quotient is NOT zero:
- while (decimalValue != 0) {
- // If the remainder is a digit < 10, simply add it to
- // the left side of the new number.
- if (decimalValue % b2 < 10)
- output = Integer.toString(decimalValue % b2) + output;
- // If the remainder is >= 10, add a character with the
- // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
- else
- output = (char)((decimalValue % b2)+55) + output;
- // Divide by the new base again
- decimalValue /= b2;
- }
- return output;
- }
-}
diff --git a/Others/Node.java b/Others/Node.java
deleted file mode 100644
index ab495b77de01..000000000000
--- a/Others/Node.java
+++ /dev/null
@@ -1,16 +0,0 @@
-public class Node {
- public Object anElement;
- public Node less;
- public Node greater;
-
- public Node(Object theElement) {
- this(theElement, null, null); //an empty node at the end will be by itself with no children, therefore the other 2 parameters are always null
- //obviously the node can still be a child of other elements
- }
-
- public Node(Object currentElement, Node lessSide, Node greaterSide) {
- anElement = currentElement;
- this.less = lessSide;
- this.greater = greaterSide;
- }
-}
diff --git a/Others/Palindrome.java b/Others/Palindrome.java
deleted file mode 100644
index 0bbddb7544c8..000000000000
--- a/Others/Palindrome.java
+++ /dev/null
@@ -1,26 +0,0 @@
-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;
-
- return SecondWay(x.substring(1 , x.length() - 1));
- }
- }
diff --git a/Others/PasswordGen.java b/Others/PasswordGen.java
deleted file mode 100644
index bde0a50fe621..000000000000
--- a/Others/PasswordGen.java
+++ /dev/null
@@ -1,45 +0,0 @@
-import java.util.Collections;
-import java.util.Random;
-import java.util.List;
-import java.util.ArrayList;
-
-/*
- Creates a random password from ASCII letters
- Given password length bounds
-
- author: AKS1996
- date: 2017-10-25
-*/
-
-class PasswordGen {
- public static void main(String args[]){
- String password = generatePassword(8,16);
- System.out.print("Password: " + password);
- }
-
- static String generatePassword(int min_length, int max_length){
- Random random = new Random();
-
- String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- String lower = "abcdefghijklmnopqrstuvwxyz";
- String numbers = "0123456789";
- String specialChars = "!@#$%^&*(){}?";
-
- String allChars = upper+lower+numbers+specialChars;
-
- List letters = new ArrayList();
- for(char c:allChars.toCharArray())
- letters.add(c);
-
- // Inbuilt method to randomly shuffle a elements of a list
- Collections.shuffle(letters);
- String password = "";
-
- // Note that size of the password is also random
- for(int i = random.nextInt(max_length-min_length) + min_length; i>0; --i) {
- password += letters.get(random.nextInt(letters.size()));
- }
-
- return password;
- }
-}
diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java
deleted file mode 100644
index 1d0f795a3a35..000000000000
--- a/Others/PerlinNoise.java
+++ /dev/null
@@ -1,164 +0,0 @@
-import java.util.Random;
-import java.util.Scanner;
-
-/**
- * For detailed info and implementation see: Perlin-Noise
- */
-public class PerlinNoise {
- /**
- * @param width width of noise array
- * @param height height of noise array
- * @param octaveCount numbers of layers used for blending noise
- * @param persistence value of impact each layer get while blending
- * @param seed used for randomizer
- * @return float array containing calculated "Perlin-Noise" values
- */
- static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) {
- final float[][] base = new float[width][height];
- final float[][] perlinNoise = new float[width][height];
- final float[][][] noiseLayers = new float[octaveCount][][];
-
- Random random = new Random(seed);
- //fill base array with random values as base for noise
- for(int x = 0; x < width; x++) {
- for(int y = 0; y < height; y++) {
- base[x][y] = random.nextFloat();
- }
- }
-
- //calculate octaves with different roughness
- for(int octave = 0; octave < octaveCount; octave++) {
- noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave);
- }
-
- float amplitude = 1f;
- float totalAmplitude = 0f;
-
- //calculate perlin noise by blending each layer together with specific persistence
- for(int octave = octaveCount - 1; octave >= 0; octave--) {
- amplitude *= persistence;
- totalAmplitude += amplitude;
-
- for(int x = 0; x < width; x++) {
- for(int y = 0; y < height; y++) {
- //adding each value of the noise layer to the noise
- //by increasing amplitude the rougher noises will have more impact
- perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude;
- }
- }
- }
-
- //normalize values so that they stay between 0..1
- for(int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- perlinNoise[x][y] /= totalAmplitude;
- }
- }
-
- return perlinNoise;
- }
-
- /**
- * @param base base random float array
- * @param width width of noise array
- * @param height height of noise array
- * @param octave current layer
- * @return float array containing calculated "Perlin-Noise-Layer" values
- */
- static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) {
- float[][] perlinNoiseLayer = new float[width][height];
-
- //calculate period (wavelength) for different shapes
- int period = 1 << octave; //2^k
- float frequency = 1f / period; // 1/2^k
-
- for(int x = 0; x < width; x++) {
- //calculates the horizontal sampling indices
- int x0 = (x / period) * period;
- int x1 = (x0 + period) % width;
- float horizintalBlend = (x - x0) * frequency;
-
- for(int y = 0; y < height; y++) {
- //calculates the vertical sampling indices
- int y0 = (y / period) * period;
- int y1 = (y0 + period) % height;
- float verticalBlend = (y - y0) * frequency;
-
- //blend top corners
- float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend);
-
- //blend bottom corners
- float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend);
-
- //blend top and bottom interpolation to get the final blend value for this cell
- perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend);
- }
- }
-
- return perlinNoiseLayer;
- }
-
- /**
- * @param a value of point a
- * @param b value of point b
- * @param alpha determine which value has more impact (closer to 0 -> a, closer to 1 -> b)
- * @return interpolated value
- */
- static float interpolate(float a, float b, float alpha) {
- return a * (1 - alpha) + alpha * b;
- }
-
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
-
- final int width;
- final int height;
- final int octaveCount;
- final float persistence;
- final long seed;
- final String charset;
- final float[][] perlinNoise;
-
- System.out.println("Width (int): ");
- width = in.nextInt();
-
- System.out.println("Height (int): ");
- height = in.nextInt();
-
- System.out.println("Octave count (int): ");
- octaveCount = in.nextInt();
-
- System.out.println("Persistence (float): ");
- persistence = in.nextFloat();
-
- System.out.println("Seed (long): ");
- seed = in.nextLong();
-
- System.out.println("Charset (String): ");
- charset = in.next();
-
-
- perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed);
- final char[] chars = charset.toCharArray();
- final int length = chars.length;
- final float step = 1f / length;
- //output based on charset
- for(int x = 0; x < width; x++) {
- for(int y = 0; y < height; y++) {
- float value = step;
- float noiseValue = perlinNoise[x][y];
-
- for (char c : chars) {
- if (noiseValue <= value) {
- System.out.print(c);
- break;
- }
-
- value += step;
- }
- }
-
- System.out.println();
- }
- }
-}
diff --git a/Others/PowerOfTwoOrNot.java b/Others/PowerOfTwoOrNot.java
deleted file mode 100644
index 36facfeddb76..000000000000
--- a/Others/PowerOfTwoOrNot.java
+++ /dev/null
@@ -1,33 +0,0 @@
-import java.util.Scanner;
-
-/**
-*A utility to check if a given number is power of two or not.
-*For example 8,16 etc.
-*/
-public class PowerOfTwoOrNot {
-
- public static void main (String[] args) {
-
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the number");
- int num = sc.nextInt();
- boolean isPowerOfTwo = checkIfPowerOfTwoOrNot(num);
- if (isPowerOfTwo) {
- System.out.println("Number is a power of two");
- } else {
- System.out.println("Number is not a power of two");
- }
- }
-
-
-/**
-* Checks whether given number is power of two or not.
-*
-* @param number
-* @return boolean
-*/
-public static boolean checkIfPowerOfTwoOrNot(int number) {
- return number != 0 && ((number & (number-1)) == 0);
- }
-
-}
diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java
deleted file mode 100644
index 271c35c1859d..000000000000
--- a/Others/QueueUsingTwoStacks.java
+++ /dev/null
@@ -1,158 +0,0 @@
-import java.util.Stack;
-
-/**
- * This implements Queue using two Stacks.
- *
- * Big O Runtime:
- * insert(): O(1)
- * remove(): O(1) amortized
- * isEmpty(): O(1)
- *
- * 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 sahilb2 (https://www.github.com/sahilb2)
- *
- */
-class QueueWithStack {
-
- // Stack to keep track of elements inserted into the queue
- private Stack inStack;
- // Stack to keep track of elements to be removed next in queue
- private Stack outStack;
-
- /**
- * Constructor
- */
- public QueueWithStack() {
- this.inStack = new Stack();
- this.outStack = new Stack();
- }
-
- /**
- * Inserts an element at the rear of the queue
- *
- * @param x element to be added
- */
- public void insert(Object x) {
- // Insert element into inStack
- this.inStack.push(x);
- }
-
- /**
- * Remove an element from the front of the queue
- *
- * @return the new front of the queue
- */
- public Object remove() {
- if(this.outStack.isEmpty()) {
- // Move all elements from inStack to outStack (preserving the order)
- while(!this.inStack.isEmpty()) {
- this.outStack.push( this.inStack.pop() );
- }
- }
- return this.outStack.pop();
- }
-
- /**
- * Peek at the element from the front of the queue
- *
- * @return the front element of the queue
- */
- public Object peekFront() {
- if(this.outStack.isEmpty()) {
- // Move all elements from inStack to outStack (preserving the order)
- while(!this.inStack.isEmpty()) {
- this.outStack.push( this.inStack.pop() );
- }
- }
- return this.outStack.peek();
- }
-
- /**
- * Peek at the element from the back of the queue
- *
- * @return the back element of the queue
- */
- public Object peekBack() {
- return this.inStack.peek();
- }
-
- /**
- * Returns true if the queue is empty
- *
- * @return true if the queue is empty
- */
- public boolean isEmpty() {
- return (this.inStack.isEmpty() && this.outStack.isEmpty());
- }
-
-}
-
-/**
- * This class is the example for the Queue class
- *
- * @author sahilb2 (https://www.github.com/sahilb2)
- *
- */
-public class QueueUsingTwoStacks {
-
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]){
- QueueWithStack myQueue = new QueueWithStack();
- myQueue.insert(1);
- System.out.println(myQueue.peekBack()); //Will print 1
- // instack: [(top) 1]
- // outStack: []
- myQueue.insert(2);
- System.out.println(myQueue.peekBack()); //Will print 2
- // instack: [(top) 2, 1]
- // outStack: []
- myQueue.insert(3);
- System.out.println(myQueue.peekBack()); //Will print 3
- // instack: [(top) 3, 2, 1]
- // outStack: []
- myQueue.insert(4);
- System.out.println(myQueue.peekBack()); //Will print 4
- // instack: [(top) 4, 3, 2, 1]
- // outStack: []
-
- System.out.println(myQueue.isEmpty()); //Will print false
-
- System.out.println(myQueue.remove()); //Will print 1
- System.out.println(myQueue.peekBack()); //Will print NULL
- // instack: []
- // outStack: [(top) 2, 3, 4]
-
- myQueue.insert(5);
- System.out.println(myQueue.peekFront()); //Will print 2
- // instack: [(top) 5]
- // outStack: [(top) 2, 3, 4]
-
- myQueue.remove();
- System.out.println(myQueue.peekFront()); //Will print 3
- // instack: [(top) 5]
- // outStack: [(top) 3, 4]
- myQueue.remove();
- System.out.println(myQueue.peekFront()); //Will print 4
- // instack: [(top) 5]
- // outStack: [(top) 4]
- myQueue.remove();
- // instack: [(top) 5]
- // outStack: []
- System.out.println(myQueue.peekFront()); //Will print 5
- // instack: []
- // outStack: [(top) 5]
- myQueue.remove();
- // instack: []
- // outStack: []
-
- System.out.println(myQueue.isEmpty()); //Will print true
-
- }
-}
diff --git a/Others/ReturnSubsequence.java b/Others/ReturnSubsequence.java
deleted file mode 100644
index ef3aaed09dd9..000000000000
--- a/Others/ReturnSubsequence.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
-This program will return all the subsequences of the input string in a string array;
-Sample Input:
-abc
-Sample Output:
-"" ( Empty String )
-c
-b
-bc
-a
-ac
-ab
-abc
-
- */
-
-import java.util.Scanner;
-
-public class ReturnSubsequence {
- /*
- Main function will accept the given string and implement return subsequences function
- */
- public static void main(String[] args) {
- System.out.println("Enter String: ");
- Scanner s=new Scanner(System.in);
- String givenString=s.next(); //given string
- String[] subsequence=returnSubsequence(givenString); //calling returnSubsequence() function
- System.out.println("Subsequences : ");
- for(int i=0;i stack=new Stack<>();
-
- //Main function
- public static void main(String[] args) {
- //To Create a Dummy Stack containing integers from 0-9
- for(int i=0;i<10;i++)
- {
- stack.push(i);
- }
- System.out.println("STACK");
-
- //To print that dummy Stack
- for(int k=9;k>=0;k--)
- {
- System.out.println(k);
- }
-
- //Reverse Function called
- reverseUsingRecursion(stack);
-
- System.out.println("REVERSED STACK : ");
- //To print reversed stack
- while (!stack.isEmpty())
- {
- System.out.println(stack.pop());
- }
-
-
- }
-
- //Function Used to reverse Stack Using Recursion
- private static void reverseUsingRecursion(Stack stack) {
- if(stack.isEmpty()) // If stack is empty then return
- {
- return;
- }
- /* All items are stored in call stack until we reach the end*/
-
- int temptop=stack.peek();
- stack.pop();
- reverseUsingRecursion(stack); //Recursion call
- insertAtEnd(temptop); // Insert items held in call stack one by one into stack
- }
-
- //Function used to insert element at the end of stack
- private static void insertAtEnd(int temptop) {
- if(stack.isEmpty())
- {
- stack.push(temptop); // If stack is empty push the element
- }
- else {
- int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
- stack.pop();
-
- insertAtEnd(temptop); //Recursive call
-
- stack.push(temp);
- }
-
- }
-
-}
diff --git a/Others/ReverseString.java b/Others/ReverseString.java
deleted file mode 100644
index 9f4d9775bb43..000000000000
--- a/Others/ReverseString.java
+++ /dev/null
@@ -1,46 +0,0 @@
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-/**
- * This method produces a reversed version of a string
- *
- * @author Unknown
- *
- */
-class ReverseString
-{
-
- /**
- * This method reverses the string str and returns it
- * @param str String to be reversed
- * @return Reversed string
- */
- public static String reverse(String str){
- if(str.isEmpty() || str == null) return str;
-
- char arr[] = str.toCharArray();
- for(int i = 0, j = str.length() - 1; i < j; i++, j--){
- char temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- return new String(arr);
- }
-
- /**
- * Main Method
- *
- * @param args Command line arguments
- * @throws IOException Exception thrown because of BufferedReader
- */
- public static void main(String args[]) throws IOException
- {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- System.out.println("Enter the string");
- String srr=br.readLine();
- System.out.println("Reverse="+reverse(srr));
- br.close();
- }
-}
-
diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java
deleted file mode 100644
index b792d692f675..000000000000
--- a/Others/RootPrecision.java
+++ /dev/null
@@ -1,33 +0,0 @@
-import java.io.*;
-import java.util.*;
-import java.text.*;
-import java.math.*;
-import java.util.regex.*;
-
-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
-
- 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;
- }
-}
diff --git a/Others/SieveOfEratosthenes.java b/Others/SieveOfEratosthenes.java
deleted file mode 100644
index 4b6fd5b78491..000000000000
--- a/Others/SieveOfEratosthenes.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-public class SieveOfEratosthenes {
-
- /**
- * This method implements the Sieve of Eratosthenes Algorithm
- *
- * @param n The number till which we have to check for prime
- * Prints all the prime numbers till n
- **/
-
- public static void findPrimesTillN(int n) {
- int[] arr = new int[n+1];
-
- for (int i=0;i<=n;i++) {
- arr[i] = 1;
- }
-
- arr[0] = arr[1] = 0;
-
- for (int i=2;i<=Math.sqrt(n);i++) {
- if (arr[i] == 1) {
- for (int j=2;i*j <= n;j++) {
- arr[i*j] = 0;
- }
- }
- }
-
- for (int i=0;i s = new Stack ();
- Scanner tokens = new Scanner(exp);
-
- while (tokens.hasNext()) {
- if (tokens.hasNextInt()) {
- s.push(tokens.nextInt()); // If int then push to stack
- } else { // else pop top two values and perform the operation
- int num2 = s.pop();
- int num1 = s.pop();
- String op = tokens.next();
-
- if (op.equals("+")) {
- s.push(num1 + num2);
- } else if (op.equals("-")) {
- s.push(num1 - num2);
- } else if (op.equals("*")) {
- s.push(num1 * num2);
- } else {
- s.push(num1 / num2);
- }
-
- // "+", "-", "*", "/"
- }
- }
- return s.pop();
- }
-}
diff --git a/Others/TowerOfHanoiUsingRecursion.java b/Others/TowerOfHanoiUsingRecursion.java
deleted file mode 100644
index b5ee7ad71e10..000000000000
--- a/Others/TowerOfHanoiUsingRecursion.java
+++ /dev/null
@@ -1,26 +0,0 @@
-import java.util.Scanner;
-
-class TowerOfHanoi
-{
- public static void shift(int n, String startPole, String intermediatePole, String endPole)
- {
- if (n == 0) // if n becomes zero the program returns thus ending the loop.
- {
- return;
- }
-
-
- // Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
- shift(n - 1, startPole, endPole, intermediatePole);
- System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
- // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
- shift(n - 1, intermediatePole, startPole, endPole);
- }
- public static void main(String[] args)
- {
- System.out.print("Enter number of discs on Pole 1: ");
- Scanner scanner = new Scanner(System.in);
- int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
- shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
- }
-}
diff --git a/Others/countwords.java b/Others/countwords.java
deleted file mode 100644
index a93aa1a33833..000000000000
--- a/Others/countwords.java
+++ /dev/null
@@ -1,26 +0,0 @@
-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
- *
- */
- 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();
- }
-
- private static int wordCount(String s){
- if(s.isEmpty() || s == null) return 0;
- return s.trim().split("[\\s]+").length;
- }
-
- }
diff --git a/Others/crc32.java b/Others/crc32.java
deleted file mode 100644
index e27c247062d4..000000000000
--- a/Others/crc32.java
+++ /dev/null
@@ -1,27 +0,0 @@
-import java.util.BitSet;
-
-//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
- else
- crc32 = (crc32 << 1);
- }
- crc32 = Integer.reverse(crc32); //result reflect
- return crc32 ^ 0xFFFFFFFF; //final xor value
- }
-
-}
diff --git a/Others/krishnamurthy.java b/Others/krishnamurthy.java
deleted file mode 100644
index 52480eb09722..000000000000
--- a/Others/krishnamurthy.java
+++ /dev/null
@@ -1,28 +0,0 @@
-import java.util.Scanner;
-
-class krishnamurthy {
- static int fact(int n) {
- int i, p = 1;
- for (i = n; i >= 1; i--)
- p = p * i;
- return p;
- }
-
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int a, b, s = 0;
- System.out.print("Enter the number : ");
- a = sc.nextInt();
- int n = a;
- while (a > 0) {
- b = a % 10;
- s = s + fact(b);
- a = a / 10;
- }
- if (s == n)
- System.out.print(n + " is a krishnamurthy number");
- else
- System.out.print(n + " is not a krishnamurthy number");
- sc.close();
- }
-}
diff --git a/Others/removeDuplicateFromString.java b/Others/removeDuplicateFromString.java
deleted file mode 100644
index ce8f3499cede..000000000000
--- a/Others/removeDuplicateFromString.java
+++ /dev/null
@@ -1,45 +0,0 @@
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-public class removeDuplicateFromString {
- public static void main (String[] args) throws Exception{
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String inp_str = br.readLine();
-
- System.out.println("Actual string is: " + inp_str);
- System.out.println("String after removing duplicates: " + removeDuplicate(inp_str));
-
- br.close();
- }
-
- /**
- * This method produces a string after removing all the duplicate characters from input string and returns it
- * Example: Input String - "aabbbccccddddd"
- * Output String - "abcd"
- * @param s String from which duplicate characters have to be removed
- * @return string with only unique characters
- */
-
- public static String removeDuplicate(String s) {
- if(s.isEmpty() || s == null) {
- return s;
- }
-
- StringBuilder sb = new StringBuilder("");
- int n = s.length();
-
- for (int i = 0; i < n; i++) {
- if (sb.toString().indexOf(s.charAt(i)) == -1) {
- sb.append(String.valueOf(s.charAt(i)));
- }
- }
-
- return sb.toString();
- }
-}
diff --git a/README-ko.md b/README-ko.md
new file mode 100644
index 000000000000..4f8cab92fc42
--- /dev/null
+++ b/README-ko.md
@@ -0,0 +1,191 @@
+# 알고리즘 - 자바
+
+## 이 [개발브런치](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](DynamicProgramming/CoinChange.java) | [Caesar](Ciphers/Caesar.java) | [Heap Sort](Sorts/HeapSort.java) |
+| [Any Base to Decimal](Conversions/AnyBaseToDecimal.java) | [Egg Dropping](DynamicProgramming/EggDropping.java) | [Columnar Transposition Cipher](Ciphers/ColumnarTranspositionCipher.java) | [Palindromic Prime Checker](Misc/PalindromePrime.java) |
+| [Binary to Decimal](Conversions/BinaryToDecimal.java) | [Fibonacci](DynamicProgramming/Fibonacci.java) | [RSA](Ciphers/RSA.java) | More soon... |
+| [Binary to HexaDecimal](Conversions/BinaryToHexadecimal.java) | [Kadane Algorithm](DynamicProgramming/KadaneAlgorithm.java) | more coming soon... |
+| [Binary to Octal](Conversions/BinaryToOctal.java) | [Knapsack](DynamicProgramming/Knapsack.java) |
+| [Decimal To Any Base](Conversions/DecimalToAnyBase.java) | [Longest Common Subsequence](DynamicProgramming/LongestCommonSubsequence.java) |
+| [Decimal To Binary](Conversions/DecimalToBinary.java) | [Longest Increasing Subsequence](DynamicProgramming/LongestIncreasingSubsequence.java) |
+| [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java) | [Rod Cutting](DynamicProgramming/RodCutting.java) |
+| and much more... | and more... |
+
+### 자료 구조
+
+| 그래프 | 힙 | 리스트 | 큐 |
+| ------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| | [빈 힙 예외처리](DataStructures/Heaps/EmptyHeapException.java) | [원형 연결리스트](DataStructures/Lists/CircleLinkedList.java) | [제너릭 어레이 리스트 큐](DataStructures/Queues/GenericArrayListQueue.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/Kruskal.java) | [최대힙](DataStructures/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/Hashing/HashMap.java)
+-
diff --git a/README.md b/README.md
index 80216abc44a4..d60d5104c385 100644
--- a/README.md
+++ b/README.md
@@ -1,193 +1,20 @@
-# The Algorithms - Java [](https://travis-ci.org/TheAlgorithms/Python)
+# The Algorithms - Java
-### All algorithms implemented in Java (for education)
+[](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml)
+[](https://codecov.io/gh/TheAlgorithms/Java)
+[](https://discord.gg/c7MnfGFGa6)
+[](https://gitpod.io/#https://github.com/TheAlgorithms/Java)
-These are for demonstration purposes only. There are many implementations of sorts in the Java standard library that are much better for performance reasons.
-## Sort Algorithms
+You can run and edit the algorithms, or contribute to them using Gitpod.io (a free online development environment) with a single click.
+[](https://gitpod.io/#https://github.com/TheAlgorithms/Java)
-### Bubble
-![alt text][bubble-image]
+### All algorithms are implemented in Java (for educational purposes)
+These implementations are intended for learning purposes. As such, they may be less efficient than the Java standard library.
-From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
+## Contribution Guidelines
+Please read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute to this project.
-__Properties__
-* Worst case performance O(n^2)
-* Best case performance O(n)
-* Average case performance O(n^2)
-
-###### View the algorithm in [action][bubble-toptal]
-
-
-
-### Insertion
-![alt text][insertion-image]
-
-From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
-
-__Properties__
-* Worst case performance O(n^2)
-* Best case performance O(n)
-* Average case performance O(n^2)
-
-###### View the algorithm in [action][insertion-toptal]
-
-
-### Merge
-![alt text][merge-image]
-
-From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelt mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
-
-__Properties__
-* Worst case performance O(n log n) (typical)
-* Best case performance O(n log n)
-* Average case performance O(n log n)
-
-
-###### View the algorithm in [action][merge-toptal]
-
-### Quick
-![alt text][quick-image]
-
-From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order.
-
-__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)
-
-###### View the algorithm in [action][quick-toptal]
-
-### Selection
-![alt text][selection-image]
-
-From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
-
-__Properties__
-* Worst case performance O(n^2)
-* Best case performance O(n^2)
-* Average case performance O(n^2)
-
-###### View the algorithm in [action][selection-toptal]
-
-### Shell
-![alt text][shell-image]
-
-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]
-
-### Time-Compexity Graphs
-
-Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort)
-
-[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png)
-
-----------------------------------------------------------------------------------
-
-## Search Algorithms
-
-### Linear
-![alt text][linear-image]
-
-From [Wikipedia][linear-wiki]: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.
- The linear search runs in at the worst linear time and makes at most n comparisons, where n is the length of the list.
-
-__Properties__
-* Worst case performance O(n)
-* Best case performance O(1)
-* Average case performance O(n)
-* Worst case space complexity O(1) iterative
-
-### Binary
-![alt text][binary-image]
-
-From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.
-
-__Properties__
-* Worst case performance O(log n)
-* Best case performance O(1)
-* 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]
-
-[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
-
-
---------------------------------------------------------------------
-## Links to the rest of the algorithms
-
-Conversions | Dynamic Programming |Ciphers|Miscellaneous|
------------ |----------------------------------------------------------------|-------|-------------|
-[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...|
-
-### 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)|
-
-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)
+## Algorithms
+Our [directory](DIRECTORY.md) has the full list of applications.
diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java
deleted file mode 100644
index 535442c87409..000000000000
--- a/Searches/BinarySearch.java
+++ /dev/null
@@ -1,71 +0,0 @@
-import java.util.Scanner;
-
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-class BinarySearch
-{
- /**
- * This method implements the Generic Binary Search
- *
- * @param array The array to make the binary search
- * @param key The number you are looking for
- * @param lb The lower bound
- * @param ub The upper bound
- * @return the location of the key
- **/
-
- public static > int BS(T array[], T key, int lb, int ub)
- {
- if ( lb > ub)
- return -1;
-
- int mid = (ub+lb) >>> 1;
- int comp = key.compareTo(array[mid]);
-
- if (comp < 0)
- return (BS(array, key, lb, mid-1));
-
- if (comp > 0)
- return (BS(array, key, mid + 1, ub));
-
- return mid;
- }
-
- // Driver Program
- public static void main(String[] args)
- {
- Scanner input=new Scanner(System.in);
-
- // For INTEGER Input
- Integer[] array = new Integer[10];
- int key = 5;
-
- for (int i = 0; i < 10 ; i++ )
- array[i] = i+1;
-
- int index = BS(array, key, 0, 9);
-
- if (index != -1)
- System.out.println("Number " + key + " found at index number : " + index);
- else
- System.out.println("Not found");
-
-
- // For STRING Input
- String[] array1 = {"a", "b", "c", "d", "e"};
- String key1 = "d";
-
- int index1 = BS(array1, key1, 0, array1.length-1);
-
- if (index1 != -1)
- System.out.println("String " + key1 + " found at index number : " + index1);
- else
- System.out.println("Not found");
-
- input.close();
- }
-}
diff --git a/Searches/LinearSearch.java b/Searches/LinearSearch.java
deleted file mode 100644
index 6c5322520ac6..000000000000
--- a/Searches/LinearSearch.java
+++ /dev/null
@@ -1,77 +0,0 @@
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-public class LinearSearch{
- /**
- * The main method
- * @param args Command line arguments
- */
- public static void main(String[] args) throws Exception {
-
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
-
- // Test for Integer inputs
- Integer[] myArray;
- int size = 0;
-
- //Prompt user to create array and its elements
- System.out.print("Enter the array size: ");
- size = Integer.parseInt(br.readLine());
- myArray = new Integer[size];
- for (int i = 0; i < size; i++){
- System.out.print("For index " + i + ", enter an integer: ");
- myArray[i] = Integer.parseInt(br.readLine());
- }
-
- //Prompt user to search for particular element
- System.out.print("Enter integer to search for: ");
- Integer key = Integer.parseInt(br.readLine());
-
- //Output array and index of target element, if found
- System.out.printf("The integer %d is found in index %d\n", key, linearSearch(myArray, key));
-
- // Test for String inputs
- String[] myArray1;
- int size1 = 0;
-
- //Prompt user to create array and its elements
- System.out.print("Enter the array size: ");
- size1 = Integer.parseInt(br.readLine());
- myArray1 = new String[size];
- for (int i = 0; i < size1; i++){
- System.out.print("For index " + i + ", enter a String: ");
- myArray1[i] = br.readLine();
- }
-
- //Prompt user to search for particular element
- System.out.print("Enter String to search for: ");
- String key1 = br.readLine();
-
- //Output array and index of target element, if found
- System.out.printf("The string %s is found in index %d\n", key1, linearSearch(myArray1, key1));
- }
-
- /**
- * Generic Linear search method
- *
- * @param array List to be searched
- * @param value Key being searched for
- * @return Location of the key
- */
- public static > int linearSearch(T[] array, T value) {
- int lo = 0;
- int hi = array.length - 1;
- for (int i = lo; i <= hi; i++) {
- if (array[i].compareTo(value) == 0) {
- return i;
- }
- }
- return -1;
- }
-}
diff --git a/Searches/SaddlebackSearch.java b/Searches/SaddlebackSearch.java
deleted file mode 100644
index f118625dcf4f..000000000000
--- a/Searches/SaddlebackSearch.java
+++ /dev/null
@@ -1,84 +0,0 @@
-import java.util.*;
-
-/**
- * Program to perform Saddleback Search
- * Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order)
- * of size n*m we can search a given element in O(n+m)
- *
- * we start from bottom left corner
- * if the current element is greater than the given element then we move up
- * else we move right
- * Sample Input:
- * 5 5 ->Dimensions
- * -10 -5 -3 4 9
- * -6 -2 0 5 10
- * -4 -1 1 6 12
- * 2 3 7 8 13
- * 100 120 130 140 150
- * 140 ->element to be searched
- * output: 4 3 // first value is row, second one is column
- *
- * @author Nishita Aggarwal
- *
- */
-
-public class SaddlebackSearch {
-
- /**
- * This method performs Saddleback Search
- *
- * @param arr The **Sorted** array in which we will search the element.
- * @param crow the current row.
- * @param ccol the current column.
- * @param ele the element that we want to search for.
- *
- * @return The index(row and column) of the element if found.
- * Else returns -1 -1.
- */
- static int[] search(int arr[][],int crow,int ccol,int ele){
-
- //array to store the answer row and column
- int ans[]={-1,-1};
- if(crow<0 || ccol>=arr[crow].length){
- return ans;
- }
- if(arr[crow][ccol]==ele)
- {
- ans[0]=crow;
- ans[1]=ccol;
- return ans;
- }
- //if the current element is greater than the given element then we move up
- else if(arr[crow][ccol]>ele)
- {
- return search(arr,crow-1,ccol,ele);
- }
- //else we move right
- return search(arr,crow,ccol+1,ele);
- }
-
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc=new Scanner(System.in);
- int arr[][];
- int i,j,rows=sc.nextInt(),col=sc.nextInt();
- arr=new int[rows][col];
- for(i=0;i end){
- return -1;
- }
- /* First boundary: add 1/3 of length to start */
- int mid1 = start + (end - start) / 3;
- /* Second boundary: add 2/3 of length to start */
- int mid2 = start + 2 * (end - start) / 3;
- if (arr[mid1] == key) {
- return mid1;
- }
- else if (arr[mid2] == key) {
- return mid2;
- }
-
- /* Search the first (1/3) rd part of the array.*/
-
- else if (key < arr[mid1]) {
- return ternarySearch(arr, key, start, mid1 - 1);
- }
- /* Search 3rd (1/3)rd part of the array */
-
- else if (key > arr[mid2]) {
- return ternarySearch(arr, key, mid2 + 1, end);
- }
- /* Search middle (1/3)rd part of the array */
-
- else {
- return ternarySearch(arr, key, mid1, mid2);
- }
- }
-
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in);
- System.out.println("Enter number of elements in the array");
- int n = s.nextInt();
- int arr[] = new int[n];
- System.out.println("Enter the elements of the Sorted array");
- for (int i= 0; i < n; i++){
- arr[i] = s.nextInt();
- }
- System.out.println("Enter element to search for : ");
- int k = s.nextInt();
- int ans = ternarySearch(arr, k);
- if (ans == -1) {
- System.out.println(" The element is not present in the array.");
- }
- else {
- System.out.println("The element is present at the position " + (ans+1));
- }
- }
-}
\ No newline at end of file
diff --git a/Searches/interpolationSearch.java b/Searches/interpolationSearch.java
deleted file mode 100644
index b8041ae6cf16..000000000000
--- a/Searches/interpolationSearch.java
+++ /dev/null
@@ -1,53 +0,0 @@
-
-class Test
-{
- // Array of items on which search will
- // be conducted.
- static int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
- 24, 33, 35, 42, 47};
-
- // If x is present in arr[0..n-1], then returns
- // index of it, else returns -1.
- static int interpolationSearch(int x)
- {
- // Find indexes of two corners
- int lo = 0, hi = (arr.length - 1);
-
- // Since array is sorted, an element present
- // in array must be in range defined by corner
- while (lo <= hi && x >= arr[lo] && x <= arr[hi])
- {
- // Probing the position with keeping
- // uniform distribution in mind.
- int pos = lo + (((hi-lo) /
- (arr[hi]-arr[lo]))*(x - arr[lo]));
-
- // Condition of target found
- if (arr[pos] == x)
- return pos;
-
- // If x is larger, x is in upper part
- if (arr[pos] < x)
- lo = pos + 1;
-
- // If x is smaller, x is in lower part
- else
- hi = pos - 1;
- }
- return -1;
- }
-
- // Driver method
- public static void main(String[] args)
- {
- int x = 18; // Element to be searched
- int index = interpolationSearch(x);
-
- // If element was found
- if (index != -1)
- System.out.println("Element found at index " + index);
- else
- System.out.println("Element not found.");
- }
-}
-
diff --git a/Sorts/BinaryTreeSort.java b/Sorts/BinaryTreeSort.java
deleted file mode 100644
index e6a80f62abdc..000000000000
--- a/Sorts/BinaryTreeSort.java
+++ /dev/null
@@ -1,80 +0,0 @@
-import java.util.Arrays;
-public class TreeSort {
-
- public Node root;
-
- public TreeSort(Object x) {
- root = new Node(x);
- }//end TreeSort constructor
-
- public Node insert(Node node, Integer x) {
- if (node == null) {
- return node = new Node(x);
- }//end if
- if (x < (Integer) node.anElement) {
- node.less = insert(node.less, x);
- } //end if
- else {
- node.greater = insert(node.greater, x);
- }//end else
- return node;
- }//end insert
-
-
- public Node decimalInsert(Node node, Double x) {
- if (node == null) {
- return node = new Node(x);
- }//end if
- if (x < (Double) node.anElement) {
- node.less = decimalInsert(node.less, x);
- } //end if
- else {
- node.greater = decimalInsert(node.greater, x);
- }//end else
- return node;
- }//end insert
-
-
- public void treeSort(Node node) {
- if (node != null) {
- treeSort(node.less);
- System.out.print(((Object) node.anElement) + ", ");
- treeSort(node.greater);
- }//end if
- }//end TreeSort class
-
-
-
-public static void main(String args[]) {
- int[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12 };
- TreeSort ts = new TreeSort(new Integer(intArray[0]));
- for (int i = 1; i < intArray.length; i++) { //sorts every index of the list one at a time
- ts.insert(ts.root, new Integer(intArray[i])); //builds on the tree from a root node
- }//end for
- System.out.print("Integer Array Sorted in Increasing Order: ");
- ts.treeSort(ts.root);
- System.out.println(); //To sort a test array of integers
-
- Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6};
- TreeSort dts = new TreeSort(new Double(decimalArray[0]).doubleValue());
- for (int i = 1; i < decimalArray.length; i++) { //sorts every index of the list one at a time
- dts.decimalInsert(dts.root, new Double(decimalArray[i]).doubleValue()); //builds on the tree from a root node
- }//end for
- System.out.print("Decimal Array, Sorted in Increasing Order: ");
- dts.treeSort(dts.root);
- System.out.println();
-
- String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"};
- int last = stringArray.length;
- Arrays.sort(stringArray); //Uses an imported arrays method to automatically alphabetize
- System.out.print("String Array Sorted in Alphabetical Order: ");
- ts.insert(ts.root, last);
- for(int i=0; i void swap(T array[], int first, int second){
- T randomElement = array[first];
- array[first] = array[second];
- array[second] = randomElement;
- }
-
- private static > boolean isSorted(T array[]){
- for(int i = 0; i 0) return false;
- }
- return true;
- }
-
- // Randomly shuffles the array
- private static void nextPermutation(T array[]){
- int length = array.length;
- Random random = new Random();
-
- for (int i = 0; i < array.length; i++) {
- int randomIndex = i + random.nextInt(length - i);
- swap(array, randomIndex, i);
- }
- }
-
- public static > void bogoSort(T array[]) {
- while(!isSorted(array)){
- nextPermutation(array);
- }
- }
-
- // Driver Program
- public static void main(String[] args)
- {
- // Integer Input
- int[] arr1 = {4,23,6,78,1,54,231,9,12};
- int last = arr1.length;
- Integer[] array = new Integer[last];
- for (int i=0;i 1 4 6 9 12 23 54 78 231
- for(int i=0; i a b c d e
- for(int i=0; i> void BS(T array[], int last) {
- //Sorting
- boolean swap;
- do
- {
- swap = false;
- for (int count = 0; count < last-1; count++)
- {
- int comp = array[count].compareTo(array[count + 1]);
- if (comp > 0)
- {
- T temp = array[count];
- array[count] = array[count + 1];
- array[count + 1] = temp;
- swap = true;
- }
- }
- last--;
- } while (swap);
- }
-
- // Driver Program
- public static void main(String[] args)
- {
- // Integer Input
- int[] arr1 = {4,23,6,78,1,54,231,9,12};
- int last = arr1.length;
- Integer[] array = new Integer[last];
- for (int i=0;i 1 4 6 9 12 23 54 78 231
- for(int i=0; i a b c d e
- for(int i=0; i> void CS(T array[], int last) {
-
- // Sorting
- boolean swap;
- do {
- swap = false;
-
- //front
- for (int count = 0; count <= last - 2; count++) {
- int comp = array[count].compareTo(array[count + 1]);
- if (comp > 0) {
- T aux = array[count];
- array[count] = array[count + 1];
- array[count + 1] = aux;
- swap = true;
- }
- }
- //break if no swap occurred
- if (!swap) {
- break;
- }
- swap = false;
-
- //back
- for (int count = last - 2; count >= 0; count--) {
- int comp = array[count].compareTo(array[count + 1]);
- if (comp > 0) {
- T aux = array[count];
- array[count] = array[count + 1];
- array[count + 1] = aux;
- swap = true;
- }
- }
- last--;
- //end
- } while (swap);
- }
-
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 };
- int last = arr1.length;
- Integer[] array = new Integer[last];
- for (int i = 0; i < last; i++) {
- array[i] = arr1[i];
- }
-
- CS(array, last);
-
- // Output => 1 4 6 9 12 23 54 78 231
- for (int i = 0; i < last; i++) {
- System.out.print(array[i] + "\t");
- }
- System.out.println();
-
- // String Input
- String[] array1 = { "c", "a", "e", "b", "d" };
- last = array1.length;
-
- CS(array1, last);
-
- // Output => a b c d e
- for (int i = 0; i < last; i++) {
- System.out.print(array1[i] + "\t");
- }
- }
-}
diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java
deleted file mode 100644
index e6828265aef9..000000000000
--- a/Sorts/CountingSort.java
+++ /dev/null
@@ -1,90 +0,0 @@
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- *
- * @author Youssef Ali (https://github.com/youssefAli11997)
- *
- */
-
-class CountingSort {
-
- /**
- * This method implements the Generic Counting Sort
- *
- * @param array The array to be sorted
- * @param last The count of total number of elements in array
- * Sorts the array in increasing order
- * It uses array elements as keys in the frequency map
- **/
-
- public static > void CS(T[] array, int last) {
-
- Map frequency = new TreeMap();
- // The final output array
- ArrayList sortedArray = new ArrayList();
-
- // Counting the frequency of @param array elements
- for(T t : array) {
- try{
- frequency.put(t, frequency.get(t)+1);
- }catch(Exception e){ // new entry
- frequency.put(t, 1);
- }
- }
-
- // Filling the sortedArray
- for(Map.Entry element : frequency.entrySet()) {
- for(int j=0; j 1 4 6 9 12 23 54 78 231
- System.out.println("After Sorting:");
- for (int i=0;i a b c d e
- System.out.println("After Sorting:");
- for(int i=0; i 0) {
- int min = this.getRoot();
- sorted[index] = min;
- index++;
- }
- return sorted;
- }
-
- /**
- * Gets input to sort
- *
- * @return unsorted array of integers to sort
- */
- public static int[] getInput() {
- final int numElements = 6;
- int[] unsorted = new int[numElements];
- Scanner input = new Scanner(System.in);
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for (int i = 0; i < numElements; i++) {
- unsorted[i] = input.nextInt();
- }
- input.close();
- return unsorted;
- }
-
- /**
- * Prints elements in heap
- *
- * @param heap array representing heap
- */
- public static void printData(int[] heap) {
- System.out.println("Sorted Elements:");
- for (int i = 0; i < heap.length; i++) {
- System.out.print(" " + heap[i] + " ");
- }
- }
-
- /**
- * Main method
- *
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- int[] heap = getInput();
- HeapSort data = new HeapSort(heap);
- int[] sorted = data.sort();
- printData(sorted);
- }
-
-}
diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java
deleted file mode 100644
index c77b895f7a9d..000000000000
--- a/Sorts/InsertionSort.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- *
- * @author Varun Upadhyay (https://github.com/varunu28)
- *
- */
-
-class InsertionSort {
-
- /**
- * This method implements the Generic Insertion Sort
- *
- * @param array The array to be sorted
- * @param last The count of total number of elements in array
- * Sorts the array in increasing order
- **/
-
- public static > void IS(T array[], int last) {
- T key;
- for (int j=1;j=0 && key.compareTo(array[i]) < 0) {
- array[i+1] = array[i];
- i--;
- }
- // Placing the key (Card) at its correct position in the sorted subarray
- array[i+1] = key;
- }
- }
-
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- int[] arr1 = {4,23,6,78,1,54,231,9,12};
- int last = arr1.length;
- Integer[] array = new Integer[arr1.length];
- for (int i=0;i 1 4 6 9 12 23 54 78 231
- for (int i=0;i a b c d e
- for(int i=0; i> void MS(T[] arr, T[] temp, int left, int right) {
- if (left < right) {
- int mid = left + (right - left) / 2;
- MS(arr, temp, left, mid);
- MS(arr, temp,mid + 1, right);
- merge(arr, temp, left, mid, right);
- }
-
- }
-
- /**
- * This method implements the merge step of the merge sort
- *
- * @param arr The array to be sorted
- * @param temp The copy of the actual array
- * @param left The first index of the array
- * @param mid The middle index of the array
- * @param right The last index of the array
- * merges two parts of an array in increasing order
- **/
-
- public static > void merge(T[] arr, T[] temp, int left, int mid, int right) {
- for (int i=left;i<=right;i++) {
- temp[i] = arr[i];
- }
-
- int i= left;
- int j = mid + 1;
- int k = left;
-
- while (i<=mid && j<=right) {
- if (temp[i].compareTo(temp[j]) <= 0) {
- arr[k] = temp[i];
- i++;
- }
- else {
- arr[k] = temp[j];
- j++;
- }
- k++;
- }
-
- while (i <= mid) {
- arr[k] = temp[i];
- i++;
- k++;
- }
- }
-
- // Driver program
- public static void main(String[] args) {
-
- // Integer Input
- int[] arr = {4,23,6,78,1,54,231,9,12};
- Integer[] array = new Integer[arr.length];
- for (int i=0;i 1 4 6 9 12 23 54 78 231
- for (int i=0;i a b c d e
- for(int i=0; i> void QS(List list, int left, int right) {
- if (left>=right) { return }
- else
- {
- int pivot = partition(array, left,right);
- QS(list, left, pivot- 1);
- QS(list, pivot + 1, right);
- }
- }
-
- /**
- * This method finds the partition index for an array
- *
- * @param array The array to be sorted
- * @param start The first index of an array
- * @param end The last index of an array
- * Finds the partition index of an array
- **/
-
- public static > int partition(List list, int left, int right) {
- int mid=(left+right)/2;
- T pivot=list.get(mid);
- swap(list,mid,right);
- while(left=0)
- {
- ++left;
- }
- if(left=0)
- {
- --right;
- }
- if(left> void swap(List list, int initial, int fin) {
- E temp= list.get(initial);
- list.set(initial,list.get(fin));
- list.set(fin,temp);
- }
-
- // Driver Program
- public static void main(String[] args) {
-
- // For integer input
- ArrayList array = new ArrayList(9);
- array = {3,4,1,32,0,2,44,111,5};
-
- QS(array, 0, array.size()-1);
-
- //Output => 0 1 2 3 4 5 32 44 111
- for (int i=0;i array1=new ArrayList(5);
- array1 = {"c", "a", "e", "b","d"};
-
- QS(array1, 0,array1.size()-1);
-
- //Output => a b c d e
- for(int i=0; i> void SS(T[] arr, int n) {
-
- for (int i=0;i 1 4 6 9 12 23 54 78 231
- for(int i=0; i a b c d e
- for(int i=0; i= 1) {
- for (int i = h; i < N; i++) {
- for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) {
- exch(array, j, j - h);
- }
- }
-
- h /= 3;
- }
- }
-
- /**
- * Helper method for exchanging places in array
- * @param array The array which elements we want to swap
- * @param i index of the first element
- * @param j index of the second element
- */
- private static void exch(Comparable[] array, int i, int j) {
- Comparable swap = array[i];
- array[i] = array[j];
- array[j] = swap;
- }
-
- /**
- * This method checks if first element is less then the other element
- * @param v first element
- * @param w second element
- * @return true if the first element is less then the second element
- */
- private static boolean less(Comparable v, Comparable w) {
- return v.compareTo(w) < 0;
- }
-
- public static void main(String[] args) {
- // Integer Input
- int[] arr1 = {4,23,6,78,1,54,231,9,12};
- Integer[] array = new Integer[arr1.length];
-
- for (int i=0;i mx)
- mx = arr[i];
- return mx;
- }
-
- static void countSort(int arr[], int n, int exp)
- {
- int output[] = new int[n];
- int i;
- int count[] = new int[10];
- Arrays.fill(count,0);
-
- for (i = 0; i < n; i++)
- count[ (arr[i]/exp)%10 ]++;
-
- for (i = 1; i < 10; i++)
- count[i] += count[i - 1];
-
- for (i = n - 1; i >= 0; i--)
- {
- output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
- count[ (arr[i]/exp)%10 ]--;
- }
-
- for (i = 0; i < n; i++)
- arr[i] = output[i];
- }
-
- static void radixsort(int arr[], int n)
- {
-
- int m = getMax(arr, n);
-
-
- for (int exp = 1; m/exp > 0; exp *= 10)
- countSort(arr, n, exp);
- }
-
-
- static void print(int arr[], int n)
- {
- for (int i=0; i
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ciphers/AES.java b/ciphers/AES.java
deleted file mode 100644
index 0e4bfff98a35..000000000000
--- a/ciphers/AES.java
+++ /dev/null
@@ -1,554 +0,0 @@
-package ciphers;
-
-import java.math.BigInteger;
-import java.util.Scanner;
-
-/* This class is build to demonstrate the
- * apllication of the AES-algorithm on
- * a single 128-Bit block of data.
- * */
-public class AES {
-
- /*
- * Precalculated values for x to the power of 2 in Rijndaels galois field.
- * Used as 'rcon' in during the key expansion.
- */
- private static int[] rcon = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab,
- 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
- 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8,
- 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f,
- 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3,
- 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01,
- 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
- 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
- 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
- 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
- 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
- 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
- 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
- 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
- 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d };
-
- /*
- * Rijndael S-box Substitution table used for encryption in the subBytes
- * step, as well as the key expansion.
- */
- private static int[] sBox = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7,
- 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
- 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7,
- 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A,
- 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC,
- 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85,
- 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6,
- 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D,
- 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E,
- 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
- 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78,
- 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66,
- 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9,
- 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68,
- 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 };
-
- /*
- * Inverse Rijndael S-box Substitution table used for decryption in the
- * subBytesDec step
- */
- private static int[] inverseSBox = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81,
- 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9,
- 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08,
- 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6,
- 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD,
- 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3,
- 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1,
- 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF,
- 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C,
- 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE,
- 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F,
- 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F,
- 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE,
- 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6,
- 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D };
-
- /*
- * Precalculated lookup table for galois field multiplication by 2 used in
- * the MixColums step during encryption.
- */
- private static int[] mult2 = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a,
- 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
- 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62,
- 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86,
- 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa,
- 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce,
- 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2,
- 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d,
- 0x03, 0x01, 0x07, 0x05, 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21,
- 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45,
- 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, 0x9b, 0x99,
- 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd,
- 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1,
- 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5,
- 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5 };
-
- /*
- * Precalculated lookup table for galois field multiplication by 3 used in
- * the MixColums step during encryption.
- */
- private static int[] mult3 = { 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17,
- 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21,
- 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, 0x50, 0x53,
- 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, 0xc5,
- 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff,
- 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9,
- 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b,
- 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86,
- 0x8f, 0x8c, 0x89, 0x8a, 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc,
- 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea,
- 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, 0x5b, 0x58,
- 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e,
- 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34,
- 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02,
- 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a };
-
- /*
- * Precalculated lookup table for galois field multiplication by 9 used in
- * the MixColums step during decryption.
- */
- private static int[] mult9 = { 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65,
- 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7,
- 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, 0xab, 0xa2,
- 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, 0x6d,
- 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb,
- 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72,
- 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c,
- 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf,
- 0x80, 0x89, 0x92, 0x9b, 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19,
- 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0,
- 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, 0x9a, 0x93,
- 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11,
- 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c,
- 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e,
- 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46 };
-
- /*
- * Precalculated lookup table for galois field multiplication by 11 used in
- * the MixColums step during decryption.
- */
- private static int[] mult11 = { 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f,
- 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9,
- 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, 0xcb, 0xc0,
- 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, 0xeb,
- 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61,
- 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc,
- 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e,
- 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2,
- 0x83, 0x88, 0x95, 0x9e, 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38,
- 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5,
- 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, 0x01, 0x0a,
- 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac,
- 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d,
- 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb,
- 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3 };
-
- /*
- * Precalculated lookup table for galois field multiplication by 13 used in
- * the MixColums step during decryption.
- */
- private static int[] mult13 = { 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51,
- 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b,
- 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, 0x6b, 0x66,
- 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, 0x7a,
- 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84,
- 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5,
- 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63,
- 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5,
- 0x86, 0x8b, 0x9c, 0x91, 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b,
- 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a,
- 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, 0xb7, 0xba,
- 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70,
- 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35,
- 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff,
- 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97 };
-
- /*
- * Precalculated lookup table for galois field multiplication by 14 used in
- * the MixColums step during decryption.
- */
- private static int[] mult14 = { 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46,
- 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba,
- 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, 0x3b, 0x35,
- 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, 0xbf,
- 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b,
- 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c,
- 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8,
- 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23,
- 0x09, 0x07, 0x15, 0x1b, 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7,
- 0xf5, 0xfb, 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0,
- 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, 0xec, 0xe2,
- 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, 0x1e,
- 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01,
- 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd,
- 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d };
-
- /*
- * Subroutine of the Rijndael key expansion.
- */
- public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
- String rBytes = t.toString(16);
-
- // Add zero padding
- while (rBytes.length() < 8) {
- rBytes = "0" + rBytes;
- }
-
- // rotate the first 16 bits to the back
- String rotatingBytes = rBytes.substring(0, 2);
- String fixedBytes = rBytes.substring(2);
-
- rBytes = fixedBytes + rotatingBytes;
-
- // apply S-Box to all 8-Bit Substrings
- for (int i = 0; i < 4; i++) {
- String currentByteBits = rBytes.substring(i * 2, (i + 1) * 2);
-
- int currentByte = Integer.parseInt(currentByteBits, 16);
- currentByte = sBox[currentByte];
-
- // add the current rcon value to the first byte
- if (i == 0) {
- currentByte = currentByte ^ rcon[rconCounter];
- }
-
- currentByteBits = Integer.toHexString(currentByte);
-
- // Add zero padding
- while (currentByteBits.length() < 2) {
- currentByteBits = "0" + currentByteBits;
- }
-
- // replace bytes in original string
- rBytes = rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2);
- }
-
- t = new BigInteger(rBytes, 16);
-
- return t;
- }
-
- /*
- * Returns an array of 10 + 1 round keys that are calcualted by using
- * Rijndael key schedule
- */
- public static BigInteger[] keyExpansion(BigInteger initialKey) {
- BigInteger[] roundKeys = { initialKey, new BigInteger("0"), new BigInteger("0"), new BigInteger("0"),
- new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), new BigInteger("0"), new BigInteger("0"),
- new BigInteger("0"), new BigInteger("0"), };
-
- // initialize rcon iteration
- int rconCounter = 1;
-
- for (int i = 1; i < 11; i++) {
-
- // get the previous 32 bits the key
- BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
-
- // split previous key into 8-bit segments
- BigInteger[] prevKey = {
- roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(new BigInteger("10000000000000000", 16)).divide(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(new BigInteger("1000000000000000000000000", 16)).divide(new BigInteger("10000000000000000", 16)),
- roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
- };
-
- // run schedule core
- t = scheduleCore(t, rconCounter);
- rconCounter += 1;
-
- // Calculate partial round key
- BigInteger t0 = t.xor(prevKey[3]);
- BigInteger t1 = t0.xor(prevKey[2]);
- BigInteger t2 = t1.xor(prevKey[1]);
- BigInteger t3 = t2.xor(prevKey[0]);
-
- // Join round key segments
- t2 = t2.multiply(new BigInteger("100000000", 16));
- t1 = t1.multiply(new BigInteger("10000000000000000", 16));
- t0 = t0.multiply(new BigInteger("1000000000000000000000000", 16));
- roundKeys[i] = t0.add(t1).add(t2).add(t3);
-
-
- }
- return roundKeys;
- }
-
- /*
- * Returns a representation of the input 128-bit block as an array of 8-bit
- * integers.
- */
- public static int[] splitBlockIntoCells(BigInteger block) {
-
- int[] cells = new int[16];
- String blockBits = block.toString(2);
-
- // Append leading 0 for full "128-bit" string
- while (blockBits.length() < 128) {
- blockBits = "0" + blockBits;
- }
-
- for (int i = 0; i < 16; i++) {
- String cellBits = blockBits.substring(8 * i, 8 * (i + 1));
- cells[i] = Integer.parseInt(cellBits, 2);
- }
-
- return cells;
- }
-
- /*
- * Returns the 128-bit BigInteger representation of the input of an array of
- * 8-bit integers.
- */
- public static BigInteger mergeCellsIntoBlock(int[] cells) {
-
- String blockBits = "";
- for (int i = 0; i < 16; i++) {
- String cellBits = Integer.toBinaryString(cells[i]);
-
- // Append leading 0 for full "8-bit" strings
- while (cellBits.length() < 8) {
- cellBits = "0" + cellBits;
- }
-
- blockBits += cellBits;
- }
-
- return new BigInteger(blockBits, 2);
- }
-
- /*
- * Returns ciphertext XOR key
- */
- public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) {
- return ciphertext.xor(key);
- }
-
- /*
- * substitutes 8-Bit long substrings of the input using the S-Box and
- * returns the result.
- */
- public static BigInteger subBytes(BigInteger ciphertext) {
-
- int[] cells = splitBlockIntoCells(ciphertext);
-
- for (int i = 0; i < 16; i++) {
- cells[i] = sBox[cells[i]];
- }
-
- return mergeCellsIntoBlock(cells);
- }
-
- /*
- * substitutes 8-Bit long substrings of the input using the inverse S-Box
- * for decryption and returns the result.
- */
- public static BigInteger subBytesDec(BigInteger ciphertext) {
-
- int[] cells = splitBlockIntoCells(ciphertext);
-
- for (int i = 0; i < 16; i++) {
- cells[i] = inverseSBox[cells[i]];
- }
-
- return mergeCellsIntoBlock(cells);
- }
-
- /*
- * Cell permutation step. Shifts cells within the rows of the input and
- * returns the result.
- */
- public static BigInteger shiftRows(BigInteger ciphertext) {
- int[] cells = splitBlockIntoCells(ciphertext);
- int[] output = new int[16];
-
- // do nothing in the first row
- output[0] = cells[0];
- output[4] = cells[4];
- output[8] = cells[8];
- output[12] = cells[12];
-
- // shift the second row backwards by one cell
- output[1] = cells[5];
- output[5] = cells[9];
- output[9] = cells[13];
- output[13] = cells[1];
-
- // shift the third row backwards by two cell
- output[2] = cells[10];
- output[6] = cells[14];
- output[10] = cells[2];
- output[14] = cells[6];
-
- // shift the forth row backwards by tree cell
- output[3] = cells[15];
- output[7] = cells[3];
- output[11] = cells[7];
- output[15] = cells[11];
-
- return mergeCellsIntoBlock(output);
- }
-
- /*
- * Cell permutation step for decryption . Shifts cells within the rows of
- * the input and returns the result.
- */
- public static BigInteger shiftRowsDec(BigInteger ciphertext) {
- int[] cells = splitBlockIntoCells(ciphertext);
- int[] output = new int[16];
-
- // do nothing in the first row
- output[0] = cells[0];
- output[4] = cells[4];
- output[8] = cells[8];
- output[12] = cells[12];
-
- // shift the second row forwards by one cell
- output[1] = cells[13];
- output[5] = cells[1];
- output[9] = cells[5];
- output[13] = cells[9];
-
- // shift the third row forwards by two cell
- output[2] = cells[10];
- output[6] = cells[14];
- output[10] = cells[2];
- output[14] = cells[6];
-
- // shift the forth row forwards by tree cell
- output[3] = cells[7];
- output[7] = cells[11];
- output[11] = cells[15];
- output[15] = cells[3];
-
- return mergeCellsIntoBlock(output);
- }
-
- /*
- * Applies the Rijndael MixColumns to the input and returns the result.
- */
- public static BigInteger mixColumns(BigInteger ciphertext) {
-
- int[] cells = splitBlockIntoCells(ciphertext);
- int[] outputCells = new int[16];
-
- for (int i = 0; i < 4; i++) {
- int[] row = { cells[i*4], cells[i*4 + 1], cells[i*4 + 2], cells[i*4 + 3] };
-
- outputCells[i*4] = mult2[row[0]] ^ mult3[row[1]] ^ row[2] ^ row[3];
- outputCells[i*4 + 1] = row[0] ^ mult2[row[1]] ^ mult3[row[2]] ^ row[3];
- outputCells[i*4 + 2] = row[0] ^ row[1] ^ mult2[row[2]] ^ mult3[row[3]];
- outputCells[i*4 + 3] = mult3[row[0]] ^ row[1] ^ row[2] ^ mult2[row[3]];
- }
- return mergeCellsIntoBlock(outputCells);
- }
-
- /*
- * Applies the inverse Rijndael MixColumns for decryption to the input and
- * returns the result.
- */
- public static BigInteger mixColumnsDec(BigInteger ciphertext) {
-
- int[] cells = splitBlockIntoCells(ciphertext);
- int[] outputCells = new int[16];
-
- for (int i = 0; i < 4; i++) {
- int[] row = { cells[i*4], cells[i*4 + 1], cells[i*4 + 2], cells[i*4 + 3] };
-
- outputCells[i*4] = mult14[row[0]] ^ mult11[row[1]] ^ mult13[row[2]] ^ mult9[row[3]];
- outputCells[i*4 + 1] = mult9[row[0]] ^ mult14[row[1]] ^ mult11[row[2]] ^ mult13[row[3]];
- outputCells[i*4 + 2] = mult13[row[0]] ^ mult9[row[1]] ^ mult14[row[2]] ^ mult11[row[3]];
- outputCells[i*4 + 3] = mult11[row[0]] ^ mult13[row[1]] ^ mult9[row[2]] ^ mult14[row[3]];
- }
- return mergeCellsIntoBlock(outputCells);
- }
-
- /*
- * Encrypts the plaintext with the key and returns the result
- */
- public static BigInteger encrypt(BigInteger plaintext, BigInteger key) {
-
- BigInteger[] roundKeys = keyExpansion(key);
-
- // Initial round
- plaintext = addRoundKey(plaintext, roundKeys[0]);
-
- // Main rounds
- for (int i = 1; i < 10; i++) {
- plaintext = subBytes(plaintext);
- plaintext = shiftRows(plaintext);
- plaintext = mixColumns(plaintext);
- plaintext = addRoundKey(plaintext, roundKeys[i]);
- }
-
- // Final round
- plaintext = subBytes(plaintext);
- plaintext = shiftRows(plaintext);
- plaintext = addRoundKey(plaintext, roundKeys[10]);
-
- return plaintext;
- }
-
- /*
- * Decrypts the ciphertext with the key and returns the result
- */
- public static BigInteger decrypt(BigInteger ciphertext, BigInteger key) {
-
- BigInteger[] roundKeys = keyExpansion(key);
-
- // Invert final round
- ciphertext = addRoundKey(ciphertext, roundKeys[10]);
- ciphertext = shiftRowsDec(ciphertext);
- ciphertext = subBytesDec(ciphertext);
-
- // Invert main rounds
- for (int i = 9; i > 0; i--) {
- ciphertext = addRoundKey(ciphertext, roundKeys[i]);
- ciphertext = mixColumnsDec(ciphertext);
- ciphertext = shiftRowsDec(ciphertext);
- ciphertext = subBytesDec(ciphertext);
- }
-
- // Invert initial round
- ciphertext = addRoundKey(ciphertext, roundKeys[0]);
-
- return ciphertext;
- }
-
- public static void main(String[] args) {
-
- Scanner input = new Scanner(System.in);
-
- System.out.println("Do you want to (e)ncrypt or (d)ecrypt a message?");
- char choice = input.nextLine().charAt(0);
- String in;
- if(choice == 'E' || choice=='e'){
- System.out.println("Choose a plaintext block (128-Bit Integer in base 16):\n");
- in = input.nextLine();
- BigInteger plaintext = new BigInteger(in, 16);
- System.out.println("Choose a Key (128-Bit Integer in base 16):\n");
- in = input.nextLine();
- BigInteger key = new BigInteger(in, 16);
-
- System.out.println("The encrypted message is: \n" + encrypt(plaintext,key).toString(16));
- }
- if(choice =='D' || choice =='d'){
- System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):\n");
- in = input.nextLine();
- BigInteger ciphertext = new BigInteger(in, 16);
- System.out.println("Choose a Key (128-Bit Integer in base 16):\n");
- in = input.nextLine();
- BigInteger key = new BigInteger(in, 16);
- System.out.println("The deciphered message is:\n" + decrypt(ciphertext,key).toString(16));
- }
-
- input.close();
- }
-
-}
diff --git a/ciphers/AESEncryption.java b/ciphers/AESEncryption.java
deleted file mode 100644
index 7ecb0874ddc4..000000000000
--- a/ciphers/AESEncryption.java
+++ /dev/null
@@ -1,83 +0,0 @@
-import javax.crypto.Cipher;
-import javax.crypto.KeyGenerator;
-import javax.crypto.SecretKey;
-import javax.xml.bind.DatatypeConverter;
-
-/**
- * This example program shows how AES encryption and decryption can be done in Java.
- * Please note that secret key and encrypted text is unreadable binary and hence
- * in the following program we display it in hexadecimal format of the underlying bytes.
- */
-public class AESEncryption {
-
- /**
- * 1. Generate a plain text for encryption
- * 2. Get a secret key (printed in hexadecimal form). In actual use this must
- * by encrypted and kept safe. The same key is required for decryption.
- *
- */
- public static void main(String[] args) throws Exception {
- String plainText = "Hello World";
- SecretKey secKey = getSecretEncryptionKey();
- byte[] cipherText = encryptText(plainText, secKey);
- String decryptedText = decryptText(cipherText, secKey);
-
- System.out.println("Original Text:" + plainText);
- System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
- System.out.println("Encrypted Text (Hex Form):"+bytesToHex(cipherText));
- System.out.println("Descrypted Text:"+decryptedText);
-
- }
-
- /**
- * gets the AES encryption key. In your actual programs, this should be safely
- * stored.
- * @return
- * @throws Exception
- */
- public static SecretKey getSecretEncryptionKey() throws Exception{
- KeyGenerator generator = KeyGenerator.getInstance("AES");
- generator.init(128); // The AES key size in number of bits
- SecretKey secKey = generator.generateKey();
- return secKey;
- }
-
- /**
- * Encrypts plainText in AES using the secret key
- * @param plainText
- * @param secKey
- * @return
- * @throws Exception
- */
- public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
- // AES defaults to AES/ECB/PKCS5Padding in Java 7
- Cipher aesCipher = Cipher.getInstance("AES");
- aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
- byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
- return byteCipherText;
- }
-
- /**
- * Decrypts encrypted byte array using the key used for encryption.
- * @param byteCipherText
- * @param secKey
- * @return
- * @throws Exception
- */
- public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
- // AES defaults to AES/ECB/PKCS5Padding in Java 7
- Cipher aesCipher = Cipher.getInstance("AES");
- aesCipher.init(Cipher.DECRYPT_MODE, secKey);
- byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
- return new String(bytePlainText);
- }
-
- /**
- * Convert a binary byte array into readable hex form
- * @param hash
- * @return
- */
- private static String bytesToHex(byte[] hash) {
- return DatatypeConverter.printHexBinary(hash);
- }
-}
diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java
deleted file mode 100644
index 32bc87b86e95..000000000000
--- a/ciphers/Caesar.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
-Author : FAHRI YARDIMCI
-
-A Java implementation of Caesar Cipher.
-/It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. /
-**/
-import java.util.Scanner;
-public class Caesar {
-public static String encode (String message,int shift)
-{
- String encoded = "";
- for(int i = 0 ; i=65 && current<= 90)
- {
- int numAlphabet = message.charAt(i);
- if(shift + numAlphabet > 90)
- {
- int j = 90 - numAlphabet;
- char nextKey = (char)(65 + (shift - j - 1));
- encoded += nextKey;
-
- }
- else
- {
- char nextKey = (char)(current + shift);
- encoded += nextKey;
- }
- }
- else if (current>=97 && current <= 122)
- {
- int numAlphabet = message.charAt(i);
- if(shift + numAlphabet > 122)
- {
- int j = 122 - numAlphabet;
- char nextKey = (char)(97 + (shift - j - 1));
- encoded += nextKey;
- }
- else
- {
- char nextKey = (char)(current + shift);
- encoded += nextKey;
- }
- }
- }
- return encoded;
-}
-public static String decode (String message,int shift)
-{
- String decoded = "";
- for(int i = 0 ; i=65 && current<= 90)
- {
- int numAlphabet = message.charAt(i);
- if(numAlphabet - shift < 65)
- {
- int j = numAlphabet - 65;
- char nextKey = (char)(90 - (shift - j - 1));
- decoded += nextKey;
-
- }
- else
- {
- char nextKey = (char)(current - shift);
- decoded += nextKey;
- }
- }
- else if (current>=97 && current <= 122)
- {
- int numAlphabet = message.charAt(i);
- if(numAlphabet - shift < 97)
- {
- int j = numAlphabet - 97;
- char nextKey = (char)(122 - (shift - j - 1));
- decoded += nextKey;
- }
- else
- {
- char nextKey = (char)(current - shift);
- decoded += nextKey;
- }
- }
- }
- return decoded;
-}
-public static void main(String[] args)
-{
- Scanner input = new Scanner(System.in);
- System.out.println("Please enter the message (Latin Alphabet)");
- String message = input.nextLine();
- System.out.println(message);
- System.out.println("Please enter the shift number");
- int shift = input.nextInt() % 26;
- System.out.println("(E)ncode or (D)ecode ?");
- char choice = input.next().charAt(0);
- if(choice == 'E' || choice=='e')
- System.out.println("ENCODED MESSAGE IS \n" + encode(message,shift)); //send our function to handle
- if(choice =='D' || choice =='d')
- System.out.println("DECODED MESSAGE IS \n" + decode(message,shift));
-}
-
-}
\ No newline at end of file
diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java
deleted file mode 100644
index b12743715984..000000000000
--- a/ciphers/ColumnarTranspositionCipher.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * Columnar Transposition Cipher Encryption and Decryption.
- * @author freitzzz
- */
-public class ColumnarTranspositionCipher {
- private static String keyword;
- private static Object[][] table;
- private static String abecedarium;
- public static final String ABECEDARIUM="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
- private static final String ENCRYPTION_FIELD="≈";
- private static final char ENCRYPTION_FIELD_CHAR='≈';
- /**
- * Encrypts a certain String with the Columnar Transposition Cipher Rule
- * @param word Word being encrypted
- * @param keyword String with keyword being used
- * @return a String with the word encrypted by the Columnar Transposition Cipher Rule
- */
- public static String encrpyter(String word,String keyword){
- ColumnarTranspositionCipher.keyword=keyword;
- abecedariumBuilder(500);
- table=tableBuilder(word);
- Object[][] sortedTable=sortTable(table);
- String wordEncrypted="";
- for(int i=0;iword.length()/keyword.length()){
- return (word.length()/keyword.length())+1;
- }else{
- return word.length()/keyword.length();
- }
- }
- private static Object[] findElements(){
- Object[] charValues=new Object[keyword.length()];
- for(int i=0;i(int)table[0][j]){
- Object[] column=getColumn(tableSorted,tableSorted.length,i);
- switchColumns(tableSorted,j,i,column);
- }
- }
- }
- return tableSorted;
- }
- private static Object[] getColumn(Object[][] table,int rows,int column){
- Object[] columnArray=new Object[rows];
- for(int i=0;i>> "+wordBeingEncrypted);
- System.out.println("Word encrypted ->>> "+ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted,keywordForExample));
- System.out.println("Word decryped ->>> "+ColumnarTranspositionCipher.decrypter());
- System.out.println("\n### Encrypted Table ###");
- showTable();
- }
-}
diff --git a/ciphers/RSA.java b/ciphers/RSA.java
deleted file mode 100644
index 5baa61b0424d..000000000000
--- a/ciphers/RSA.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package ciphers;
-
-import java.math.BigInteger;
-import java.security.SecureRandom;
-
-/**
- * Created by Nguyen Duy Tiep on 23-Oct-17.
- */
-public class RSA {
- private BigInteger modulus, privateKey, publicKey;
-
- public RSA(int bits) {
- generateKeys(bits);
- }
-
- public synchronized String encrypt(String message) {
- return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
- }
-
- public synchronized BigInteger encrypt(BigInteger message) {
- return message.modPow(publicKey, modulus);
- }
-
- public synchronized String decrypt(String message) {
- return new String((new BigInteger(message)).modPow(privateKey, modulus).toByteArray());
- }
-
- public synchronized BigInteger decrypt(BigInteger message) {
- return message.modPow(privateKey, modulus);
- }
-
- /** Generate a new public and private key set. */
- public synchronized void generateKeys(int bits) {
- SecureRandom r = new SecureRandom();
- BigInteger p = new BigInteger(bits / 2, 100, r);
- BigInteger q = new BigInteger(bits / 2, 100, r);
- modulus = p.multiply(q);
-
- BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
-
- publicKey = new BigInteger("3");
-
- while (m.gcd(publicKey).intValue() > 1) {
- publicKey = publicKey.add(new BigInteger("2"));
- }
-
- privateKey = publicKey.modInverse(m);
- }
-
- /** Trivial test program. */
- public static void main(String[] args) {
- RSA rsa = new RSA(1024);
-
- String text1 = "This is a message";
- System.out.println("Plaintext: " + text1);
-
- String ciphertext = rsa.encrypt(text1);
- System.out.println("Ciphertext: " + ciphertext);
-
- System.out.println("Plaintext: " + rsa.decrypt(ciphertext));
- }
-}
diff --git a/data_structures/Stacks/BalancedBrackets.java b/data_structures/Stacks/BalancedBrackets.java
deleted file mode 100644
index d0e9ef9c540c..000000000000
--- a/data_structures/Stacks/BalancedBrackets.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
-
-The nested brackets problem is a problem that determines if a sequence of
-brackets are properly nested. A sequence of brackets s is considered properly nested
-if any of the following conditions are true:
- - s is empty
- - s has the form (U) or [U] or {U} where U is a properly nested string
- - s has the form VW where V and W are properly nested strings
-For example, the string "()()[()]" is properly nested but "[(()]" is not.
-The function called is_balanced takes as input a string S which is a sequence of brackets and
-returns true if S is nested and false otherwise.
-
- author: akshay sharma
- date: 2017-10-17
-*/
-import java.util.Scanner;
-import java.util.Stack;
-import java.util.ArrayList;
-
-class BalancedBrackets {
-
- static boolean is_balanced(char[] S) {
- Stack stack = new Stack<>();
- String pair = "";
- for (int i = 0; i < S.length; ++i) {
- if (S[i] == '(' || S[i] == '{' || S[i] == '[') {
- stack.push(S[i]);
- } else if (stack.size() > 0) {
- if (!pair.equals("[]") && !pair.equals("()") && !pair.equals("{}")) {
- return false;
- }
- } else {
- return false;
- }
- }
-
- return stack.isEmpty();
- }
-
- static void print(Object a) {
- System.out.println(a);
- }
-
- public static void main(String args[]) {
- try {
- Scanner in = new Scanner(System.in);
- print("Enter sequence of brackets: ");
- String S = in.nextLine();
- if (is_balanced(S.toCharArray())) {
- print(S + " is balanced");
- } else {
- print(S + " ain't balanced");
- }
- in.close();
- } catch (Exception e) {
- e.toString();
- }
- }
-}
diff --git a/pmd-exclude.properties b/pmd-exclude.properties
new file mode 100644
index 000000000000..1848412c9d30
--- /dev/null
+++ b/pmd-exclude.properties
@@ -0,0 +1,64 @@
+com.thealgorithms.ciphers.AffineCipher=UselessParentheses
+com.thealgorithms.ciphers.DES=UselessParentheses
+com.thealgorithms.ciphers.RSA=UselessParentheses
+com.thealgorithms.conversions.AnyBaseToAnyBase=UselessParentheses
+com.thealgorithms.conversions.AnytoAny=UselessParentheses
+com.thealgorithms.datastructures.crdt.Pair=UnusedPrivateField
+com.thealgorithms.datastructures.graphs.AStar=UselessParentheses
+com.thealgorithms.datastructures.graphs.AdjacencyMatrixGraph=CollapsibleIfStatements,UnnecessaryFullyQualifiedName,UselessParentheses
+com.thealgorithms.datastructures.graphs.BipartiteGraphDFS=CollapsibleIfStatements
+com.thealgorithms.datastructures.hashmap.hashing.HashMapCuckooHashing=UselessParentheses
+com.thealgorithms.datastructures.heaps.FibonacciHeap=UselessParentheses
+com.thealgorithms.datastructures.heaps.HeapNode=UselessParentheses
+com.thealgorithms.datastructures.lists.DoublyLinkedList=UselessParentheses
+com.thealgorithms.datastructures.lists.SearchSinglyLinkedListRecursion=UselessParentheses
+com.thealgorithms.datastructures.lists.SinglyLinkedList=UnusedLocalVariable
+com.thealgorithms.datastructures.queues.PriorityQueue=UselessParentheses
+com.thealgorithms.datastructures.trees.CheckBinaryTreeIsValidBST=UselessParentheses
+com.thealgorithms.datastructures.trees.SegmentTree=UselessParentheses
+com.thealgorithms.devutils.nodes.LargeTreeNode=UselessParentheses
+com.thealgorithms.devutils.nodes.SimpleNode=UselessParentheses
+com.thealgorithms.devutils.nodes.SimpleTreeNode=UselessParentheses
+com.thealgorithms.devutils.nodes.TreeNode=UselessParentheses
+com.thealgorithms.divideandconquer.ClosestPair=UnnecessaryFullyQualifiedName,UselessParentheses
+com.thealgorithms.divideandconquer.Point=UselessParentheses
+com.thealgorithms.dynamicprogramming.WineProblem=UselessParentheses
+com.thealgorithms.maths.BinomialCoefficient=UselessParentheses
+com.thealgorithms.maths.Complex=UselessParentheses
+com.thealgorithms.maths.DistanceFormulaTest=UnnecessaryFullyQualifiedName
+com.thealgorithms.maths.Gaussian=UselessParentheses
+com.thealgorithms.maths.GcdSolutionWrapper=UselessParentheses
+com.thealgorithms.maths.HeronsFormula=UselessParentheses
+com.thealgorithms.maths.KaprekarNumbers=UselessParentheses
+com.thealgorithms.maths.KeithNumber=UselessParentheses
+com.thealgorithms.maths.LeonardoNumber=UselessParentheses
+com.thealgorithms.maths.LinearDiophantineEquationsSolver=UselessParentheses
+com.thealgorithms.maths.RomanNumeralUtil=UselessParentheses
+com.thealgorithms.maths.SecondMinMax=UselessParentheses
+com.thealgorithms.maths.SecondMinMaxTest=UnnecessaryFullyQualifiedName
+com.thealgorithms.maths.StandardDeviation=UselessParentheses
+com.thealgorithms.maths.SumOfArithmeticSeries=UselessParentheses
+com.thealgorithms.maths.TrinomialTriangle=UselessParentheses
+com.thealgorithms.maths.Volume=UselessParentheses
+com.thealgorithms.misc.Sparsity=UselessParentheses
+com.thealgorithms.others.CRC16=UselessParentheses
+com.thealgorithms.others.Damm=UnnecessaryFullyQualifiedName
+com.thealgorithms.others.Luhn=UnnecessaryFullyQualifiedName
+com.thealgorithms.others.Mandelbrot=UselessParentheses
+com.thealgorithms.others.MiniMaxAlgorithm=UselessParentheses
+com.thealgorithms.others.PageRank=UselessParentheses
+com.thealgorithms.others.PerlinNoise=UselessParentheses
+com.thealgorithms.others.QueueUsingTwoStacks=UselessParentheses
+com.thealgorithms.others.Trieac=UselessParentheses
+com.thealgorithms.others.Verhoeff=UnnecessaryFullyQualifiedName
+com.thealgorithms.searches.InterpolationSearch=UselessParentheses
+com.thealgorithms.searches.KMPSearch=UselessParentheses
+com.thealgorithms.searches.RabinKarpAlgorithm=UselessParentheses
+com.thealgorithms.sorts.CircleSort=EmptyControlStatement
+com.thealgorithms.sorts.DutchNationalFlagSort=UselessParentheses
+com.thealgorithms.sorts.MergeSortNoExtraSpace=UselessParentheses
+com.thealgorithms.sorts.RadixSort=UselessParentheses
+com.thealgorithms.sorts.WiggleSort=UselessParentheses
+com.thealgorithms.stacks.PostfixToInfix=UselessParentheses
+com.thealgorithms.strings.HorspoolSearch=UnnecessaryFullyQualifiedName,UselessParentheses
+com.thealgorithms.strings.Palindrome=UselessParentheses
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 000000000000..b4ca8562ff9d
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,156 @@
+
+
+ 4.0.0
+ com.thealgorithms
+ Java
+ 1.0-SNAPSHOT
+ jar
+
+
+ UTF-8
+ 21
+ 21
+ 3.27.3
+
+
+
+
+
+ org.junit
+ junit-bom
+ 5.13.0
+ pom
+ import
+
+
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.mockito
+ mockito-core
+ 5.18.0
+ test
+
+
+ org.apache.commons
+ commons-lang3
+ 3.17.0
+
+
+ org.apache.commons
+ commons-collections4
+ 4.5.0
+
+
+
+
+
+
+ maven-surefire-plugin
+ 3.5.3
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.14.0
+
+ 21
+ 21
+
+ -Xlint:all
+ -Xlint:-auxiliaryclass
+ -Xlint:-rawtypes
+ -Xlint:-unchecked
+ -Werror
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+ 0.8.13
+
+
+
+ prepare-agent
+
+
+
+ generate-code-coverage-report
+ test
+
+ report
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 3.6.0
+
+ checkstyle.xml
+ true
+ true
+ warning
+
+
+
+ com.puppycrawl.tools
+ checkstyle
+ 10.25.0
+
+
+
+
+ com.github.spotbugs
+ spotbugs-maven-plugin
+ 4.9.3.0
+
+ spotbugs-exclude.xml
+ true
+
+
+ com.mebigfatguy.fb-contrib
+ fb-contrib
+ 7.6.10
+
+
+ com.h3xstream.findsecbugs
+ findsecbugs-plugin
+ 1.14.0
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ 3.26.0
+
+ true
+ true
+ false
+ pmd-exclude.properties
+
+
+
+
+
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
new file mode 100644
index 000000000000..bcc053611de6
--- /dev/null
+++ b/spotbugs-exclude.xml
@@ -0,0 +1,208 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/com/thealgorithms/audiofilters/EMAFilter.java b/src/main/java/com/thealgorithms/audiofilters/EMAFilter.java
new file mode 100644
index 000000000000..0dd23e937953
--- /dev/null
+++ b/src/main/java/com/thealgorithms/audiofilters/EMAFilter.java
@@ -0,0 +1,48 @@
+package com.thealgorithms.audiofilters;
+
+/**
+ * Exponential Moving Average (EMA) Filter for smoothing audio signals.
+ *
+ *
This filter applies an exponential moving average to a sequence of audio
+ * signal values, making it useful for smoothing out rapid fluctuations.
+ * The smoothing factor (alpha) controls the degree of smoothing.
+ *
+ *
Based on the definition from
+ * Wikipedia link.
+ */
+public class EMAFilter {
+ private final double alpha;
+ private double emaValue;
+ /**
+ * Constructs an EMA filter with a given smoothing factor.
+ *
+ * @param alpha Smoothing factor (0 < alpha <= 1)
+ * @throws IllegalArgumentException if alpha is not in (0, 1]
+ */
+ public EMAFilter(double alpha) {
+ if (alpha <= 0 || alpha > 1) {
+ throw new IllegalArgumentException("Alpha must be between 0 and 1.");
+ }
+ this.alpha = alpha;
+ this.emaValue = 0.0;
+ }
+ /**
+ * Applies the EMA filter to an audio signal array.
+ *
+ * @param audioSignal Array of audio samples to process
+ * @return Array of processed (smoothed) samples
+ */
+ public double[] apply(double[] audioSignal) {
+ if (audioSignal.length == 0) {
+ return new double[0];
+ }
+ double[] emaSignal = new double[audioSignal.length];
+ emaValue = audioSignal[0];
+ emaSignal[0] = emaValue;
+ for (int i = 1; i < audioSignal.length; i++) {
+ emaValue = alpha * audioSignal[i] + (1 - alpha) * emaValue;
+ emaSignal[i] = emaValue;
+ }
+ return emaSignal;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
new file mode 100644
index 000000000000..fbc095909541
--- /dev/null
+++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
@@ -0,0 +1,93 @@
+package com.thealgorithms.audiofilters;
+
+/**
+ * N-Order IIR Filter Assumes inputs are normalized to [-1, 1]
+ *
+ * Based on the difference equation from
+ * Wikipedia link
+ */
+public class IIRFilter {
+
+ private final int order;
+ private final double[] coeffsA;
+ private final double[] coeffsB;
+ private final double[] historyX;
+ private final double[] historyY;
+
+ /**
+ * Construct an IIR Filter
+ *
+ * @param order the filter's order
+ * @throws IllegalArgumentException if order is zero or less
+ */
+ public IIRFilter(int order) throws IllegalArgumentException {
+ if (order < 1) {
+ throw new IllegalArgumentException("order must be greater than zero");
+ }
+
+ this.order = order;
+ coeffsA = new double[order + 1];
+ coeffsB = new double[order + 1];
+
+ // Sane defaults
+ coeffsA[0] = 1.0;
+ coeffsB[0] = 1.0;
+
+ historyX = new double[order];
+ historyY = new double[order];
+ }
+
+ /**
+ * Set coefficients
+ *
+ * @param aCoeffs Denominator coefficients
+ * @param bCoeffs Numerator coefficients
+ * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is
+ * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0
+ */
+ public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
+ if (aCoeffs.length != order) {
+ throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length);
+ }
+
+ if (aCoeffs[0] == 0.0) {
+ throw new IllegalArgumentException("aCoeffs.get(0) must not be zero");
+ }
+
+ if (bCoeffs.length != order) {
+ throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length);
+ }
+
+ for (int i = 0; i < order; i++) {
+ coeffsA[i] = aCoeffs[i];
+ coeffsB[i] = bCoeffs[i];
+ }
+ }
+
+ /**
+ * Process a single sample
+ *
+ * @param sample the sample to process
+ * @return the processed sample
+ */
+ public double process(double sample) {
+ double result = 0.0;
+
+ // Process
+ for (int i = 1; i <= order; i++) {
+ result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
+ }
+ result = (result + coeffsB[0] * sample) / coeffsA[0];
+
+ // Feedback
+ for (int i = order - 1; i > 0; i--) {
+ historyX[i] = historyX[i - 1];
+ historyY[i] = historyY[i - 1];
+ }
+
+ historyX[0] = sample;
+ historyY[0] = result;
+
+ return result;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
new file mode 100644
index 000000000000..6f93b704ffb2
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -0,0 +1,100 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Program description - To find all possible paths from source to destination
+ * Wikipedia
+ *
+ * @author Siddhant Swarup Mallick
+ */
+public class AllPathsFromSourceToTarget {
+
+ // No. of vertices in graph
+ private final int v;
+
+ // To store the paths from source to destination
+ static List> nm = new ArrayList<>();
+ // adjacency list
+ private ArrayList[] adjList;
+
+ // Constructor
+ public AllPathsFromSourceToTarget(int vertices) {
+
+ // initialise vertex count
+ this.v = vertices;
+
+ // initialise adjacency list
+ initAdjList();
+ }
+
+ // utility method to initialise adjacency list
+ private void initAdjList() {
+ adjList = new ArrayList[v];
+
+ for (int i = 0; i < v; i++) {
+ adjList[i] = new ArrayList<>();
+ }
+ }
+
+ // add edge from u to v
+ public void addEdge(int u, int v) {
+ // Add v to u's list.
+ adjList[u].add(v);
+ }
+
+ public void storeAllPaths(int s, int d) {
+ boolean[] isVisited = new boolean[v];
+ ArrayList pathList = new ArrayList<>();
+
+ // add source to path[]
+ pathList.add(s);
+ // Call recursive utility
+ storeAllPathsUtil(s, d, isVisited, pathList);
+ }
+
+ // A recursive function to print all paths from 'u' to 'd'.
+ // isVisited[] keeps track of vertices in current path.
+ // localPathList<> stores actual vertices in the current path
+ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List localPathList) {
+
+ if (u.equals(d)) {
+ nm.add(new ArrayList<>(localPathList));
+ return;
+ }
+
+ // Mark the current node
+ isVisited[u] = true;
+
+ // Recursion for all the vertices adjacent to current vertex
+
+ for (Integer i : adjList[u]) {
+ if (!isVisited[i]) {
+ // store current node in path[]
+ localPathList.add(i);
+ storeAllPathsUtil(i, d, isVisited, localPathList);
+
+ // remove current node in path[]
+ localPathList.remove(i);
+ }
+ }
+
+ // Mark the current node
+ isVisited[u] = false;
+ }
+
+ // Driver program
+ public static List> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) {
+ // Create a sample graph
+ AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
+ for (int[] i : a) {
+ g.addEdge(i[0], i[1]);
+ // edges are added
+ }
+ g.storeAllPaths(source, destination);
+ // method call to store all possible paths
+ return nm;
+ // returns all possible paths from source to destination
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
new file mode 100644
index 000000000000..f8cd0c40c20e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
@@ -0,0 +1,54 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class provides methods to find all combinations of integers from 0 to n-1
+ * of a specified length k using backtracking.
+ */
+public final class ArrayCombination {
+ private ArrayCombination() {
+ }
+
+ /**
+ * Generates all possible combinations of length k from the integers 0 to n-1.
+ *
+ * @param n The total number of elements (0 to n-1).
+ * @param k The desired length of each combination.
+ * @return A list containing all combinations of length k.
+ * @throws IllegalArgumentException if n or k are negative, or if k is greater than n.
+ */
+ public static List> combination(int n, int k) {
+ if (n < 0 || k < 0 || k > n) {
+ throw new IllegalArgumentException("Invalid input: n must be non-negative, k must be non-negative and less than or equal to n.");
+ }
+
+ List> combinations = new ArrayList<>();
+ combine(combinations, new ArrayList<>(), 0, n, k);
+ return combinations;
+ }
+
+ /**
+ * A helper method that uses backtracking to find combinations.
+ *
+ * @param combinations The list to store all valid combinations found.
+ * @param current The current combination being built.
+ * @param start The starting index for the current recursion.
+ * @param n The total number of elements (0 to n-1).
+ * @param k The desired length of each combination.
+ */
+ private static void combine(List> combinations, List current, int start, int n, int k) {
+ // Base case: combination found
+ if (current.size() == k) {
+ combinations.add(new ArrayList<>(current));
+ return;
+ }
+
+ for (int i = start; i < n; i++) {
+ current.add(i);
+ combine(combinations, current, i + 1, n, k);
+ current.remove(current.size() - 1); // Backtrack
+ }
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java
new file mode 100644
index 000000000000..ecaf7428f986
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/Combination.java
@@ -0,0 +1,67 @@
+package com.thealgorithms.backtracking;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.TreeSet;
+
+/**
+ * Finds all permutations of given array
+ * @author Alan Piao (git-Alan Piao)
+ */
+public final class Combination {
+ private Combination() {
+ }
+
+ /**
+ * Find all combinations of given array using backtracking
+ * @param arr the array.
+ * @param n length of combination
+ * @param the type of elements in the array.
+ * @return a list of all combinations of length n. If n == 0, return null.
+ */
+ public static List> combination(T[] arr, int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("The combination length cannot be negative.");
+ }
+
+ if (n == 0) {
+ return Collections.emptyList();
+ }
+ T[] array = arr.clone();
+ Arrays.sort(array);
+
+ List> result = new LinkedList<>();
+ backtracking(array, n, 0, new TreeSet(), result);
+ return result;
+ }
+
+ /**
+ * Backtrack all possible combinations of a given array
+ * @param arr the array.
+ * @param n length of the combination
+ * @param index the starting index.
+ * @param currSet set that tracks current combination
+ * @param result the list contains all combination.
+ * @param the type of elements in the array.
+ */
+ private static void backtracking(T[] arr, int n, int index, TreeSet currSet, List> result) {
+ if (index + n - currSet.size() > arr.length) {
+ return;
+ }
+ if (currSet.size() == n - 1) {
+ for (int i = index; i < arr.length; i++) {
+ currSet.add(arr[i]);
+ result.add(new TreeSet<>(currSet));
+ currSet.remove(arr[i]);
+ }
+ return;
+ }
+ for (int i = index; i < arr.length; i++) {
+ currSet.add(arr[i]);
+ backtracking(arr, n, i + 1, currSet, result);
+ currSet.remove(arr[i]);
+ }
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java
new file mode 100644
index 000000000000..6bfb026c7de9
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java
@@ -0,0 +1,125 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * A class to solve a crossword puzzle using backtracking.
+ * Example:
+ * Input:
+ * puzzle = {
+ * {' ', ' ', ' '},
+ * {' ', ' ', ' '},
+ * {' ', ' ', ' '}
+ * }
+ * words = List.of("cat", "dog")
+ *
+ * Output:
+ * {
+ * {'c', 'a', 't'},
+ * {' ', ' ', ' '},
+ * {'d', 'o', 'g'}
+ * }
+ */
+public final class CrosswordSolver {
+ private CrosswordSolver() {
+ }
+
+ /**
+ * Checks if a word can be placed at the specified position in the crossword.
+ *
+ * @param puzzle The crossword puzzle represented as a 2D char array.
+ * @param word The word to be placed.
+ * @param row The row index where the word might be placed.
+ * @param col The column index where the word might be placed.
+ * @param vertical If true, the word is placed vertically; otherwise, horizontally.
+ * @return true if the word can be placed, false otherwise.
+ */
+ public static boolean isValid(char[][] puzzle, String word, int row, int col, boolean vertical) {
+ for (int i = 0; i < word.length(); i++) {
+ if (vertical) {
+ if (row + i >= puzzle.length || puzzle[row + i][col] != ' ') {
+ return false;
+ }
+ } else {
+ if (col + i >= puzzle[0].length || puzzle[row][col + i] != ' ') {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Places a word at the specified position in the crossword.
+ *
+ * @param puzzle The crossword puzzle represented as a 2D char array.
+ * @param word The word to be placed.
+ * @param row The row index where the word will be placed.
+ * @param col The column index where the word will be placed.
+ * @param vertical If true, the word is placed vertically; otherwise, horizontally.
+ */
+ public static void placeWord(char[][] puzzle, String word, int row, int col, boolean vertical) {
+ for (int i = 0; i < word.length(); i++) {
+ if (vertical) {
+ puzzle[row + i][col] = word.charAt(i);
+ } else {
+ puzzle[row][col + i] = word.charAt(i);
+ }
+ }
+ }
+
+ /**
+ * Removes a word from the specified position in the crossword.
+ *
+ * @param puzzle The crossword puzzle represented as a 2D char array.
+ * @param word The word to be removed.
+ * @param row The row index where the word is placed.
+ * @param col The column index where the word is placed.
+ * @param vertical If true, the word was placed vertically; otherwise, horizontally.
+ */
+ public static void removeWord(char[][] puzzle, String word, int row, int col, boolean vertical) {
+ for (int i = 0; i < word.length(); i++) {
+ if (vertical) {
+ puzzle[row + i][col] = ' ';
+ } else {
+ puzzle[row][col + i] = ' ';
+ }
+ }
+ }
+
+ /**
+ * Solves the crossword puzzle using backtracking.
+ *
+ * @param puzzle The crossword puzzle represented as a 2D char array.
+ * @param words The list of words to be placed.
+ * @return true if the crossword is solved, false otherwise.
+ */
+ public static boolean solveCrossword(char[][] puzzle, Collection words) {
+ // Create a mutable copy of the words list
+ List remainingWords = new ArrayList<>(words);
+
+ for (int row = 0; row < puzzle.length; row++) {
+ for (int col = 0; col < puzzle[0].length; col++) {
+ if (puzzle[row][col] == ' ') {
+ for (String word : new ArrayList<>(remainingWords)) {
+ for (boolean vertical : new boolean[] {true, false}) {
+ if (isValid(puzzle, word, row, col, vertical)) {
+ placeWord(puzzle, word, row, col, vertical);
+ remainingWords.remove(word);
+ if (solveCrossword(puzzle, remainingWords)) {
+ return true;
+ }
+ remainingWords.add(word);
+ removeWord(puzzle, word, row, col, vertical);
+ }
+ }
+ }
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
new file mode 100644
index 000000000000..c8219ca8ba7e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
@@ -0,0 +1,62 @@
+package com.thealgorithms.backtracking;
+
+/**
+ * Java program for Flood fill algorithm.
+ * @author Akshay Dubey (Git-Akshay Dubey)
+ */
+public final class FloodFill {
+ private FloodFill() {
+ }
+
+ /**
+ * Get the color at the given coordinates of a 2D image
+ *
+ * @param image The image to be filled
+ * @param x The x co-ordinate of which color is to be obtained
+ * @param y The y co-ordinate of which color is to be obtained
+ */
+
+ public static int getPixel(final int[][] image, final int x, final int y) {
+ return image[x][y];
+ }
+
+ /**
+ * Put the color at the given coordinates of a 2D image
+ *
+ * @param image The image to be filled
+ * @param x The x co-ordinate at which color is to be filled
+ * @param y The y co-ordinate at which color is to be filled
+ */
+ public static void putPixel(final int[][] image, final int x, final int y, final int newColor) {
+ image[x][y] = newColor;
+ }
+
+ /**
+ * Fill the 2D image with new color
+ *
+ * @param image The image to be filled
+ * @param x The x co-ordinate at which color is to be filled
+ * @param y The y co-ordinate at which color is to be filled
+ * @param newColor The new color which to be filled in the image
+ * @param oldColor The old color which is to be replaced in the image
+ */
+ public static void floodFill(final int[][] image, final int x, final int y, final int newColor, final int oldColor) {
+ if (newColor == oldColor || x < 0 || x >= image.length || y < 0 || y >= image[x].length || getPixel(image, x, y) != oldColor) {
+ return;
+ }
+
+ putPixel(image, x, y, newColor);
+
+ /* Recursively check for horizontally & vertically adjacent coordinates */
+ floodFill(image, x + 1, y, newColor, oldColor);
+ floodFill(image, x - 1, y, newColor, oldColor);
+ floodFill(image, x, y + 1, newColor, oldColor);
+ floodFill(image, x, y - 1, newColor, oldColor);
+
+ /* Recursively check for diagonally adjacent coordinates */
+ floodFill(image, x + 1, y - 1, newColor, oldColor);
+ floodFill(image, x - 1, y + 1, newColor, oldColor);
+ floodFill(image, x + 1, y + 1, newColor, oldColor);
+ floodFill(image, x - 1, y - 1, newColor, oldColor);
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
new file mode 100644
index 000000000000..2c2da659f3aa
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
@@ -0,0 +1,156 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * The KnightsTour class solves the Knight's Tour problem using backtracking.
+ *
+ * Problem Statement:
+ * Given an N*N board with a knight placed on the first block, the knight must
+ * move according to chess rules and visit each square on the board exactly once.
+ * The class outputs the sequence of moves for the knight.
+ *
+ * Example:
+ * Input: N = 8 (8x8 chess board)
+ * Output: The sequence of numbers representing the order in which the knight visits each square.
+ */
+public final class KnightsTour {
+ private KnightsTour() {
+ }
+
+ // The size of the chess board (12x12 grid, with 2 extra rows/columns as a buffer around a 8x8 area)
+ private static final int BASE = 12;
+
+ // Possible moves for a knight in chess
+ private static final int[][] MOVES = {
+ {1, -2},
+ {2, -1},
+ {2, 1},
+ {1, 2},
+ {-1, 2},
+ {-2, 1},
+ {-2, -1},
+ {-1, -2},
+ };
+
+ // Chess grid representing the board
+ static int[][] grid;
+
+ // Total number of cells the knight needs to visit
+ static int total;
+
+ /**
+ * Resets the chess board to its initial state.
+ * Initializes the grid with boundary cells marked as -1 and internal cells as 0.
+ * Sets the total number of cells the knight needs to visit.
+ */
+ public static void resetBoard() {
+ grid = new int[BASE][BASE];
+ total = (BASE - 4) * (BASE - 4);
+ for (int r = 0; r < BASE; r++) {
+ for (int c = 0; c < BASE; c++) {
+ if (r < 2 || r > BASE - 3 || c < 2 || c > BASE - 3) {
+ grid[r][c] = -1; // Mark boundary cells
+ }
+ }
+ }
+ }
+
+ /**
+ * Recursive method to solve the Knight's Tour problem.
+ *
+ * @param row The current row of the knight
+ * @param column The current column of the knight
+ * @param count The current move number
+ * @return True if a solution is found, False otherwise
+ */
+ static boolean solve(int row, int column, int count) {
+ if (count > total) {
+ return true;
+ }
+
+ List neighbor = neighbors(row, column);
+
+ if (neighbor.isEmpty() && count != total) {
+ return false;
+ }
+
+ // Sort neighbors by Warnsdorff's rule (fewest onward moves)
+ neighbor.sort(Comparator.comparingInt(a -> a[2]));
+
+ for (int[] nb : neighbor) {
+ int nextRow = nb[0];
+ int nextCol = nb[1];
+ grid[nextRow][nextCol] = count;
+ if (!orphanDetected(count, nextRow, nextCol) && solve(nextRow, nextCol, count + 1)) {
+ return true;
+ }
+ grid[nextRow][nextCol] = 0; // Backtrack
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns a list of valid neighboring cells where the knight can move.
+ *
+ * @param row The current row of the knight
+ * @param column The current column of the knight
+ * @return A list of arrays representing valid moves, where each array contains:
+ * {nextRow, nextCol, numberOfPossibleNextMoves}
+ */
+ static List neighbors(int row, int column) {
+ List neighbour = new ArrayList<>();
+
+ for (int[] m : MOVES) {
+ int x = m[0];
+ int y = m[1];
+ if (row + y >= 0 && row + y < BASE && column + x >= 0 && column + x < BASE && grid[row + y][column + x] == 0) {
+ int num = countNeighbors(row + y, column + x);
+ neighbour.add(new int[] {row + y, column + x, num});
+ }
+ }
+ return neighbour;
+ }
+
+ /**
+ * Counts the number of possible valid moves for a knight from a given position.
+ *
+ * @param row The row of the current position
+ * @param column The column of the current position
+ * @return The number of valid neighboring moves
+ */
+ static int countNeighbors(int row, int column) {
+ int num = 0;
+ for (int[] m : MOVES) {
+ int x = m[0];
+ int y = m[1];
+ if (row + y >= 0 && row + y < BASE && column + x >= 0 && column + x < BASE && grid[row + y][column + x] == 0) {
+ num++;
+ }
+ }
+ return num;
+ }
+
+ /**
+ * Detects if moving to a given position will create an orphan (a position with no further valid moves).
+ *
+ * @param count The current move number
+ * @param row The row of the current position
+ * @param column The column of the current position
+ * @return True if an orphan is detected, False otherwise
+ */
+ static boolean orphanDetected(int count, int row, int column) {
+ if (count < total - 1) {
+ List neighbor = neighbors(row, column);
+ for (int[] nb : neighbor) {
+ if (countNeighbors(nb[0], nb[1]) == 0) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/backtracking/MColoring.java b/src/main/java/com/thealgorithms/backtracking/MColoring.java
new file mode 100644
index 000000000000..d0188dfd13aa
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java
@@ -0,0 +1,96 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.Set;
+
+/**
+ * Node class represents a graph node. Each node is associated with a color
+ * (initially 1) and contains a set of edges representing its adjacent nodes.
+ *
+ * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ */
+class Node {
+ int color = 1; // Initial color for each node
+ Set edges = new HashSet(); // Set of edges representing adjacent nodes
+}
+
+/**
+ * MColoring class solves the M-Coloring problem where the goal is to determine
+ * if it's possible to color a graph using at most M colors such that no two
+ * adjacent nodes have the same color.
+ */
+public final class MColoring {
+
+ private MColoring() {
+ } // Prevent instantiation of utility class
+
+ /**
+ * Determines whether it is possible to color the graph using at most M colors.
+ *
+ * @param nodes List of nodes representing the graph.
+ * @param n The total number of nodes in the graph.
+ * @param m The maximum number of allowed colors.
+ * @return true if the graph can be colored using M colors, false otherwise.
+ */
+ static boolean isColoringPossible(ArrayList nodes, int n, int m) {
+
+ // Visited array keeps track of whether each node has been processed.
+ ArrayList visited = new ArrayList