From 33e74a0e7077a004b0bf999994d8e9c78449c3f2 Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Mon, 21 Nov 2016 12:38:53 +0000
Subject: [PATCH 0001/2305] Added array implementation of a stack
---
Data_Structures/Stack.class | Bin 0 -> 947 bytes
Data_Structures/Stacks.class | Bin 0 -> 765 bytes
data_structures/Stacks.java | 57 +++++++++++++++++++++++++++++++++++
3 files changed, 57 insertions(+)
create mode 100644 Data_Structures/Stack.class
create mode 100644 Data_Structures/Stacks.class
create mode 100644 data_structures/Stacks.java
diff --git a/Data_Structures/Stack.class b/Data_Structures/Stack.class
new file mode 100644
index 0000000000000000000000000000000000000000..c82f0408d1a8a73efe485d9750399f9588f1e067
GIT binary patch
literal 947
zcmZ{hUr!T36vfZ%PP^^0^be&77O@H{>;t^;hA|oTG$zLQ0sK(LGwZgj8Xr2dbLXDlId}Tw=hyE5wsFr!9=D3f;kI5@^|EH+j)l7d
zR!_Y>^xt~|Vqd_HV%6zB8V=Pv0pk@bW;_T5^7s9|A3qR~>-!r=+;#`2l$2Y3-+MOd
zwY}jB)ecyhYYjRoI8sAjpVOj@&-{p1twT-Up*%_)WjKn?1acQD7*T76+R9wtpsfr&
zuSUvkLjA$PYM#GM`=j&KAi7whaR~O2G
zgB1rB3J!{}9n7G>5J`tXMYn7Ps{dx|pndLjVl??&c|N2GLyP!jXkD^X%H4t>bCzp~
zr`NnUxG%Y1Al$|nhU;F!_-2n`y2cptb0RHsT_74nNCGvo#w?3ORg${|f-2^CB96BO
zS_sTft)3^LfV%tg5>lQJPAii?**LheDX|SG)1X3eHG{8D@paTw`~t3}lk6~_pt71k
zwZ*YKrN`zc77YTyhtUo53DWu9oFWA$nSi$0t^4drx_=0Z8G=0}Ea5tJ`cZdNLP^hN
ze1IiCLYg{<+NWF`9S_V2$L{ZciBBsg2TMdc$G_8|zU~cJ5P5M(N`cM*0
z`~W}7xXu|OA#onotbJem?B9QW`~vV0PfeV|4Ffk#6tJk^Ru#8#N3pvm?%}>-4-_mZ
zv#D6iz_I~bpz=&cGJ7FVY_|3UN;~mqUtrdik^g!e_WjWZuOHAe=f(ps*z-nG*(c6Y
zb|6!M8Ml{tgQIkt^`R#tfkyL_d+2@foWP5QPA?nDXt=HWd!r#M=Km8GFv5v$M3#4C
zL$eo;M+1LXDiO7OPFuCMa2~S)W$jYNiiK6I7-(B?ux4Q$9RnK{Uue_9BXlf0#+EXf
z_yk*AJ?|z^Kb88Xf9MY~?$PXOxyd*^IFrzuq?sS`x#BU?7V<4+?7ZcQ85i}vkg5%t
zz6_IWqMvo2`|1g2)0ma0qJZyJYVNCX6`AgigMfD8`$xLCOHAT~2eo)+^%Wr0>cl!N
zhkwC;dHERPn+{(fR!{wE3_jbjvDduED~UDsIF
zv`YMrvOPs*3L|F>pD;$v+*kX@l
Date: Mon, 21 Nov 2016 12:42:17 +0000
Subject: [PATCH 0002/2305] Added array implementation of a stack
---
Data_Structures/Stack.class | Bin 947 -> 0 bytes
Data_Structures/Stacks.class | Bin 765 -> 0 bytes
2 files changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 Data_Structures/Stack.class
delete mode 100644 Data_Structures/Stacks.class
diff --git a/Data_Structures/Stack.class b/Data_Structures/Stack.class
deleted file mode 100644
index c82f0408d1a8a73efe485d9750399f9588f1e067..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 947
zcmZ{hUr!T36vfZ%PP^^0^be&77O@H{>;t^;hA|oTG$zLQ0sK(LGwZgj8Xr2dbLXDlId}Tw=hyE5wsFr!9=D3f;kI5@^|EH+j)l7d
zR!_Y>^xt~|Vqd_HV%6zB8V=Pv0pk@bW;_T5^7s9|A3qR~>-!r=+;#`2l$2Y3-+MOd
zwY}jB)ecyhYYjRoI8sAjpVOj@&-{p1twT-Up*%_)WjKn?1acQD7*T76+R9wtpsfr&
zuSUvkLjA$PYM#GM`=j&KAi7whaR~O2G
zgB1rB3J!{}9n7G>5J`tXMYn7Ps{dx|pndLjVl??&c|N2GLyP!jXkD^X%H4t>bCzp~
zr`NnUxG%Y1Al$|nhU;F!_-2n`y2cptb0RHsT_74nNCGvo#w?3ORg${|f-2^CB96BO
zS_sTft)3^LfV%tg5>lQJPAii?**LheDX|SG)1X3eHG{8D@paTw`~t3}lk6~_pt71k
zwZ*YKrN`zc77YTyhtUo53DWu9oFWA$nSi$0t^4drx_=0Z8G=0}Ea5tJ`cZdNLP^hN
ze1IiCLYg{<+NWF`9S_V2$L{ZciBBsg2TMdc$G_8|zU~cJ5P5M(N`cM*0
z`~W}7xXu|OA#onotbJem?B9QW`~vV0PfeV|4Ffk#6tJk^Ru#8#N3pvm?%}>-4-_mZ
zv#D6iz_I~bpz=&cGJ7FVY_|3UN;~mqUtrdik^g!e_WjWZuOHAe=f(ps*z-nG*(c6Y
zb|6!M8Ml{tgQIkt^`R#tfkyL_d+2@foWP5QPA?nDXt=HWd!r#M=Km8GFv5v$M3#4C
zL$eo;M+1LXDiO7OPFuCMa2~S)W$jYNiiK6I7-(B?ux4Q$9RnK{Uue_9BXlf0#+EXf
z_yk*AJ?|z^Kb88Xf9MY~?$PXOxyd*^IFrzuq?sS`x#BU?7V<4+?7ZcQ85i}vkg5%t
zz6_IWqMvo2`|1g2)0ma0qJZyJYVNCX6`AgigMfD8`$xLCOHAT~2eo)+^%Wr0>cl!N
zhkwC;dHERPn+{(fR!{wE3_jbjvDduED~UDsIF
zv`YMrvOPs*3L|F>pD;$v+*kX@l
Date: Mon, 21 Nov 2016 21:52:33 +0000
Subject: [PATCH 0003/2305] Added Queues and Priority Queues
---
Data_Structures/PriorityQueues.java | 68 +++++++++++++++++++++++
Data_Structures/Queues.java | 86 +++++++++++++++++++++++++++++
2 files changed, 154 insertions(+)
create mode 100644 Data_Structures/PriorityQueues.java
create mode 100644 Data_Structures/Queues.java
diff --git a/Data_Structures/PriorityQueues.java b/Data_Structures/PriorityQueues.java
new file mode 100644
index 000000000000..cacec5f33e36
--- /dev/null
+++ b/Data_Structures/PriorityQueues.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+class PriorityQueue{
+ private int maxSize;
+ private int[] queueArray;
+ private int nItems;
+
+ public PriorityQueue(int size){ //Constructor
+ maxSize = size;
+ queueArray = new int[size];
+ nItems = 0;
+ }
+
+ public void insert(int value){ //Inserts an element in it's appropriate place
+ if(nItems == 0){
+ queueArray[0] = value;
+ }
+ else{
+ int j = nItems;
+ while(j > 0 && queueArray[j-1] > value){
+ queueArray[j] = queueArray[j-1];
+ j--;
+ }
+ queueArray[j] = value;
+ }
+ nItems++;
+ }
+
+ public int remove(){ //Remove the element from the front of the queue
+ return queueArray[--nItems];
+ }
+
+ public int peek(){ //Checks what's at the front of the queue
+ return queueArray[nItems-1];
+ }
+
+ public boolean isEmpty(){ //Returns true is the queue is empty
+ return(nItems == 0);
+ }
+
+ public boolean isFull(){ //Returns true is the queue is full
+ return(nItems == maxSize);
+ }
+
+ public int getSize(){ //Returns the number of elements in the queue
+ return nItems;
+ }
+}
+//Example
+public class PriorityQueues{
+ 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.java b/Data_Structures/Queues.java
new file mode 100644
index 000000000000..c7725417954d
--- /dev/null
+++ b/Data_Structures/Queues.java
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+class Queue{
+ private int maxSize;
+ private int[] queueArray;
+ private int front;
+ private int rear;
+ private int nItems;
+
+ public Queue(int size){ //Constructor
+ maxSize = size;
+ queueArray = new int[size];
+ front = 0;
+ rear = -1;
+ nItems = 0;
+ }
+
+ public boolean insert(int x){ //Inserts an element at the rear of the queue
+ 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;
+ }
+
+ 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;
+ }
+
+ public int peekFront(){ //Checks what's at the front of the queue
+ return queueArray[front];
+ }
+
+ public int peekRear(){ //Checks what's at the rear of the queue
+ return queueArray[rear];
+ }
+
+ public boolean isEmpty(){ //Returns true is the queue is empty
+ return(nItems == 0);
+ }
+
+ public boolean isFull(){ //Returns true is the queue is full
+ return(nItems == maxSize);
+ }
+
+ public int getSize(){ //Returns the number of elements in the queue
+ return nItems;
+ }
+}
+//Example
+public class Queues{
+ 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
From ec2d4ccdc8edbe5bd7ddac75e5b47faed608ea12 Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Mon, 21 Nov 2016 22:08:00 +0000
Subject: [PATCH 0004/2305] fixing problem with folder
---
Data_Structures/PriorityQueues.java | 68 -----------------------
Data_Structures/Queues.java | 86 -----------------------------
2 files changed, 154 deletions(-)
delete mode 100644 Data_Structures/PriorityQueues.java
delete mode 100644 Data_Structures/Queues.java
diff --git a/Data_Structures/PriorityQueues.java b/Data_Structures/PriorityQueues.java
deleted file mode 100644
index cacec5f33e36..000000000000
--- a/Data_Structures/PriorityQueues.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-class PriorityQueue{
- private int maxSize;
- private int[] queueArray;
- private int nItems;
-
- public PriorityQueue(int size){ //Constructor
- maxSize = size;
- queueArray = new int[size];
- nItems = 0;
- }
-
- public void insert(int value){ //Inserts an element in it's appropriate place
- if(nItems == 0){
- queueArray[0] = value;
- }
- else{
- int j = nItems;
- while(j > 0 && queueArray[j-1] > value){
- queueArray[j] = queueArray[j-1];
- j--;
- }
- queueArray[j] = value;
- }
- nItems++;
- }
-
- public int remove(){ //Remove the element from the front of the queue
- return queueArray[--nItems];
- }
-
- public int peek(){ //Checks what's at the front of the queue
- return queueArray[nItems-1];
- }
-
- public boolean isEmpty(){ //Returns true is the queue is empty
- return(nItems == 0);
- }
-
- public boolean isFull(){ //Returns true is the queue is full
- return(nItems == maxSize);
- }
-
- public int getSize(){ //Returns the number of elements in the queue
- return nItems;
- }
-}
-//Example
-public class PriorityQueues{
- 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.java b/Data_Structures/Queues.java
deleted file mode 100644
index c7725417954d..000000000000
--- a/Data_Structures/Queues.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-class Queue{
- private int maxSize;
- private int[] queueArray;
- private int front;
- private int rear;
- private int nItems;
-
- public Queue(int size){ //Constructor
- maxSize = size;
- queueArray = new int[size];
- front = 0;
- rear = -1;
- nItems = 0;
- }
-
- public boolean insert(int x){ //Inserts an element at the rear of the queue
- 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;
- }
-
- 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;
- }
-
- public int peekFront(){ //Checks what's at the front of the queue
- return queueArray[front];
- }
-
- public int peekRear(){ //Checks what's at the rear of the queue
- return queueArray[rear];
- }
-
- public boolean isEmpty(){ //Returns true is the queue is empty
- return(nItems == 0);
- }
-
- public boolean isFull(){ //Returns true is the queue is full
- return(nItems == maxSize);
- }
-
- public int getSize(){ //Returns the number of elements in the queue
- return nItems;
- }
-}
-//Example
-public class Queues{
- 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
From 67d3bf5ee126b30592d556c364de1a980c9bce8f Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Mon, 21 Nov 2016 22:13:34 +0000
Subject: [PATCH 0005/2305] Fixing folder problems
---
data_structures/PriorityQueues.java | 68 +++++++++++++++++++++++
data_structures/Queues.java | 86 +++++++++++++++++++++++++++++
2 files changed, 154 insertions(+)
create mode 100644 data_structures/PriorityQueues.java
create mode 100644 data_structures/Queues.java
diff --git a/data_structures/PriorityQueues.java b/data_structures/PriorityQueues.java
new file mode 100644
index 000000000000..cacec5f33e36
--- /dev/null
+++ b/data_structures/PriorityQueues.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+class PriorityQueue{
+ private int maxSize;
+ private int[] queueArray;
+ private int nItems;
+
+ public PriorityQueue(int size){ //Constructor
+ maxSize = size;
+ queueArray = new int[size];
+ nItems = 0;
+ }
+
+ public void insert(int value){ //Inserts an element in it's appropriate place
+ if(nItems == 0){
+ queueArray[0] = value;
+ }
+ else{
+ int j = nItems;
+ while(j > 0 && queueArray[j-1] > value){
+ queueArray[j] = queueArray[j-1];
+ j--;
+ }
+ queueArray[j] = value;
+ }
+ nItems++;
+ }
+
+ public int remove(){ //Remove the element from the front of the queue
+ return queueArray[--nItems];
+ }
+
+ public int peek(){ //Checks what's at the front of the queue
+ return queueArray[nItems-1];
+ }
+
+ public boolean isEmpty(){ //Returns true is the queue is empty
+ return(nItems == 0);
+ }
+
+ public boolean isFull(){ //Returns true is the queue is full
+ return(nItems == maxSize);
+ }
+
+ public int getSize(){ //Returns the number of elements in the queue
+ return nItems;
+ }
+}
+//Example
+public class PriorityQueues{
+ 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.java b/data_structures/Queues.java
new file mode 100644
index 000000000000..c7725417954d
--- /dev/null
+++ b/data_structures/Queues.java
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+class Queue{
+ private int maxSize;
+ private int[] queueArray;
+ private int front;
+ private int rear;
+ private int nItems;
+
+ public Queue(int size){ //Constructor
+ maxSize = size;
+ queueArray = new int[size];
+ front = 0;
+ rear = -1;
+ nItems = 0;
+ }
+
+ public boolean insert(int x){ //Inserts an element at the rear of the queue
+ 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;
+ }
+
+ 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;
+ }
+
+ public int peekFront(){ //Checks what's at the front of the queue
+ return queueArray[front];
+ }
+
+ public int peekRear(){ //Checks what's at the rear of the queue
+ return queueArray[rear];
+ }
+
+ public boolean isEmpty(){ //Returns true is the queue is empty
+ return(nItems == 0);
+ }
+
+ public boolean isFull(){ //Returns true is the queue is full
+ return(nItems == maxSize);
+ }
+
+ public int getSize(){ //Returns the number of elements in the queue
+ return nItems;
+ }
+}
+//Example
+public class Queues{
+ 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
From c65e562e7040c87d93c8818e5f35dddaa0662ee2 Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Tue, 22 Nov 2016 15:55:15 +0000
Subject: [PATCH 0006/2305] Added Queues, Priority Queues and Linked Lists
---
data_structures/LinkedLists.java | 69 +++++++++++++++++++++++++++++
data_structures/PriorityQueues.java | 4 +-
2 files changed, 71 insertions(+), 2 deletions(-)
create mode 100644 data_structures/LinkedLists.java
diff --git a/data_structures/LinkedLists.java b/data_structures/LinkedLists.java
new file mode 100644
index 000000000000..1f1d323010aa
--- /dev/null
+++ b/data_structures/LinkedLists.java
@@ -0,0 +1,69 @@
+/*
+ * A linked list is similar to an array, it holds 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 grows and shrinks as it is edited.
+ * This is an example of a singly linked list. Elements can only be added/removed at the head/front of the list.
+*/
+class LinkedList{
+ private Link head; //Head refers to the front of the list
+
+ public LinkedList(){
+ head = null;
+ }
+
+ public void insertHead(int x){ //Insert an element at the head
+ Link newLink = new Link(x); //Create a new link with a value attached to it
+ newLink.next = head; //Set the new link to point to the current head
+ head = newLink; //Now set the new link to be the head
+ }
+
+ public Link deleteHead(){ //Delete the element at the head
+ Link 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;
+ }
+
+ public boolean isEmpty(){ //Returns true if list is empty
+ return(head == null);
+ }
+
+ public void display(){ //Prints contents of the list
+ Link current = head;
+ while(current!=null){
+ current.displayLink();
+ current = current.next;
+ }
+ System.out.println();
+ }
+}
+
+class Link{
+ public int value;
+ public Link next; //This is what the link will point to
+
+ public Link(int valuein){
+ value = valuein;
+ }
+
+ public void displayLink(){
+ System.out.print(value+" ");
+ }
+}
+
+//Example
+public class LinkedLists{
+ public static void main(String args[]){
+ LinkedList myList = new LinkedList();
+
+ 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
+ }
+}
\ No newline at end of file
diff --git a/data_structures/PriorityQueues.java b/data_structures/PriorityQueues.java
index cacec5f33e36..a0c1af1a0da7 100644
--- a/data_structures/PriorityQueues.java
+++ b/data_structures/PriorityQueues.java
@@ -22,10 +22,10 @@ public void insert(int value){ //Inserts an element in it's appropriate place
else{
int j = nItems;
while(j > 0 && queueArray[j-1] > value){
- queueArray[j] = queueArray[j-1];
+ queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
j--;
}
- queueArray[j] = value;
+ queueArray[j] = value; //Once the correct position is found the value is inserted
}
nItems++;
}
From c97d806ba0393c24bdaf8cc4626623b33cc89011 Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Wed, 23 Nov 2016 18:07:18 +0000
Subject: [PATCH 0007/2305] Added Sieve of Eratosthenes algorithm for finding
primes
---
FindingPrimes.java | 30 ++++++++++++++++++++++++++++++
1 file changed, 30 insertions(+)
create mode 100644 FindingPrimes.java
diff --git a/FindingPrimes.java b/FindingPrimes.java
new file mode 100644
index 000000000000..ecf3f7b4b82f
--- /dev/null
+++ b/FindingPrimes.java
@@ -0,0 +1,30 @@
+/*
+ * The Sieve of Eratosthenes is an algorithm used to find prime numbers, up to a given value.
+ * Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
+*/
+public class FindingPrimes{
+ public static void main(String args[]){
+ SOE(20); //Example: Finds all the primes up to 20
+ }
+
+ public static void SOE(int n){
+ boolean sieve[] = new boolean[n];
+
+ int check = (int)Math.round(Math.sqrt(n)); //No need to check for multiples past the square root of n
+
+ sieve[0] = false;
+ sieve[1] = false;
+ for(int i = 2; i < n; i++)
+ sieve[i] = true; //Set every index to true except index 0 and 1
+
+ for(int i = 2; i< check; i++){
+ if(sieve[i]==true) //If i is a prime
+ for(int j = i+i; j < n; j+=i) //Step through the array in increments of i(the multiples of the prime)
+ sieve[j] = false; //Set every multiple of i to false
+ }
+ for(int i = 0; i< n; i++){
+ if(sieve[i]==true)
+ System.out.print(i+" "); //In this example it will print 2 3 5 7 11 13 17 19
+ }
+ }
+}
\ No newline at end of file
From a56dc240bead7ed575b53b2c92e4bf1cb70d5369 Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Mon, 28 Nov 2016 22:49:28 +0000
Subject: [PATCH 0008/2305] Added doubly linked list
---
data_structures/DoublyLinkedList.java | 141 ++++++++++++++++++
...LinkedLists.java => SinglyLinkedList.java} | 2 +-
2 files changed, 142 insertions(+), 1 deletion(-)
create mode 100644 data_structures/DoublyLinkedList.java
rename data_structures/{LinkedLists.java => SinglyLinkedList.java} (98%)
diff --git a/data_structures/DoublyLinkedList.java b/data_structures/DoublyLinkedList.java
new file mode 100644
index 000000000000..f8411994f7c7
--- /dev/null
+++ b/data_structures/DoublyLinkedList.java
@@ -0,0 +1,141 @@
+/*
+ * A linked list is similar to an array, it holds 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 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.
+*/
+class LinkedList{
+ private Link head; //Head refers to the front of the list
+ private Link tail; //Tail refers to the back of the list
+
+ public LinkedList(){
+ head = null;
+ tail = null;
+ }
+
+ public void insertHead(int x){ //Insert an element at the head
+ 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
+ }
+
+ 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) -->
+ }
+
+ public Link deleteHead(){ //Delete the element at the head
+ 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;
+ }
+
+ public Link deleteTail(){
+ Link temp = tail;
+ tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
+ tail.next = null; // 2ndLast(tail) --> null
+ return temp;
+ }
+
+ 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;
+ }
+
+ 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
+ }
+ }
+
+ public boolean isEmpty(){ //Returns true if list is empty
+ return(head == null);
+ }
+
+ public void display(){ //Prints contents of the list
+ Link current = head;
+ while(current!=null){
+ current.displayLink();
+ current = current.next;
+ }
+ System.out.println();
+ }
+}
+
+class Link{
+ public int value;
+ public Link next; //This points to the link in front of the new link
+ public Link previous; //This points to the link behind the new link
+
+ public Link(int value){
+ this.value = value;
+ }
+
+ public void displayLink(){
+ System.out.print(value+" ");
+ }
+}
+
+//Example
+public class DoublyLinkedList{
+ public static void main(String args[]){
+ LinkedList myList = new LinkedList();
+
+ 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/LinkedLists.java b/data_structures/SinglyLinkedList.java
similarity index 98%
rename from data_structures/LinkedLists.java
rename to data_structures/SinglyLinkedList.java
index 1f1d323010aa..75660c7316fb 100644
--- a/data_structures/LinkedLists.java
+++ b/data_structures/SinglyLinkedList.java
@@ -50,7 +50,7 @@ public void displayLink(){
}
//Example
-public class LinkedLists{
+public class SinglyLinkedList{
public static void main(String args[]){
LinkedList myList = new LinkedList();
From 4c14273d17bc3196d6b76d58fc2a9d6b7b222548 Mon Sep 17 00:00:00 2001
From: Nicolas Renard
Date: Tue, 13 Dec 2016 15:42:35 +0100
Subject: [PATCH 0009/2305] Adding all heap classes and interface and specific
exception.
---
data_structures/heaps/EmptyHeapException.java | 18 +++
data_structures/heaps/Heap.java | 39 ++++++
data_structures/heaps/HeapElement.java | 132 ++++++++++++++++++
data_structures/heaps/MaxHeap.java | 109 +++++++++++++++
data_structures/heaps/MinHeap.java | 109 +++++++++++++++
5 files changed, 407 insertions(+)
create mode 100644 data_structures/heaps/EmptyHeapException.java
create mode 100644 data_structures/heaps/Heap.java
create mode 100644 data_structures/heaps/HeapElement.java
create mode 100644 data_structures/heaps/MaxHeap.java
create mode 100644 data_structures/heaps/MinHeap.java
diff --git a/data_structures/heaps/EmptyHeapException.java b/data_structures/heaps/EmptyHeapException.java
new file mode 100644
index 000000000000..b7d853c56845
--- /dev/null
+++ b/data_structures/heaps/EmptyHeapException.java
@@ -0,0 +1,18 @@
+/**
+ *
+ */
+package heaps;
+
+/**
+ * @author Nicolas Renard
+ * Exception to be thrown if the getElement method is used on an empty heap.
+ *
+ */
+@SuppressWarnings("serial")
+public class EmptyHeapException extends Exception {
+
+ public EmptyHeapException(String message) {
+ super(message);
+ }
+
+}
diff --git a/data_structures/heaps/Heap.java b/data_structures/heaps/Heap.java
new file mode 100644
index 000000000000..625bc05a992b
--- /dev/null
+++ b/data_structures/heaps/Heap.java
@@ -0,0 +1,39 @@
+package heaps;
+
+/**
+ * Interface common to heap data structures.
+ * 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).
+ * @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
new file mode 100644
index 000000000000..e0cc93ccbfe0
--- /dev/null
+++ b/data_structures/heaps/HeapElement.java
@@ -0,0 +1,132 @@
+/**
+ *
+ */
+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
new file mode 100644
index 000000000000..e4e1a89fa63f
--- /dev/null
+++ b/data_structures/heaps/MaxHeap.java
@@ -0,0 +1,109 @@
+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 ((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
new file mode 100644
index 000000000000..5714c74cfe1b
--- /dev/null
+++ b/data_structures/heaps/MinHeap.java
@@ -0,0 +1,109 @@
+/**
+ *
+ */
+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 ((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");
+ }
+ }
+}
From c3dda1f0ddf1f528cb85f94a737ccb6b391d7a26 Mon Sep 17 00:00:00 2001
From: Nicolas Renard
Date: Tue, 13 Dec 2016 15:52:17 +0100
Subject: [PATCH 0010/2305] Adding exception throws in case of handling empty
heap.
---
data_structures/heaps/MaxHeap.java | 1 +
data_structures/heaps/MinHeap.java | 1 +
2 files changed, 2 insertions(+)
diff --git a/data_structures/heaps/MaxHeap.java b/data_structures/heaps/MaxHeap.java
index e4e1a89fa63f..6768d4871e8a 100644
--- a/data_structures/heaps/MaxHeap.java
+++ b/data_structures/heaps/MaxHeap.java
@@ -84,6 +84,7 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
+ if (isempty(maxHeap)) throw new EmptyHeapException("Attempt to delete an element from an empty heap");
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()));
diff --git a/data_structures/heaps/MinHeap.java b/data_structures/heaps/MinHeap.java
index 5714c74cfe1b..cd484d79fe55 100644
--- a/data_structures/heaps/MinHeap.java
+++ b/data_structures/heaps/MinHeap.java
@@ -87,6 +87,7 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
+ if (isempty(maxHeap)) throw new EmptyHeapException("Attempt to delete an element from an empty heap");
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()));
From 4338456f9cbdbe4100d554239806efcae844ca48 Mon Sep 17 00:00:00 2001
From: Nicolas Renard
Date: Tue, 13 Dec 2016 16:09:28 +0100
Subject: [PATCH 0011/2305] Adding computing time (O(log n)) in help text.
---
data_structures/heaps/Heap.java | 2 ++
1 file changed, 2 insertions(+)
diff --git a/data_structures/heaps/Heap.java b/data_structures/heaps/Heap.java
index 625bc05a992b..02b2ba270918 100644
--- a/data_structures/heaps/Heap.java
+++ b/data_structures/heaps/Heap.java
@@ -8,6 +8,8 @@
* 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
*
*
From 266538299a9c16ac39cab6358818e3825b402f2c Mon Sep 17 00:00:00 2001
From: Rian Gallagher
Date: Sun, 12 Feb 2017 21:50:39 +0000
Subject: [PATCH 0012/2305] Added binary tree
---
data_structures/BinaryTree.java | 192 ++++++++++++++++++++++++++++++++
1 file changed, 192 insertions(+)
create mode 100644 data_structures/BinaryTree.java
diff --git a/data_structures/BinaryTree.java b/data_structures/BinaryTree.java
new file mode 100644
index 000000000000..90a6d98023a1
--- /dev/null
+++ b/data_structures/BinaryTree.java
@@ -0,0 +1,192 @@
+//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
+class Node{
+ public int data;
+ public Node left;
+ public Node right;
+ public Node parent;
+
+ public Node(int value){
+ data = value;
+ left = null;
+ right = null;
+ parent = null;
+ }
+}
+
+class Tree{
+ private Node root;
+
+ public Tree(){
+ root = null;
+ }
+ //Returns the node if it finds it, otherwise returns the parent
+ public Node find(int key){
+ Node current = root;
+ Node last = root;
+ while(current != null){
+ last = current;
+ if(key < current.data)
+ current = current.left;
+ else if(key > current.data)
+ current = current.right;
+ //If you find the value return it
+ else
+ return current;
+ }
+ return last;
+ }
+
+ //Inserts the given value
+ 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 the given value
+ 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 succesor = findSuccesor(temp);
+
+ //The left tree of temp is made the left tree of the successor
+ succesor.left = temp.left;
+ succesor.left.parent = succesor;
+
+ //If the successor has a right child, the child's grandparent is it's new parent
+ if(succesor.right != null && succesor.parent != temp){
+ succesor.right.parent = succesor.parent;
+ succesor.parent.left = succesor.right;
+ succesor.right = temp.right;
+ succesor.right.parent = succesor;
+ }
+ if(temp == root){
+ succesor.parent = null;
+ root = succesor;
+ return true;
+ }
+
+ //If you're not deleting the root
+ else{
+ succesor.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 = succesor;
+ else
+ temp.parent.left = succesor;
+ 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;
+ }
+ }
+ }
+
+ //Move right once and go left down the tree as far as you can
+ public Node findSuccesor(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;
+ }
+
+ public Node getRoot(){
+ return root;
+ }
+
+ //Prints leftChild - root - rightChild
+ public void inOrder(Node localRoot){
+ if(localRoot != null){
+ inOrder(localRoot.left);
+ System.out.print(localRoot.data + " ");
+ inOrder(localRoot.right);
+ }
+ }
+ //Prints root - leftChild - rightChild
+ public void preOrder(Node localRoot){
+ if(localRoot != null){
+ System.out.print(localRoot.data + " ");
+ preOrder(localRoot.left);
+ preOrder(localRoot.right);
+ }
+ }
+ //Prints rightChild - leftChild - root
+ public void postOrder(Node localRoot){
+ if(localRoot != null){
+ postOrder(localRoot.left);
+ postOrder(localRoot.right);
+ System.out.print(localRoot.data + " ");
+ }
+ }
+}
\ No newline at end of file
From 23a099d23202172fe6668526d6397b385739da91 Mon Sep 17 00:00:00 2001
From: Yash Bhansali
Date: Fri, 10 Mar 2017 00:41:42 +0530
Subject: [PATCH 0013/2305] Stack List Implementation
---
data_structures/Stacks.java | 89 +++++++++++++++++++++++++++++++------
1 file changed, 75 insertions(+), 14 deletions(-)
diff --git a/data_structures/Stacks.java b/data_structures/Stacks.java
index 7fdf6133fb45..18139147fed6 100644
--- a/data_structures/Stacks.java
+++ b/data_structures/Stacks.java
@@ -38,20 +38,81 @@ 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 ArrayList Implementation of stack , Where size is not
+ a problem we can extend the stack as much as we want*/
+class Stack2{
+
+
+ ArrayList stackList;
+
+ Stack2(){ //constructor
+ stackList=new ArrayList<>();
+ }
+
+
+ void push(int value){ //adds value to the end of list which is the top for stack
+ stackList.add(value);
+ }
+
+ int pop(){ //pops last element of list which is indeed the top for Stack
+
+ 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;
+ }
+
+ }
+
+ boolean isEmpty(){ //checks for empty Stack
+ if(stackList.isEmpty())
+ return true;
+
+ else return false;
+
+ }
+
+ int peek(){ //top element of stack
+ return stackList.get(stackList.size()-1);
+ }
+ }
+
//Example
public class Stacks{
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(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
- }
-}
\ No newline at end of file
+ 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
+ }
+}
From 10c9e6adeccf515c367b9d52c0f7136ba35fc7b1 Mon Sep 17 00:00:00 2001
From: Anthony Chan
Date: Wed, 15 Mar 2017 00:06:52 -0400
Subject: [PATCH 0014/2305] Add Linear Search
---
LinearSearch.java | 48 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
create mode 100644 LinearSearch.java
diff --git a/LinearSearch.java b/LinearSearch.java
new file mode 100644
index 000000000000..820785938bbb
--- /dev/null
+++ b/LinearSearch.java
@@ -0,0 +1,48 @@
+import java.util.Scanner;
+
+public class LinearSearch{
+ //Main method
+ public static void main(String[] args){
+
+ Scanner input = new Scanner(System.in);
+ int[] myArray;
+ int size = 0;
+
+ //Prompt user to create array and its elements
+ System.out.print("Enter the array size: ");
+ size = input.nextInt();
+ myArray = new int[size];
+ for (int i = 0; i < size; i++){
+ System.out.print("For index " + i + ", enter an integer: ");
+ myArray[i] = input.nextInt();
+ }
+
+ //Prompt user to search for particular element
+ System.out.print("Enter integer to search for: ");
+ int key = input.nextInt();
+
+ //Output array and index of target element, if found
+ printarray(myArray);
+ System.out.printf("The integer %d is found in index %d\n", key, linearsearch(myArray, key));
+
+ }
+
+ //Linear search method
+ public static int linearsearch(int[] list, int key){
+
+ for (int i = 0; i< list.length; i++){
+ if (list[i] == key){
+ return i;
+ }
+
+ } return -1;
+ }
+ //Helper method
+ public static void printarray(int[] a){
+ System.out.print("The array is: ");
+ for( int d: a){
+ System.out.print(d+" ");
+ }
+ System.out.println();
+ }
+}
\ No newline at end of file
From c2c6c8b66f22d980bd780a4d4031d5232d598b83 Mon Sep 17 00:00:00 2001
From: Anthony Chan
Date: Wed, 15 Mar 2017 00:17:33 -0400
Subject: [PATCH 0015/2305] Implement quicksort
---
Quicksort.java | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 71 insertions(+)
create mode 100644 Quicksort.java
diff --git a/Quicksort.java b/Quicksort.java
new file mode 100644
index 000000000000..f693c42b6753
--- /dev/null
+++ b/Quicksort.java
@@ -0,0 +1,71 @@
+import java.util.Scanner;
+
+public class Quicksort{
+
+ public static void main(String[] args){
+ Scanner input = new Scanner(System.in);
+ int[] array;
+ int size = 0;
+
+ //Prompt user to create array and its elements
+ System.out.print("Enter the size of the array: ");
+ size = input.nextInt();
+ array = new int[size];
+ for (int i = 0; i < size; i++){
+ System.out.print("For index " + i + ", give an integer input: ");
+ array[i] = input.nextInt();
+ }
+
+ //Output inputted array
+ System.out.println("The array is: ");
+ printarray(array);
+ System.out.println();
+
+ //Run quicksort, and output sorted array
+ quicksort(array, 0, array.length - 1);
+ System.out.println("The sorted array is: ");
+ printarray(array);
+ System.out.println();
+ }
+
+ //Quicksort Method
+ public static void quicksort(int[] ar, int start, int end){
+ int[] array;
+
+ int i = start, j = end;
+ if (end-start >= 1){
+ int pivot = ar[end];
+ while (i< j){
+ while (ar[i]=pivot && j>start){
+ j--;
+ }
+ if (i
Date: Thu, 16 Mar 2017 10:39:23 -0400
Subject: [PATCH 0016/2305] Implement factorial
---
Factorial.java | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 Factorial.java
diff --git a/Factorial.java b/Factorial.java
new file mode 100644
index 000000000000..f675ba6a1273
--- /dev/null
+++ b/Factorial.java
@@ -0,0 +1,35 @@
+import java.util.Scanner;
+
+public class Factorial{
+
+ public static void main(String[] args){
+ Scanner input = new Scanner(System.in);
+ //Prompt user to enter integer
+ System.out.print("Enter a non-negative integer: ");
+
+ //Proceed with factorial calculation only if inputted number is not negative
+ if(input.hasNextInt()){
+ int number = input.nextInt();
+ if (number < 0){
+ System.out.print("Cannot execute. Please enter a non-negative integer: ");
+ number = input.nextInt();
+ } else {
+ //Output of factorial for any non-negative number
+ System.out.println("The factorial of "+number+" will yield: "+factorial(number));
+ }
+ }
+ }
+
+ //Factorial method
+ public static long factorial(int n){
+
+ if (n==0){
+ return 1;
+ } else if (n==1){
+ return 1;
+ } else {
+ return n * factorial(n-1);
+ }
+
+ }
+}
\ No newline at end of file
From 63726a98a104cfdf18691c16482613cc89dda117 Mon Sep 17 00:00:00 2001
From: Mayank Kumar Jha
Date: Fri, 17 Mar 2017 19:25:24 +0530
Subject: [PATCH 0017/2305] Create dfs.java
---
dfs.java | 43 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 dfs.java
diff --git a/dfs.java b/dfs.java
new file mode 100644
index 000000000000..52e642725187
--- /dev/null
+++ b/dfs.java
@@ -0,0 +1,43 @@
+import java.util.*;
+
+public class App{
+
+
+ public static void dfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
+ byte []b=new byte[vertices]; //flag container containing status of each vertices
+ Arrays.fill(b,(byte)-1); //status initialization
+ /* code status
+ -1 = ready
+ 0 = waiting
+ 1 = processed */
+
+
+ Stack st=new Stack<>(); //operational stack
+ st.push(source); //assigning source
+ while(!st.isEmpty()){
+ b[st.peek()]=(byte)0; //assigning waiting status
+ System.out.println(st.peek());
+ int pop=st.pop();
+ b[pop]=(byte)1; //assigning processed status
+ for(int i=0;i
Date: Fri, 17 Mar 2017 19:31:25 +0530
Subject: [PATCH 0018/2305] bfs.java
---
bfs.java | 42 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
create mode 100644 bfs.java
diff --git a/bfs.java b/bfs.java
new file mode 100644
index 000000000000..a44ec4897e1d
--- /dev/null
+++ b/bfs.java
@@ -0,0 +1,42 @@
+import java.util.*;
+
+public class App{
+
+ public static void bfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
+ byte []b=new byte[vertices]; //flag container containing status of each vertices
+ Arrays.fill(b,(byte)-1); //status initialization
+ /* code status
+ -1 = ready
+ 0 = waiting
+ 1 = processed */
+
+ Queue st=new LinkedList<>(); //operational stack
+ st.add(source); //assigning source
+ while(!st.isEmpty()){
+ b[st.peek()]=(byte)0; //assigning waiting status
+ System.out.println(st.element());
+ int pop=st.element();
+ b[pop]=(byte)1; //assigning processed status
+ st.remove(); //removing head of the queue
+ for(int i=0;i
Date: Tue, 28 Mar 2017 16:17:37 +0530
Subject: [PATCH 0019/2305] Added decimal to binary conversion
---
.DS_Store | Bin 0 -> 6148 bytes
Decimal to Binary.java | 19 +++++++++++++++++++
2 files changed, 19 insertions(+)
create mode 100644 .DS_Store
create mode 100644 Decimal to Binary.java
diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..2eade9623e392215bfd8e6436bdbfeb203e1ebef
GIT binary patch
literal 6148
zcmeHKOHKko5PhXAP$PawjLTWNBJlwp2V%eLRu%&%vjM3n)
z%hj)YK%d@5GwokL*l(c4aYihc7!n8c)+CPEy2da&y3{^c@1R1hCZp)lLzm-^IDV9g
zYfdEcM1L}wum%c@t!`s$1Re7?!&cs?pJrj3w#sD7>Nd{ILr)`^$%Hcbl45cl$JDRm
z;Y%E*EsHqe*h5+?^Bpp9zxYiUmuW9sIJMd990qwvn=0a;aZ!#7|i%&CFbM32)@vUdPXx98i5jW}l
z+FzV}m~&ttFz~Gm=>8C~D8?QWhqiUFvMT^F$8Hn0_47b&B9F1h#37$h#F-MEsrV~~
zICJ(#UN82TICSO^fB6tUviKW{*y!{hnK~qP80x@4U?9uDvirNK=l|jC`+wFb{0j^O
z2L2TTlB--)$_&Y$ty972SsSrjv8bqC;?PW3`Qz9cdKB-nnDAMo4PxvuamXG@_z*A}
LLKPVJQ3l=t)Wh0<
literal 0
HcmV?d00001
diff --git a/Decimal to Binary.java b/Decimal to Binary.java
new file mode 100644
index 000000000000..e89b65fade03
--- /dev/null
+++ b/Decimal to Binary.java
@@ -0,0 +1,19 @@
+#import java.util.*;
+class Decimal_Binary
+{
+ public static void main(String args[])
+ {
+ Scanner sc=new Scanner(System.in);
+ int n,k,s=0,c=0,d;
+ n=sc.nextInt();
+ k=n;
+ while(k!=0)
+ {
+ d=k%2;
+ s=s+d*(int)Math.pow(10,c++);
+ k/=2;
+ }//converting decimal to binary
+ System.out.println("Decimal number:"+n);
+ System.out.println("Binary equivalent:"+s);
+ }
+}
From 025257206c5284db4a862ab81c8f2ff5955a634c Mon Sep 17 00:00:00 2001
From: Shivam Singhal
Date: Tue, 28 Mar 2017 16:30:18 +0530
Subject: [PATCH 0020/2305] Added Binary to Decimal conversion.
---
.DS_Store | Bin 6148 -> 6148 bytes
Binary to Decimal.java | 19 +++++++++++++++++++
2 files changed, 19 insertions(+)
create mode 100644 Binary to Decimal.java
diff --git a/.DS_Store b/.DS_Store
index 2eade9623e392215bfd8e6436bdbfeb203e1ebef..4cf14ef7f27b85cdb617e6cd45d6e716b9e2546a 100644
GIT binary patch
delta 75
zcmZoMXfc@J&&aniU^g=(-((&ZcX=@eCx%RhJcdMuB8Ex^1%?uad?4w
Date: Tue, 28 Mar 2017 19:21:53 +0530
Subject: [PATCH 0021/2305] Added Decimal to Octal conversion.
---
.DS_Store | Bin 6148 -> 6148 bytes
Decimal to octal.java | 19 +++++++++++++++++++
2 files changed, 19 insertions(+)
create mode 100644 Decimal to octal.java
diff --git a/.DS_Store b/.DS_Store
index 4cf14ef7f27b85cdb617e6cd45d6e716b9e2546a..1a232cde137af2184269187bf1ffab4b548ca660 100644
GIT binary patch
delta 56
zcmZoMXfc@J&&a*ksrkD;O9Um^UY}
MMl)?@=lIJH0E71p0{{R3
delta 32
ocmZoMXfc@J&&aniU^g=(-)0_`SjNqpSwom6Hh67j=lIJH0Hw
Date: Sat, 1 Apr 2017 23:42:34 +0530
Subject: [PATCH 0022/2305] Changes in for loop for sorting
This would decrease the number of comparisons in the loop used for sorting.
---
Bubble Sort.java | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/Bubble Sort.java b/Bubble Sort.java
index b1147d1ba637..a374d9ff7673 100644
--- a/Bubble Sort.java
+++ b/Bubble Sort.java
@@ -15,15 +15,15 @@ public static void main(String[] args)
}
//Sorting
- for(int i=0; i<6; i++)
+ for(int i=0; i<5; i++)
{
- for(int j=0; j<5; j++)
+ for(int j=i+1; j<6; j++)
{
- if(array[j]>array[j+1])
+ if(array[j]>array[i])
{
int temp=array[j];
- array[j]=array[j+1];
- array[j+1]=temp;
+ array[j]=array[i];
+ array[i]=temp;
}
}
}
@@ -35,4 +35,4 @@ public static void main(String[] args)
}
}
-}
\ No newline at end of file
+}
From b0027cd585746ff82bee16b18259a195e22a8cfc Mon Sep 17 00:00:00 2001
From: Ashish Agarwal
Date: Sat, 8 Apr 2017 18:26:06 +0530
Subject: [PATCH 0023/2305] Counting words of a string
---
.DS_Store | Bin 6148 -> 8196 bytes
countwords.java | 23 +++++++++++++++++++++++
2 files changed, 23 insertions(+)
create mode 100644 countwords.java
diff --git a/.DS_Store b/.DS_Store
index 1a232cde137af2184269187bf1ffab4b548ca660..dd05b9be5a8cdaa608a8a520040e4f99e574da1b 100644
GIT binary patch
delta 170
zcmZoMXmOBWU|?W$DortDU;r^WfEYvza8E20o2aMAD6lbLH}hr%jz7$c**Q2SHn1=X
zOy*&^DxA!a&rr&c$56sh4rCQEq%aguc3_p@V!Qz~uL5WS`{o-gJd7+r7VG90tW01Q
z%j9=#%RoYGlV`98ZdT`c&depj4dlCmY}_o!@tt`xzli5#e;y7FMu=k=HplbKVFmzW
CSs~c~
delta 135
zcmZp1XfcprU|?W$DortDU=RQ@Ie-{Mvv5r;6q~50$jHAjU^g=(|70G4tDEHonHgFB
z1HooBAtnfGvX1aFu+Zdd!hsX3
Date: Thu, 13 Apr 2017 11:54:22 -0600
Subject: [PATCH 0026/2305] Create InsertionSortInteger
---
InsertionSortInteger | 56 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
create mode 100644 InsertionSortInteger
diff --git a/InsertionSortInteger b/InsertionSortInteger
new file mode 100644
index 000000000000..b457ae137312
--- /dev/null
+++ b/InsertionSortInteger
@@ -0,0 +1,56 @@
+package sorts;
+/**
+ * This is my implementation of an insertion sort.
+ *
+ * I decided to do this when i didn't feel comfortable enough about implementing
+ * different types of sorts, so this is my trial and error to try and get myself to implement
+ * the various sorts correctly.
+ *
+ * @author Kody C. Kendall
+ *
+ */
+public class InsertionSort {
+
+
+ public int[] insertionIntArraySort(int[] initialArray){
+
+ int[] sortedArray = new int[initialArray.length];
+
+ //Marking first element as sorted.
+ sortedArray[0] = initialArray[0];
+
+ //For each element in the initialArray
+ for (int index = 1; index < initialArray.length; index++){
+
+ //Finding the last index that was sorted
+ int lastSortedIndex = index;
+
+ //Extracting the next element to be compared w/ other sorted elements from initial array
+ int extractedElement = initialArray[index];
+
+ //Compare the values of the sorted index to the current extractedElement
+ for (lastSortedIndex = index; lastSortedIndex > 0; lastSortedIndex--){
+
+ //If our extracted element is smaller than element to the right, switch them.
+ if (sortedArray[lastSortedIndex-1] > extractedElement){
+ //move the element to the left of extractedElement to the right in sortedArray
+ sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
+ //And move the current extractedElement to the left one (since it's smaller).
+ sortedArray[lastSortedIndex-1] = extractedElement;
+ }
+ else{
+ //insert element where it is.
+ sortedArray[lastSortedIndex] = extractedElement;
+ //Terminating loop since element is in the right spot.
+ break;
+ }
+
+ }
+
+ }
+
+ return sortedArray;
+
+ }
+
+}
From 94871b7e6a6583884d90004a939da89d5c479429 Mon Sep 17 00:00:00 2001
From: Zachary Jones
Date: Sun, 16 Apr 2017 10:44:08 -0700
Subject: [PATCH 0027/2305] Added JavaDoc to BinarySearch.java
I wanted to see if you would like me to add to your repository with Javadoc.
---
Binary Search.java | 27 ++++++++++++++++++++++++---
1 file changed, 24 insertions(+), 3 deletions(-)
diff --git a/Binary Search.java b/Binary Search.java
index a108de7e87f8..25814197fd23 100644
--- a/Binary Search.java
+++ b/Binary Search.java
@@ -1,10 +1,23 @@
import java.util.Scanner;
+/**
+ * Implements a Binary Search in Java
+ *
+ * @author unknown
+ */
class BinarySearch
{
+ /**
+ * This method implements the 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 up The upper bound
+ * @return the location of the key
+ **/
public static int BS(int array[], int key, int lb, int ub)
- {
- if (lb>ub)
+ { if (lb>ub)
{
return -1;
}
@@ -25,6 +38,14 @@ else if (key>array[mid])
}
}
+
+ /**
+ * This is the main method of Binary Search
+ *
+ * @author Unknown
+ * @param args Command line parameters
+ */
+
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
@@ -50,4 +71,4 @@ public static void main(String[] args)
System.out.println("Not found");
}
}
-}
\ No newline at end of file
+}
From 9411d5be56f444e750e19a052cff25f8e22365e0 Mon Sep 17 00:00:00 2001
From: zacharyjones123
Date: Tue, 18 Apr 2017 07:57:17 -0700
Subject: [PATCH 0028/2305] In this commit I have:
Added JavaDoc to every package except for "heaps"
---
.classpath | 7 +
.gitignore | 1 +
.project | 17 ++
BinarySearch.java | 74 ++++++
BinaryToDecimal.java | 32 +++
BubbleSort.java | 50 ++++
DecimalToBinary.java | 31 +++
DecimalToOctal.java | 31 +++
Factorial.java | 19 +-
FindingPrimes.java | 21 +-
HeapSort.java | 359 +++++++++++++-------------
InsertionSort.java | 49 ++++
InsertionSortInteger.java | 55 ++++
LinearSearch.java | 19 +-
MergeSort.java | 216 ++++++++--------
Quicksort.java | 33 ++-
ReverseString.java | 47 ++++
SelectionSort.java | 52 ++++
bfs.java | 22 +-
countwords.java | 13 +
data_structures/BinaryTree.java | 124 +++++++--
data_structures/DoublyLinkedList.java | 115 +++++++--
data_structures/PriorityQueues.java | 75 +++++-
data_structures/Queues.java | 82 +++++-
data_structures/SinglyLinkedList.java | 118 ++++++---
data_structures/Stacks.java | 135 ++++++++--
data_structures/heaps/MaxHeap.java | 8 +-
data_structures/heaps/MinHeap.java | 8 +-
dfs.java | 22 +-
29 files changed, 1408 insertions(+), 427 deletions(-)
create mode 100644 .classpath
create mode 100644 .gitignore
create mode 100644 .project
create mode 100644 BinarySearch.java
create mode 100644 BinaryToDecimal.java
create mode 100644 BubbleSort.java
create mode 100644 DecimalToBinary.java
create mode 100644 DecimalToOctal.java
create mode 100644 InsertionSort.java
create mode 100644 InsertionSortInteger.java
create mode 100644 ReverseString.java
create mode 100644 SelectionSort.java
diff --git a/.classpath b/.classpath
new file mode 100644
index 000000000000..67d5f6d35842
--- /dev/null
+++ b/.classpath
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000000..ae3c1726048c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/bin/
diff --git a/.project b/.project
new file mode 100644
index 000000000000..ea54703d8788
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+
+
+ Java
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/BinarySearch.java b/BinarySearch.java
new file mode 100644
index 000000000000..25814197fd23
--- /dev/null
+++ b/BinarySearch.java
@@ -0,0 +1,74 @@
+import java.util.Scanner;
+
+/**
+ * Implements a Binary Search in Java
+ *
+ * @author unknown
+ */
+class BinarySearch
+{
+ /**
+ * This method implements the 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 up The upper bound
+ * @return the location of the key
+ **/
+ public static int BS(int array[], int key, int lb, int ub)
+ { if (lb>ub)
+ {
+ return -1;
+ }
+
+ int mid=(lb+ub)/2;
+
+ if (keyarray[mid])
+ {
+ return (BS(array, key, mid+1, ub));
+ }
+ else
+ {
+ return mid;
+ }
+ }
+
+
+ /**
+ * This is the main method of Binary Search
+ *
+ * @author Unknown
+ * @param args Command line parameters
+ */
+
+ public static void main(String[] args)
+ {
+ Scanner input=new Scanner(System.in);
+ int array[]=new int[10] ;
+ int key;
+
+ //Input
+ System.out.println("Enter an array of 10 numbers : ");
+ for (int i=0; i<10 ;i++ )
+ {
+ array[i]=input.nextInt();
+ }
+ System.out.println("Enter the number to be searched : ");
+ key=input.nextInt();
+
+ int index=BS(array, key, 0, 9);
+ if (index!=-1)
+ {
+ System.out.println("Number found at index number : " + index);
+ }
+ else
+ {
+ System.out.println("Not found");
+ }
+ }
+}
diff --git a/BinaryToDecimal.java b/BinaryToDecimal.java
new file mode 100644
index 000000000000..f7357d3ce5d4
--- /dev/null
+++ b/BinaryToDecimal.java
@@ -0,0 +1,32 @@
+import java.util.Scanner;
+
+/**
+ * This class converts a Binary number to a Decimal number
+ *
+ * @author Unknown
+ *
+ */
+class BinaryToDecimal
+{
+
+ /**
+ * Main Method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[])
+ {
+ Scanner sc=new Scanner(System.in);
+ int n,k,d,s=0,c=0;
+ n=sc.nextInt();
+ k=n;
+ while(k!=0)
+ {
+ d=k%10;
+ s+=d*(int)Math.pow(2,c++);
+ k/=10;
+ }
+ System.out.println("Binary number:"+n);
+ System.out.println("Decimal equivalent:"+s);
+ }
+}
diff --git a/BubbleSort.java b/BubbleSort.java
new file mode 100644
index 000000000000..ac4015f18f3e
--- /dev/null
+++ b/BubbleSort.java
@@ -0,0 +1,50 @@
+import java.util.Scanner;
+
+/**
+ * This class implements BubbleSort
+ *
+ * @author Unknown
+ *
+ */
+
+class BubbleSort
+{
+ /**
+ * Main Method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args)
+ {
+ int array[]=new int[6];
+ Scanner input=new Scanner(System.in);
+
+ //Input
+ System.out.println("Enter any 6 Numbers for Unsorted Array : ");
+ for(int i=0; i<6; i++)
+ {
+ array[i]=input.nextInt();
+ }
+
+ //Sorting
+ for(int i=0; i<5; i++)
+ {
+ for(int j=i+1; j<6; j++)
+ {
+ if(array[j]>array[i])
+ {
+ int temp=array[j];
+ array[j]=array[i];
+ array[i]=temp;
+ }
+ }
+ }
+
+ //Output
+ for(int i=0; i<6; i++)
+ {
+ System.out.print(array[i]+"\t");
+ }
+
+ }
+}
diff --git a/DecimalToBinary.java b/DecimalToBinary.java
new file mode 100644
index 000000000000..e88c7d97658f
--- /dev/null
+++ b/DecimalToBinary.java
@@ -0,0 +1,31 @@
+import java.util.Scanner;
+
+/**
+ * This class converts a Decimal number to a Binary number
+ *
+ * @author Unknown
+ *
+ */
+class DecimalToBinary
+{
+ /**
+ * Main Method
+ *
+ * @param args Command Line Arguments
+ */
+ public static void main(String args[])
+ {
+ Scanner sc=new Scanner(System.in);
+ int n,k,s=0,c=0,d;
+ n=sc.nextInt();
+ k=n;
+ while(k!=0)
+ {
+ d=k%2;
+ s=s+d*(int)Math.pow(10,c++);
+ k/=2;
+ }//converting decimal to binary
+ System.out.println("Decimal number:"+n);
+ System.out.println("Binary equivalent:"+s);
+ }
+}
diff --git a/DecimalToOctal.java b/DecimalToOctal.java
new file mode 100644
index 000000000000..f0590316041c
--- /dev/null
+++ b/DecimalToOctal.java
@@ -0,0 +1,31 @@
+import java.util.Scanner;
+
+/**
+ * This class converts Decimal numbers to Octal Numbers
+ *
+ * @author Unknown
+ *
+ */
+class Decimal_Octal
+{
+ /**
+ * Main Method
+ *
+ * @param args Command line Arguments
+ */
+ public static void main(String[] args)
+ {
+ Scanner sc=new Scanner(System.in);
+ int n,k,d,s=0,c=0;
+ n=sc.nextInt();
+ k=n;
+ while(k!=0)
+ {
+ d=k%8;
+ s+=d*(int)Math.pow(10,c++);
+ k/=8;
+ }
+ System.out.println("Decimal number:"+n);
+ System.out.println("Octal equivalent:"+s);
+ }
+}
diff --git a/Factorial.java b/Factorial.java
index f675ba6a1273..134ec2f5de5e 100644
--- a/Factorial.java
+++ b/Factorial.java
@@ -1,7 +1,19 @@
import java.util.Scanner;
+/**
+ * This program will print out the factorial of any non-negative
+ * number that you input into it.
+ *
+ * @author Unknown
+ *
+ */
public class Factorial{
+ /**
+ * The main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Prompt user to enter integer
@@ -20,7 +32,12 @@ public static void main(String[] args){
}
}
- //Factorial method
+ /**
+ * Recursive Factorial Method
+ *
+ * @param n The number to factorial
+ * @return The factorial of the number
+ */
public static long factorial(int n){
if (n==0){
diff --git a/FindingPrimes.java b/FindingPrimes.java
index ecf3f7b4b82f..f7cc14d722ed 100644
--- a/FindingPrimes.java
+++ b/FindingPrimes.java
@@ -1,12 +1,27 @@
-/*
- * The Sieve of Eratosthenes is an algorithm used to find prime numbers, up to a given value.
+/**
+ * The Sieve of Eratosthenes is an algorithm use to find prime numbers,
+ * up to a given value.
* Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
-*/
+ * (This illustration is also in the github repository)
+ *
+ * @author Unknown
+ *
+ */
public class FindingPrimes{
+ /**
+ * The Main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[]){
SOE(20); //Example: Finds all the primes up to 20
}
+ /**
+ * The method implementing the Sieve of Eratosthenes
+ *
+ * @param n Number to perform SOE on
+ */
public static void SOE(int n){
boolean sieve[] = new boolean[n];
diff --git a/HeapSort.java b/HeapSort.java
index 7dd420a1077f..6b3a3fdcc490 100644
--- a/HeapSort.java
+++ b/HeapSort.java
@@ -1,185 +1,174 @@
-import java.util.Scanner;
-
-/**
- * Heap Sort Algorithm. Implements MinHeap
- *
- */
-public class HeapSort {
- /**
- * array to store heap.
- */
- private int[] heap;
- /**
- * size of heap.
- */
- private int size;
-
- /**
- * Constructor.
- *
- * @param heap
- * array of unordered integers
- */
- public HeapSort(int[] heap) {
- this.setHeap(heap);
- this.setSize(heap.length);
- }
-
- /**
- * Sets this.size with {@code length).
- *
- * @param length
- * integer length of heap
- */
- private void setSize(int length) {
- this.size = length;
- }
-
- /**
- * Sets Heap with {@code heap}.
- *
- * @param heap
- * array of unordered elements
- */
- private void setHeap(int[] heap) {
- this.heap = heap;
- }
-
- /**
- * Swaps index of {@code first} with {@code second}.
- *
- * @param first
- * index to swap {@code second} with
- * @param second
- * index to swap {@code first} with
- */
- private void swap(int first, int second) {
- int temp = this.heap[first];
- this.heap[first] = this.heap[second];
- this.heap[second] = temp;
- }
-
- /**
- * Heapifies subtree from {@code top} as root to {@code last} as last child.
- *
- * @param rootIndex
- * index of root
- * @param lastChild
- * index of last child
- */
- private void heapSubtree(int rootIndex, int lastChild) {
- int leftIndex = rootIndex * 2 + 1;
- int rightIndex = rootIndex * 2 + 2;
- int root = this.heap[rootIndex];
- if (rightIndex <= lastChild) { // if has right and left children
- int left = this.heap[leftIndex];
- int right = this.heap[rightIndex];
- if (left < right && left < root) {
- this.swap(leftIndex, rootIndex);
- this.heapSubtree(leftIndex, lastChild);
- } else if (right < root) {
- this.swap(rightIndex, rootIndex);
- this.heapSubtree(rightIndex, lastChild);
- }
- } else if (leftIndex <= lastChild) { // if no right child, but has left child
- int left = this.heap[leftIndex];
- if (left < root) {
- this.swap(leftIndex, rootIndex);
- this.heapSubtree(leftIndex, lastChild);
- }
- }
- }
-
- /**
- * Makes heap with {@code root} as root.
- *
- * @param root
- * index of root of heap
- */
- private void makeMinHeap(int root) {
- int leftIndex = root * 2 + 1;
- int rightIndex = root * 2 + 2;
- boolean hasLeftChild = leftIndex < this.heap.length;
- boolean hasRightChild = rightIndex < this.heap.length;
- if (hasRightChild) { //if has left and right
- this.makeMinHeap(leftIndex);
- this.makeMinHeap(rightIndex);
- this.heapSubtree(root, this.heap.length - 1);
- } else if (hasLeftChild) {
- this.heapSubtree(root, this.heap.length - 1);
- }
- }
-
- /**
- * Gets the root of this.heap.
- *
- * @return root of this.heap
- */
- private int getRoot() {
- this.swap(0, this.size - 1);
- this.size--;
- this.heapSubtree(0, this.size - 1);
- return this.heap[this.size]; // return old root
- }
-
- /**
- * Sorts this.heap with heap sort; displays ordered elements to console.
- *
- * @return {@code sorted} array of sorted elements
- */
- public final int[] sort() {
- this.makeMinHeap(0); // make min heap using index 0 as root.
- int[] sorted = new int[this.size];
- int index = 0;
- while (this.size > 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);
- }
-
-}
+import java.util.Scanner;
+
+/**
+ * Heap Sort Algorithm
+ * Implements MinHeap
+ *
+ * @author Unknown
+ *
+ */
+public class HeapSort {
+ /** Array to store heap */
+ private int[] heap;
+ /** The size of the heap */
+ private int size;
+
+ /**
+ * Constructor
+ *
+ * @param heap array of unordered integers
+ */
+ public HeapSort(int[] heap) {
+ this.setHeap(heap);
+ this.setSize(heap.length);
+ }
+
+ /**
+ * Setter for variable size
+ *
+ * @param length new size
+ */
+ private void setSize(int length) {
+ this.size = length;
+ }
+
+ /**
+ * Setter for variable heap
+ *
+ * @param heap array of unordered elements
+ */
+ private void setHeap(int[] heap) {
+ this.heap = heap;
+ }
+
+ /**
+ * Swaps index of first with second
+ *
+ * @param first First index to switch
+ * @param second Second index to switch
+ */
+ private void swap(int first, int second) {
+ int temp = this.heap[first];
+ this.heap[first] = this.heap[second];
+ this.heap[second] = temp;
+ }
+
+ /**
+ * Heapifies subtree from top as root to last as last child
+ *
+ * @param rootIndex index of root
+ * @param lastChild index of last child
+ */
+ private void heapSubtree(int rootIndex, int lastChild) {
+ int leftIndex = rootIndex * 2 + 1;
+ int rightIndex = rootIndex * 2 + 2;
+ int root = this.heap[rootIndex];
+ if (rightIndex <= lastChild) { // if has right and left children
+ int left = this.heap[leftIndex];
+ int right = this.heap[rightIndex];
+ if (left < right && left < root) {
+ this.swap(leftIndex, rootIndex);
+ this.heapSubtree(leftIndex, lastChild);
+ } else if (right < root) {
+ this.swap(rightIndex, rootIndex);
+ this.heapSubtree(rightIndex, lastChild);
+ }
+ } else if (leftIndex <= lastChild) { // if no right child, but has left child
+ int left = this.heap[leftIndex];
+ if (left < root) {
+ this.swap(leftIndex, rootIndex);
+ this.heapSubtree(leftIndex, lastChild);
+ }
+ }
+ }
+
+ /**
+ * Makes heap with root as root
+ *
+ * @param root index of root of heap
+ */
+ private void makeMinHeap(int root) {
+ int leftIndex = root * 2 + 1;
+ int rightIndex = root * 2 + 2;
+ boolean hasLeftChild = leftIndex < this.heap.length;
+ boolean hasRightChild = rightIndex < this.heap.length;
+ if (hasRightChild) { //if has left and right
+ this.makeMinHeap(leftIndex);
+ this.makeMinHeap(rightIndex);
+ this.heapSubtree(root, this.heap.length - 1);
+ } else if (hasLeftChild) {
+ this.heapSubtree(root, this.heap.length - 1);
+ }
+ }
+
+ /**
+ * Gets the root of heap
+ *
+ * @return root of heap
+ */
+ private int getRoot() {
+ this.swap(0, this.size - 1);
+ this.size--;
+ this.heapSubtree(0, this.size - 1);
+ return this.heap[this.size]; // return old root
+ }
+
+ /**
+ * Sorts heap with heap sort; displays ordered elements to console.
+ *
+ * @return sorted array of sorted elements
+ */
+ public final int[] sort() {
+ this.makeMinHeap(0); // make min heap using index 0 as root.
+ int[] sorted = new int[this.size];
+ int index = 0;
+ while (this.size > 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/InsertionSort.java b/InsertionSort.java
new file mode 100644
index 000000000000..772b5a77e2d8
--- /dev/null
+++ b/InsertionSort.java
@@ -0,0 +1,49 @@
+import java.util.Scanner;
+
+/**
+ * This class implements Insertion Sort
+ *
+ * @author Unknown
+ *
+ */
+class InsertionSort
+{
+ /**
+ * Main Method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args)
+ {
+ int array[]=new int[6];
+ Scanner input=new Scanner(System.in);
+
+ //Input
+ System.out.println("Enter any 6 Numbers for Unsorted Array : ");
+ for(int i=0; i<6; i++)
+ {
+ array[i]=input.nextInt();
+ }
+
+ //Sorting
+ for(int i=0; i<6; i++)
+ {
+ int temp=array[i];
+ int j=i-1;
+ while(j>=0 && temp 0; lastSortedIndex--){
+
+ //If our extracted element is smaller than element to the right, switch them.
+ if (sortedArray[lastSortedIndex-1] > extractedElement){
+ //move the element to the left of extractedElement to the right in sortedArray
+ sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
+ //And move the current extractedElement to the left one (since it's smaller).
+ sortedArray[lastSortedIndex-1] = extractedElement;
+ }
+ else{
+ //insert element where it is.
+ sortedArray[lastSortedIndex] = extractedElement;
+ //Terminating loop since element is in the right spot.
+ break;
+ }
+
+ }
+
+ }
+
+ return sortedArray;
+
+ }
+
+}
diff --git a/LinearSearch.java b/LinearSearch.java
index 820785938bbb..f74f4ad096e6 100644
--- a/LinearSearch.java
+++ b/LinearSearch.java
@@ -1,7 +1,10 @@
import java.util.Scanner;
public class LinearSearch{
- //Main method
+ /**
+ * The main method
+ * @param args Command line arguments
+ */
public static void main(String[] args){
Scanner input = new Scanner(System.in);
@@ -27,7 +30,13 @@ public static void main(String[] args){
}
- //Linear search method
+ /**
+ * Linear search method
+ *
+ * @param list List to be searched
+ * @param key Key being searched for
+ * @return Location of the key
+ */
public static int linearsearch(int[] list, int key){
for (int i = 0; i< list.length; i++){
@@ -37,7 +46,11 @@ public static int linearsearch(int[] list, int key){
} return -1;
}
- //Helper method
+ /**
+ * Helper Method
+ *
+ * @param a array to be printed
+ */
public static void printarray(int[] a){
System.out.print("The array is: ");
for( int d: a){
diff --git a/MergeSort.java b/MergeSort.java
index 08479ff75a9b..f574281d65c0 100644
--- a/MergeSort.java
+++ b/MergeSort.java
@@ -1,107 +1,109 @@
-import java.util.Scanner;
-
-/**
- * Merge Sort
- *
- */
-public class MergeSort {
- private int[] array;
- private int[] tempMergArr;
- private int length;
-
- /**
- * Sorts {@code inputArr} with merge sort algorithm.
- *
- * @param inputArr
- */
- public final void sort(int inputArr[]) {
- this.array = inputArr;
- this.length = inputArr.length;
- this.tempMergArr = new int[this.length];
- this.mergeSort(0, this.length - 1);
- }
-
- /**
- * Partitions Array into recursively smaller pieces.
- *
- * @param lowerIndex
- * lower bound to include in the first partition
- * @param higherIndex
- * upper bound to include in the third partition
- */
- private void mergeSort(int lowerIndex, int higherIndex) {
- if (lowerIndex < higherIndex) {
- int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
- // Below step sorts the left side of the array
- this.mergeSort(lowerIndex, middle);
- // Below step sorts the right side of the array
- this.mergeSort(middle + 1, higherIndex);
- // Now merge both sides
- this.mergeParts(lowerIndex, middle, higherIndex);
- }
- }
-
- /**
- * Merges partitions.
- *
- * @param lowerIndex
- * @param middle
- * @param higherIndex
- */
- private void mergeParts(int lowerIndex, int middle, int higherIndex) {
- for (int i = lowerIndex; i <= higherIndex; i++) {
- this.tempMergArr[i] = this.array[i];
- }
- int i = lowerIndex;
- int j = middle + 1;
- int k = lowerIndex;
- while (i <= middle && j <= higherIndex) {
- if (this.tempMergArr[i] <= this.tempMergArr[j]) {
- this.array[k] = this.tempMergArr[i];
- i++;
- } else {
- this.array[k] = this.tempMergArr[j];
- j++;
- }
- k++;
- }
- while (i <= middle) {
- this.array[k] = this.tempMergArr[i];
- k++;
- i++;
- }
-
- }
-
- /**
- * 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;
- }
-
- /**
- * Main Method.
- *
- * @param args
- */
- public static void main(String args[]) {
- int[] inputArr = getInput();
- MergeSort mergeSort = new MergeSort();
- mergeSort.sort(inputArr);
- for (int i : inputArr) {
- System.out.print(i);
- System.out.print(" ");
- }
- }
-}
+import java.util.Scanner;
+
+/**
+ * This class implements MergeSort
+ * @author Unknown
+ *
+ */
+public class MergeSort {
+ /** Array for mergeSort*/
+ private int[] array;
+ /** Temp Merge Array*/
+ private int[] tempMergArr;
+ /** Length of the array*/
+ private int length;
+
+ /**
+ * Sorts inputArr with merge sort algorithm
+ *
+ * @param inputArr Array to be sorted
+ */
+ public final void sort(int inputArr[]) {
+ this.array = inputArr;
+ this.length = inputArr.length;
+ this.tempMergArr = new int[this.length];
+ this.mergeSort(0, this.length - 1);
+ }
+
+ /**
+ * Partitions Array into recursively smaller pieces
+ *
+ * @param lowerIndex lower bound to include in the first partition
+ * @param higherIndex upper bound to include in the third partition
+ */
+ private void mergeSort(int lowerIndex, int higherIndex) {
+ if (lowerIndex < higherIndex) {
+ int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
+ // Below step sorts the left side of the array
+ this.mergeSort(lowerIndex, middle);
+ // Below step sorts the right side of the array
+ this.mergeSort(middle + 1, higherIndex);
+ // Now merge both sides
+ this.mergeParts(lowerIndex, middle, higherIndex);
+ }
+ }
+
+ /**
+ * Merges partitions
+ *
+ * @param lowerIndex The lower index
+ * @param middle The middle index
+ * @param higherIndex The higher index
+ */
+ private void mergeParts(int lowerIndex, int middle, int higherIndex) {
+ for (int i = lowerIndex; i <= higherIndex; i++) {
+ this.tempMergArr[i] = this.array[i];
+ }
+ int i = lowerIndex;
+ int j = middle + 1;
+ int k = lowerIndex;
+ while (i <= middle && j <= higherIndex) {
+ if (this.tempMergArr[i] <= this.tempMergArr[j]) {
+ this.array[k] = this.tempMergArr[i];
+ i++;
+ } else {
+ this.array[k] = this.tempMergArr[j];
+ j++;
+ }
+ k++;
+ }
+ while (i <= middle) {
+ this.array[k] = this.tempMergArr[i];
+ k++;
+ i++;
+ }
+
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * Main Method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ int[] inputArr = getInput();
+ MergeSort mergeSort = new MergeSort();
+ mergeSort.sort(inputArr);
+ for (int i : inputArr) {
+ System.out.print(i);
+ System.out.print(" ");
+ }
+ }
+}
diff --git a/Quicksort.java b/Quicksort.java
index f693c42b6753..5b5896f8a12e 100644
--- a/Quicksort.java
+++ b/Quicksort.java
@@ -1,7 +1,19 @@
import java.util.Scanner;
+/**
+ * Implementation of QuickSort
+ *
+ * @author Unknown
+ *
+ */
+
public class Quicksort{
+ /**
+ * The main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] array;
@@ -28,7 +40,13 @@ public static void main(String[] args){
System.out.println();
}
- //Quicksort Method
+ /**
+ * QuickSort method
+ *
+ * @param ar Array to perform QuickSort
+ * @param start Start of the array
+ * @param end End of the array
+ */
public static void quicksort(int[] ar, int start, int end){
int[] array;
@@ -54,7 +72,13 @@ public static void quicksort(int[] ar, int start, int end){
}
}
- //Helper methods
+ /**
+ * Helper Method 1 - Swaps elements of an array
+ *
+ * @param ar Array to be used
+ * @param index1 Index 1 to be switched with Index 2
+ * @param index2 Index 2 to be switched with Index 1
+ */
public static void swap(int[] ar, int index1, int index2){
int temp = ar[index1];
@@ -62,6 +86,11 @@ public static void swap(int[] ar, int index1, int index2){
ar[index2] = temp;
}
+ /**
+ * Helper Method 2 - Prints the elements of an array
+ *
+ * @param array Array to be printed
+ */
public static void printarray(int[] array){
for (int data : array){
diff --git a/ReverseString.java b/ReverseString.java
new file mode 100644
index 000000000000..e8a75b3ed99e
--- /dev/null
+++ b/ReverseString.java
@@ -0,0 +1,47 @@
+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
+ */
+ static String reverseString(String str)
+ {
+ String reverse=" ";
+ if(str.length()==1)
+ {
+ return str;
+ }
+ else
+ {
+ reverse=reverse+str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1));
+ return reverse;
+ }
+ }
+
+ /**
+ * 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="+reverseString(srr));
+ }
+}
+
\ No newline at end of file
diff --git a/SelectionSort.java b/SelectionSort.java
new file mode 100644
index 000000000000..d8e1e0032df0
--- /dev/null
+++ b/SelectionSort.java
@@ -0,0 +1,52 @@
+import java.util.Scanner;
+
+/**
+ * This class implements Selection Sort
+ *
+ * @author Unknown
+ *
+ */
+
+class SelectionSort
+{
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String[] args)
+ {
+ int array[]=new int[6];
+ Scanner input=new Scanner(System.in);
+
+ //Input
+ System.out.println("Enter any 6 Numbers for Unsorted Array : ");
+ for(int i=0; i<6; i++)
+ {
+ array[i]=input.nextInt();
+ }
+
+ //Sorting
+ for(int i=0; i<6; i++)
+ {
+ int min=i;
+ for(int j=i+1; j<6; j++)
+ {
+ if(array[j] st=new LinkedList<>(); //operational stack
+ Queue st=new Queue<>(); //operational stack
st.add(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
@@ -26,6 +39,11 @@ public static void bfs(byte [][] a,int vertices,int source){ //passing adjacenc
}
+ /**
+ * The main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
diff --git a/countwords.java b/countwords.java
index a1d4d72dbbf4..2eebe786847b 100644
--- a/countwords.java
+++ b/countwords.java
@@ -1,6 +1,19 @@
import java.util.Scanner;
+
+/**
+ * You enter a string into this program, and it will return how
+ * many words were in that particular string
+ *
+ * @author Unknown
+ *
+ */
class CountTheWords
{
+ /**
+ * The main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[])
{
System.out.println("Enter the string");
diff --git a/data_structures/BinaryTree.java b/data_structures/BinaryTree.java
index 90a6d98023a1..b26525cfc730 100644
--- a/data_structures/BinaryTree.java
+++ b/data_structures/BinaryTree.java
@@ -1,11 +1,35 @@
-//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
+/**
+ * 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;
@@ -14,13 +38,33 @@ public Node(int value){
}
}
+
+/**
+ * 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;
}
- //Returns the node if it finds it, otherwise returns the parent
+
+ /**
+ * 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;
Node last = root;
@@ -37,7 +81,11 @@ else if(key > current.data)
return last;
}
- //Inserts the given value
+ /**
+ * 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)
@@ -60,7 +108,12 @@ public void put(int value){
}
}
- //Deletes the given value
+ /**
+ * 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);
@@ -84,34 +137,34 @@ else if(temp.parent.data < temp.data)
//Two children
else if(temp.left != null && temp.right != null){
- Node succesor = findSuccesor(temp);
+ Node successor = findSuccessor(temp);
//The left tree of temp is made the left tree of the successor
- succesor.left = temp.left;
- succesor.left.parent = succesor;
+ 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(succesor.right != null && succesor.parent != temp){
- succesor.right.parent = succesor.parent;
- succesor.parent.left = succesor.right;
- succesor.right = temp.right;
- succesor.right.parent = succesor;
+ 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){
- succesor.parent = null;
- root = succesor;
+ successor.parent = null;
+ root = successor;
return true;
}
//If you're not deleting the root
else{
- succesor.parent = temp.parent;
+ 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 = succesor;
+ temp.parent.right = successor;
else
- temp.parent.left = succesor;
+ temp.parent.left = successor;
return true;
}
}
@@ -148,8 +201,14 @@ else if(temp.left != null && temp.right != null){
}
}
- //Move right once and go left down the tree as far as you can
- public Node findSuccesor(Node n){
+ /**
+ * 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;
@@ -161,11 +220,20 @@ public Node findSuccesor(Node n){
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
+ /**
+ * Prints leftChild - root - rightChild
+ *
+ * @param localRoot The local root of the binary tree
+ */
public void inOrder(Node localRoot){
if(localRoot != null){
inOrder(localRoot.left);
@@ -173,7 +241,12 @@ public void inOrder(Node localRoot){
inOrder(localRoot.right);
}
}
- //Prints root - leftChild - rightChild
+
+ /**
+ * 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 + " ");
@@ -181,7 +254,12 @@ public void preOrder(Node localRoot){
preOrder(localRoot.right);
}
}
- //Prints rightChild - leftChild - root
+
+ /**
+ * Prints rightChild - leftChild - root
+ *
+ * @param localRoot The local root of the binary tree
+ */
public void postOrder(Node localRoot){
if(localRoot != null){
postOrder(localRoot.left);
diff --git a/data_structures/DoublyLinkedList.java b/data_structures/DoublyLinkedList.java
index f8411994f7c7..c3229d9c336d 100644
--- a/data_structures/DoublyLinkedList.java
+++ b/data_structures/DoublyLinkedList.java
@@ -1,19 +1,38 @@
-/*
- * A linked list is similar to an array, it holds 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 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.
-*/
-class LinkedList{
- private Link head; //Head refers to the front of the list
- private Link tail; //Tail refers to the back of the list
-
- public LinkedList(){
+/**
+ * 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;
}
- public void insertHead(int x){ //Insert an element at the head
+ /**
+ * 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;
@@ -23,6 +42,11 @@ public void insertHead(int x){ //Insert an element at the 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 -->
@@ -31,7 +55,12 @@ public void insertTail(int x){
tail = newLink; // oldTail <--> newLink(tail) -->
}
- public Link deleteHead(){ //Delete the element at the head
+ /**
+ * 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
@@ -40,6 +69,11 @@ public Link deleteHead(){ //Delete the element at the head
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
@@ -47,6 +81,12 @@ public Link deleteTail(){
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;
@@ -66,6 +106,11 @@ else if(current == tail)
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;
@@ -86,10 +131,18 @@ else if(current == null)
}
}
- public boolean isEmpty(){ //Returns true if list is empty
+ /**
+ * 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){
@@ -100,24 +153,44 @@ public void display(){ //Prints contents of the list
}
}
+/**
+ * This class is used to implement the nodes of the
+ * linked list.
+ *
+ * @author Unknown
+ *
+ */
class Link{
+ /** Value of node */
public int value;
- public Link next; //This points to the link in front of the new link
- public Link previous; //This points to the link behind the new link
-
+ /** 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+" ");
}
-}
-//Example
-public class DoublyLinkedList{
+ /**
+ * Main Method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[]){
- LinkedList myList = new LinkedList();
+ DoublyLinkedList myList = new DoublyLinkedList();
myList.insertHead(13);
myList.insertHead(7);
diff --git a/data_structures/PriorityQueues.java b/data_structures/PriorityQueues.java
index a0c1af1a0da7..acb6b552537e 100644
--- a/data_structures/PriorityQueues.java
+++ b/data_structures/PriorityQueues.java
@@ -1,21 +1,40 @@
-/*
+/**
+ * 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.
+ * 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;
- public PriorityQueue(int size){ //Constructor
+ /**
+ * Constructor
+ *
+ * @param size Size of the queue
+ */
+ public PriorityQueue(int size){
maxSize = size;
queueArray = new int[size];
nItems = 0;
}
- public void insert(int value){ //Inserts an element in it's appropriate place
+ /**
+ * 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;
}
@@ -30,28 +49,64 @@ public void insert(int value){ //Inserts an element in it's appropriate place
nItems++;
}
- public int remove(){ //Remove the element from the front of the queue
+ /**
+ * Remove the element from the front of the queue
+ *
+ * @return The element removed
+ */
+ public int remove(){
return queueArray[--nItems];
}
- public int peek(){ //Checks what's at the front of the queue
+ /**
+ * Checks what's at the front of the queue
+ *
+ * @return element at the front of the queue
+ */
+ public int peek(){
return queueArray[nItems-1];
}
- public boolean isEmpty(){ //Returns true is the queue is empty
+ /**
+ * Returns true if the queue is empty
+ *
+ * @return true if the queue is empty
+ */
+ public boolean isEmpty(){
return(nItems == 0);
}
- public boolean isFull(){ //Returns true is the queue is full
+ /**
+ * Returns true if the queue is full
+ *
+ * @return true if the queue is full
+ */
+ public boolean isFull(){
return(nItems == maxSize);
}
- public int getSize(){ //Returns the number of elements in the queue
+ /**
+ * Returns the number of elements in the queue
+ *
+ * @return number of elements in the queue
+ */
+ public int getSize(){
return nItems;
}
}
-//Example
+
+/**
+ * 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);
diff --git a/data_structures/Queues.java b/data_structures/Queues.java
index c7725417954d..84638cb24751 100644
--- a/data_structures/Queues.java
+++ b/data_structures/Queues.java
@@ -1,16 +1,31 @@
-/*
+/**
+ * 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.
+ * 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;
- public Queue(int size){ //Constructor
+ /**
+ * Constructor
+ *
+ * @param size Size of the new queue
+ */
+ public Queue(int size){
maxSize = size;
queueArray = new int[size];
front = 0;
@@ -18,7 +33,13 @@ public Queue(int size){ //Constructor
nItems = 0;
}
- public boolean insert(int x){ //Inserts an element at the rear of the queue
+ /**
+ * 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
@@ -29,6 +50,11 @@ public boolean insert(int x){ //Inserts an element at the rear of the queue
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");
@@ -42,28 +68,64 @@ public int remove(){ //Remove an element from the front of the queue
return temp;
}
- public int peekFront(){ //Checks what's at the front of the queue
+ /**
+ * Checks what's at the front of the queue
+ *
+ * @return element at the front of the queue
+ */
+ public int peekFront(){
return queueArray[front];
}
- public int peekRear(){ //Checks what's at the rear of the queue
+ /**
+ * Checks what's at the rear of the queue
+ *
+ * @return element at the rear of the queue
+ */
+ public int peekRear(){
return queueArray[rear];
}
- public boolean isEmpty(){ //Returns true is the queue is empty
+ /**
+ * Returns true if the queue is empty
+ *
+ * @return true if the queue is empty
+ */
+ public boolean isEmpty(){
return(nItems == 0);
}
- public boolean isFull(){ //Returns true is the queue is full
+ /**
+ * Returns true if the queue is full
+ *
+ * @return true if the queue is full
+ */
+ public boolean isFull(){
return(nItems == maxSize);
}
- public int getSize(){ //Returns the number of elements in the queue
+ /**
+ * Returns the number of elements in the queue
+ *
+ * @return number of elements in the queue
+ */
+ public int getSize(){
return nItems;
}
}
-//Example
+
+/**
+ * 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);
diff --git a/data_structures/SinglyLinkedList.java b/data_structures/SinglyLinkedList.java
index 75660c7316fb..4523739b3a98 100644
--- a/data_structures/SinglyLinkedList.java
+++ b/data_structures/SinglyLinkedList.java
@@ -1,58 +1,78 @@
-/*
- * A linked list is similar to an array, it holds 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 grows and shrinks as it is edited.
- * This is an example of a singly linked list. Elements can only be added/removed at the head/front of the list.
-*/
-class LinkedList{
- private Link head; //Head refers to the front of the list
+/**
+ * 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 LinkForLinkedList head;
- public LinkedList(){
+ /**
+ * Constructor of SinglyLinkedList
+ */
+ public SinglyLinkedList(){
head = null;
}
- public void insertHead(int x){ //Insert an element at the head
- Link newLink = new Link(x); //Create a new link with a value attached to it
+ /**
+ * This method inserts an element at the head
+ *
+ * @param x Element to be added
+ */
+ public void insertHead(int x){
+ LinkForLinkedList newLink = new LinkForLinkedList(x); //Create a new link with a value attached to it
newLink.next = head; //Set the new link to point to the current head
head = newLink; //Now set the new link to be the head
}
- public Link deleteHead(){ //Delete the element at the head
- Link temp = head;
+ /**
+ * This method deletes an element at the head
+ *
+ * @return The element deleted
+ */
+ public LinkForLinkedList deleteHead(){
+ LinkForLinkedList 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;
}
- public boolean isEmpty(){ //Returns true if list is empty
+ /**
+ * Checks if the list is empty
+ *
+ * @return true is list is empty
+ */
+ public boolean isEmpty(){
return(head == null);
}
- public void display(){ //Prints contents of the list
- Link current = head;
+ /**
+ * Prints contents of the list
+ */
+ public void display(){
+ LinkForLinkedList current = head;
while(current!=null){
current.displayLink();
current = current.next;
}
System.out.println();
}
-}
-
-class Link{
- public int value;
- public Link next; //This is what the link will point to
-
- public Link(int valuein){
- value = valuein;
- }
-
- public void displayLink(){
- System.out.print(value+" ");
- }
-}
-
-//Example
-public class SinglyLinkedList{
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[]){
- LinkedList myList = new LinkedList();
+ SinglyLinkedList myList = new SinglyLinkedList();
System.out.println(myList.isEmpty()); //Will print true
@@ -66,4 +86,36 @@ public static void main(String args[]){
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 LinkForLinkedList{
+ /** The value of the node */
+ public int value;
+ /** Point to the next node */
+ public LinkForLinkedList next; //This is what the link will point to
+
+ /**
+ * Constructor
+ *
+ * @param valuein Value to be put in the node
+ */
+ public LinkForLinkedList(int valuein){
+ value = valuein;
+ }
+
+ /**
+ * Prints out the value of the node
+ */
+ public void displayLink(){
+ System.out.print(value+" ");
+ }
+
}
\ No newline at end of file
diff --git a/data_structures/Stacks.java b/data_structures/Stacks.java
index 18139147fed6..dbb2a6217bcf 100644
--- a/data_structures/Stacks.java
+++ b/data_structures/Stacks.java
@@ -1,62 +1,131 @@
-/*
- *A stack is exactly what it sounds like. An element gets added to 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 stacks have no fixed size, but with an array implementation it does.
-*/
+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;
- public Stack(int size){ //Constructor
+ /**
+ * Constructor
+ *
+ * @param size Size of the Stack
+ */
+ public Stack(int size){
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
- public void push(int value){ //Adds an element to the top of the stack
+ /**
+ * Adds an element to the top of the stack
+ *
+ * @param value The element added
+ */
+ public void push(int value){
top++;
stackArray[top] = value;
}
- public int pop(){ //Removes the top element of the stack and returns the value you've removed
+ /**
+ * Removes the top element of the stack and returns the value you've removed
+ *
+ * @return value popped off the Stack
+ */
+ public int pop(){
return stackArray[top--];
}
- public int peek(){ //Returns the element at the top of the stack
+ /**
+ * Returns the element at the top of the stack
+ *
+ * @return element at the top of the stack
+ */
+ public int peek(){
return stackArray[top];
}
- public boolean isEmpty(){ //Returns true if the stack is empty
+ /**
+ * Returns true if the stack is empty
+ *
+ * @return true if the stack is empty
+ */
+ public boolean isEmpty(){
return(top == -1);
}
- public boolean isFull(){ //Returns true if the stack is full
+ /**
+ * 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 ArrayList Implementation of stack , Where size is not
- a problem we can extend the stack as much as we want*/
+/**
+ * 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;
- Stack2(){ //constructor
+ /**
+ * Constructor
+ */
+ Stack2(){
stackList=new ArrayList<>();
}
-
- void push(int value){ //adds value to the end of list which is the top for stack
+ /**
+ * 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);
}
- int pop(){ //pops last element of list which is indeed the top for Stack
+ /**
+ * Pops last element of list which is indeed
+ * the top for Stack
+ *
+ * @return Element popped
+ */
+ int pop(){
if(!isEmpty()){ // checks for an empty Stack
@@ -71,7 +140,12 @@ int pop(){ //pops last element of list which is indeed the top for Stack
}
- boolean isEmpty(){ //checks for empty Stack
+ /**
+ * Checks for empty Stack
+ *
+ * @return true if stack is empty
+ */
+ boolean isEmpty(){
if(stackList.isEmpty())
return true;
@@ -79,13 +153,28 @@ boolean isEmpty(){ //checks for empty Stack
}
- int peek(){ //top element of stack
+ /**
+ * Top element of stack
+ *
+ * @return top element of stack
+ */
+ int peek(){
return stackList.get(stackList.size()-1);
}
}
-//Example
+/**
+ * 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
diff --git a/data_structures/heaps/MaxHeap.java b/data_structures/heaps/MaxHeap.java
index 6768d4871e8a..16ba7cff8852 100644
--- a/data_structures/heaps/MaxHeap.java
+++ b/data_structures/heaps/MaxHeap.java
@@ -84,7 +84,13 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
- if (isempty(maxHeap)) throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ if (maxHeap.isEmpty())
+ try {
+ throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ } catch (EmptyHeapException e) {
+ // TODO Auto-generated catch block
+ 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()));
diff --git a/data_structures/heaps/MinHeap.java b/data_structures/heaps/MinHeap.java
index cd484d79fe55..5793bb92f215 100644
--- a/data_structures/heaps/MinHeap.java
+++ b/data_structures/heaps/MinHeap.java
@@ -87,7 +87,13 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
- if (isempty(maxHeap)) throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ if (minHeap.isEmpty())
+ try {
+ throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ } catch (EmptyHeapException e) {
+ // TODO Auto-generated catch block
+ 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()));
diff --git a/dfs.java b/dfs.java
index 52e642725187..023e1d5ffc59 100644
--- a/dfs.java
+++ b/dfs.java
@@ -1,8 +1,21 @@
import java.util.*;
-public class App{
-
+/**
+ * Implementation of a Depth First Search
+ *
+ * @author Unknown
+ *
+ */
+
+public class dfs{
+ /**
+ * Implementation in code of a DFS
+ *
+ * @param a structure to be DFS'ed
+ * @param vertices The vertices
+ * @param source The source
+ */
public static void dfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
@@ -27,6 +40,11 @@ public static void dfs(byte [][] a,int vertices,int source){ //passin
}
+ /**
+ * The main method
+ *
+ * @param args Command line arguments
+ */
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
From 3714ffe326021e8c1990aff7154e43fb4862bf78 Mon Sep 17 00:00:00 2001
From: zacharyjones123
Date: Tue, 18 Apr 2017 07:59:09 -0700
Subject: [PATCH 0029/2305] I have also deleted these files in my commit
---
Binary Search.java | 74 ------------------------------------------
Binary to Decimal.java | 19 -----------
Bubble Sort.java | 38 ----------------------
Decimal to Binary.java | 19 -----------
Decimal to octal.java | 19 -----------
Insertion Sort.java | 38 ----------------------
InsertionSortInteger | 56 --------------------------------
Selection Sort.java | 40 -----------------------
reverse string.java | 25 --------------
9 files changed, 328 deletions(-)
delete mode 100644 Binary Search.java
delete mode 100644 Binary to Decimal.java
delete mode 100644 Bubble Sort.java
delete mode 100644 Decimal to Binary.java
delete mode 100644 Decimal to octal.java
delete mode 100644 Insertion Sort.java
delete mode 100644 InsertionSortInteger
delete mode 100644 Selection Sort.java
delete mode 100644 reverse string.java
diff --git a/Binary Search.java b/Binary Search.java
deleted file mode 100644
index 25814197fd23..000000000000
--- a/Binary Search.java
+++ /dev/null
@@ -1,74 +0,0 @@
-import java.util.Scanner;
-
-/**
- * Implements a Binary Search in Java
- *
- * @author unknown
- */
-class BinarySearch
-{
- /**
- * This method implements the 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 up The upper bound
- * @return the location of the key
- **/
- public static int BS(int array[], int key, int lb, int ub)
- { if (lb>ub)
- {
- return -1;
- }
-
- int mid=(lb+ub)/2;
-
- if (keyarray[mid])
- {
- return (BS(array, key, mid+1, ub));
- }
- else
- {
- return mid;
- }
- }
-
-
- /**
- * This is the main method of Binary Search
- *
- * @author Unknown
- * @param args Command line parameters
- */
-
- public static void main(String[] args)
- {
- Scanner input=new Scanner(System.in);
- int array[]=new int[10] ;
- int key;
-
- //Input
- System.out.println("Enter an array of 10 numbers : ");
- for (int i=0; i<10 ;i++ )
- {
- array[i]=input.nextInt();
- }
- System.out.println("Enter the number to be searched : ");
- key=input.nextInt();
-
- int index=BS(array, key, 0, 9);
- if (index!=-1)
- {
- System.out.println("Number found at index number : " + index);
- }
- else
- {
- System.out.println("Not found");
- }
- }
-}
diff --git a/Binary to Decimal.java b/Binary to Decimal.java
deleted file mode 100644
index b61c9f1c5c1b..000000000000
--- a/Binary to Decimal.java
+++ /dev/null
@@ -1,19 +0,0 @@
-#import java.util.*;
-class Binary_Decimal
-{
- public static void main(String args[])
- {
- Scanner sc=new Scanner(System.in);
- int n,k,d,s=0,c=0;
- n=sc.nextInt();
- k=n;
- while(k!=0)
- {
- d=k%10;
- s+=d*(int)Math.pow(2,c++);
- k/=10;
- }
- System.out.println("Binary number:"+n);
- System.out.println("Decimal equivalent:"+s);
- }
-}
diff --git a/Bubble Sort.java b/Bubble Sort.java
deleted file mode 100644
index a374d9ff7673..000000000000
--- a/Bubble Sort.java
+++ /dev/null
@@ -1,38 +0,0 @@
-import java.util.Scanner;
-
-class BubbleSort
-{
- public static void main(String[] args)
- {
- int array[]=new int[6];
- Scanner input=new Scanner(System.in);
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- for(int i=0; i<5; i++)
- {
- for(int j=i+1; j<6; j++)
- {
- if(array[j]>array[i])
- {
- int temp=array[j];
- array[j]=array[i];
- array[i]=temp;
- }
- }
- }
-
- //Output
- for(int i=0; i<6; i++)
- {
- System.out.print(array[i]+"\t");
- }
-
- }
-}
diff --git a/Decimal to Binary.java b/Decimal to Binary.java
deleted file mode 100644
index e89b65fade03..000000000000
--- a/Decimal to Binary.java
+++ /dev/null
@@ -1,19 +0,0 @@
-#import java.util.*;
-class Decimal_Binary
-{
- public static void main(String args[])
- {
- Scanner sc=new Scanner(System.in);
- int n,k,s=0,c=0,d;
- n=sc.nextInt();
- k=n;
- while(k!=0)
- {
- d=k%2;
- s=s+d*(int)Math.pow(10,c++);
- k/=2;
- }//converting decimal to binary
- System.out.println("Decimal number:"+n);
- System.out.println("Binary equivalent:"+s);
- }
-}
diff --git a/Decimal to octal.java b/Decimal to octal.java
deleted file mode 100644
index 11a8a563fd98..000000000000
--- a/Decimal to octal.java
+++ /dev/null
@@ -1,19 +0,0 @@
-#import java.util.*;
-class Decimal_Octal
-{
- public static void main()
- {
- Scanner sc=new Scanner(System.in);
- int n,k,d,s=0,c=0;
- n=sc.nextInt();
- k=n;
- while(k!=0)
- {
- d=k%8;
- s+=d*(int)Math.pow(10,c++);
- k/=8;
- }
- System.out.println("Decimal number:"+n);
- System.out.println("Octal equivalent:"+s);
- }
-}
diff --git a/Insertion Sort.java b/Insertion Sort.java
deleted file mode 100644
index 179030919796..000000000000
--- a/Insertion Sort.java
+++ /dev/null
@@ -1,38 +0,0 @@
-import java.util.Scanner;
-
-class InsertionSort
-{
- public static void main(String[] args)
- {
- int array[]=new int[6];
- Scanner input=new Scanner(System.in);
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- for(int i=0; i<6; i++)
- {
- int temp=array[i];
- int j=i-1;
- while(j>=0 && temp 0; lastSortedIndex--){
-
- //If our extracted element is smaller than element to the right, switch them.
- if (sortedArray[lastSortedIndex-1] > extractedElement){
- //move the element to the left of extractedElement to the right in sortedArray
- sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
- //And move the current extractedElement to the left one (since it's smaller).
- sortedArray[lastSortedIndex-1] = extractedElement;
- }
- else{
- //insert element where it is.
- sortedArray[lastSortedIndex] = extractedElement;
- //Terminating loop since element is in the right spot.
- break;
- }
-
- }
-
- }
-
- return sortedArray;
-
- }
-
-}
diff --git a/Selection Sort.java b/Selection Sort.java
deleted file mode 100644
index d4f7c0ccb1dd..000000000000
--- a/Selection Sort.java
+++ /dev/null
@@ -1,40 +0,0 @@
-import java.util.Scanner;
-
-class SelectionSort
-{
- public static void main(String[] args)
- {
- int array[]=new int[6];
- Scanner input=new Scanner(System.in);
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- for(int i=0; i<6; i++)
- {
- int min=i;
- for(int j=i+1; j<6; j++)
- {
- if(array[j]
Date: Tue, 18 Apr 2017 12:20:59 -0400
Subject: [PATCH 0030/2305] CircleLinkedList
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Uses a dummy node and generics…. this implementation of a singly linked
list eliminates need to use tail reference
---
data_structures/CircleLinkedList.java | 42 +++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
create mode 100644 data_structures/CircleLinkedList.java
diff --git a/data_structures/CircleLinkedList.java b/data_structures/CircleLinkedList.java
new file mode 100644
index 000000000000..cf03cd7cdfd2
--- /dev/null
+++ b/data_structures/CircleLinkedList.java
@@ -0,0 +1,42 @@
+public class CircleLinkedList{
+ private static class Node{
+ Node next;
+ E value;
+ private Node(E value, Node next){
+ this.value = value;
+ this.next = next;
+ }
+ }
+ private int size; //For better O.O design this should be private allows for better black box design
+ private Node head; //this will point to dummy node;
+ public CircleLinkedList(){ //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;
+ head = new Node(null,head); //creation of the dummy node
+ size = 0;
+ }
+ public int getSize(){ return size;} // getter for the size... needed because size is private.
+ public void append(E value){ // 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.
+ if(value == null){
+ throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list.
+ }
+ head.next = new Node(value,head); //head.next points to the last element;
+ size++;}
+ public E remove(int pos){
+ if(pos>size || pos< 0){
+ throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors
+ }
+ Node iterator = head.next;
+ Node before = head; //we need to keep track of the element before the element we want to remove we can see why bellow.
+ for(int i = 1; i<=pos; i++){
+ iterator = iterator.next;
+ before = before.next;
+ }
+ E saved = iterator.value;
+ before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
+ iterator.next = null; // scrubbing
+ iterator.value = null;
+ return saved;
+
+ }
+
+ }
+
From abbc4bee08adf9f0d6a26ad778600d9be0350c16 Mon Sep 17 00:00:00 2001
From: Moro-Code
Date: Tue, 18 Apr 2017 12:20:59 -0400
Subject: [PATCH 0031/2305] CircleLinkedList
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Uses a dummy node and generics…. this implementation of a singly linked
list eliminates need to use tail reference
---
data_structures/CircleLinkedList.java | 42 +++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
create mode 100644 data_structures/CircleLinkedList.java
diff --git a/data_structures/CircleLinkedList.java b/data_structures/CircleLinkedList.java
new file mode 100644
index 000000000000..cf03cd7cdfd2
--- /dev/null
+++ b/data_structures/CircleLinkedList.java
@@ -0,0 +1,42 @@
+public class CircleLinkedList{
+ private static class Node{
+ Node next;
+ E value;
+ private Node(E value, Node next){
+ this.value = value;
+ this.next = next;
+ }
+ }
+ private int size; //For better O.O design this should be private allows for better black box design
+ private Node head; //this will point to dummy node;
+ public CircleLinkedList(){ //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;
+ head = new Node(null,head); //creation of the dummy node
+ size = 0;
+ }
+ public int getSize(){ return size;} // getter for the size... needed because size is private.
+ public void append(E value){ // 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.
+ if(value == null){
+ throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list.
+ }
+ head.next = new Node(value,head); //head.next points to the last element;
+ size++;}
+ public E remove(int pos){
+ if(pos>size || pos< 0){
+ throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors
+ }
+ Node iterator = head.next;
+ Node before = head; //we need to keep track of the element before the element we want to remove we can see why bellow.
+ for(int i = 1; i<=pos; i++){
+ iterator = iterator.next;
+ before = before.next;
+ }
+ E saved = iterator.value;
+ before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
+ iterator.next = null; // scrubbing
+ iterator.value = null;
+ return saved;
+
+ }
+
+ }
+
From 03dbfa78c808306141004802aca1f8cd53341044 Mon Sep 17 00:00:00 2001
From: zacharyjones123
Date: Thu, 20 Apr 2017 11:56:21 -0700
Subject: [PATCH 0032/2305] - Closed all Scanner and Buffered Readers
- Added Some Java Doc
- ReverseString - took space out of between each letter so "Zachary" to
"yrahcaZ" instead of "y r a h c aZ"
- bfs - Trying to repair this class but need to research bfs more
- dfs - Trying to repair this class but need to research dfs more
- Added new Classes
1) OctalToBinary - Not done
2) BinaryToOctal - Not done
3) OctalToDecimal - Not done
4) Graphs
-Added the dataStructure Graphs (Unfinished)
---
BinarySearch.java | 1 +
BinaryToDecimal.java | 3 ++-
BinaryToOctal.java | 35 ++++++++++++++++++++++++++++++
BubbleSort.java | 2 +-
DecimalToBinary.java | 3 ++-
DecimalToOctal.java | 4 +++-
Factorial.java | 3 ++-
InsertionSort.java | 2 +-
InsertionSortInteger.java | 6 +++++
LinearSearch.java | 3 ++-
OctalToBinary.java | 34 +++++++++++++++++++++++++++++
OctalToDecimal.java | 34 +++++++++++++++++++++++++++++
Quicksort.java | 2 ++
ReverseString.java | 3 ++-
SelectionSort.java | 3 ++-
bfs.java | 20 +++++++++--------
countwords.java | 1 +
data_structures/Graphs.java | 32 +++++++++++++++++++++++++++
data_structures/heaps/MaxHeap.java | 1 -
data_structures/heaps/MinHeap.java | 1 -
dfs.java | 10 +++++----
21 files changed, 179 insertions(+), 24 deletions(-)
create mode 100644 BinaryToOctal.java
create mode 100644 OctalToBinary.java
create mode 100644 OctalToDecimal.java
create mode 100644 data_structures/Graphs.java
diff --git a/BinarySearch.java b/BinarySearch.java
index 25814197fd23..54f2c4c81d55 100644
--- a/BinarySearch.java
+++ b/BinarySearch.java
@@ -70,5 +70,6 @@ public static void main(String[] args)
{
System.out.println("Not found");
}
+ input.close();
}
}
diff --git a/BinaryToDecimal.java b/BinaryToDecimal.java
index f7357d3ce5d4..9e5494eebd85 100644
--- a/BinaryToDecimal.java
+++ b/BinaryToDecimal.java
@@ -18,6 +18,7 @@ public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,k,d,s=0,c=0;
+ System.out.print("Binary number: ");
n=sc.nextInt();
k=n;
while(k!=0)
@@ -26,7 +27,7 @@ public static void main(String args[])
s+=d*(int)Math.pow(2,c++);
k/=10;
}
- System.out.println("Binary number:"+n);
System.out.println("Decimal equivalent:"+s);
+ sc.close();
}
}
diff --git a/BinaryToOctal.java b/BinaryToOctal.java
new file mode 100644
index 000000000000..1e2dcd8182b5
--- /dev/null
+++ b/BinaryToOctal.java
@@ -0,0 +1,35 @@
+import java.util.Scanner;
+
+/**
+ * Converts any Binary number to an Octal Number
+ *
+ * @author Zachary Jones
+ *
+ */
+public class BinaryToOctal {
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int b = sc.nextInt();
+ System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
+ sc.close();
+
+ }
+
+ /**
+ * This method converts a binary number to
+ * an octal number.
+ *
+ * @param b The binary number
+ * @return The octal number
+ */
+ public static int convertBinaryToOctal(int b) {
+
+ }
+
+}
diff --git a/BubbleSort.java b/BubbleSort.java
index ac4015f18f3e..7e7c72f6ad87 100644
--- a/BubbleSort.java
+++ b/BubbleSort.java
@@ -45,6 +45,6 @@ public static void main(String[] args)
{
System.out.print(array[i]+"\t");
}
-
+ input.close();
}
}
diff --git a/DecimalToBinary.java b/DecimalToBinary.java
index e88c7d97658f..671cedf201d2 100644
--- a/DecimalToBinary.java
+++ b/DecimalToBinary.java
@@ -17,6 +17,7 @@ public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,k,s=0,c=0,d;
+ System.out.print("Decimal number: ");
n=sc.nextInt();
k=n;
while(k!=0)
@@ -25,7 +26,7 @@ public static void main(String args[])
s=s+d*(int)Math.pow(10,c++);
k/=2;
}//converting decimal to binary
- System.out.println("Decimal number:"+n);
System.out.println("Binary equivalent:"+s);
+ sc.close();
}
}
diff --git a/DecimalToOctal.java b/DecimalToOctal.java
index f0590316041c..1efa00f8b938 100644
--- a/DecimalToOctal.java
+++ b/DecimalToOctal.java
@@ -17,6 +17,7 @@ public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n,k,d,s=0,c=0;
+ System.out.print("Decimal number: ");
n=sc.nextInt();
k=n;
while(k!=0)
@@ -25,7 +26,8 @@ public static void main(String[] args)
s+=d*(int)Math.pow(10,c++);
k/=8;
}
- System.out.println("Decimal number:"+n);
+
System.out.println("Octal equivalent:"+s);
+ sc.close();
}
}
diff --git a/Factorial.java b/Factorial.java
index 134ec2f5de5e..a3b4052eda8f 100644
--- a/Factorial.java
+++ b/Factorial.java
@@ -29,7 +29,8 @@ public static void main(String[] args){
//Output of factorial for any non-negative number
System.out.println("The factorial of "+number+" will yield: "+factorial(number));
}
- }
+ }
+ input.close();
}
/**
diff --git a/InsertionSort.java b/InsertionSort.java
index 772b5a77e2d8..0fa34c2b46ef 100644
--- a/InsertionSort.java
+++ b/InsertionSort.java
@@ -44,6 +44,6 @@ public static void main(String[] args)
{
System.out.print(array[i]+"\t");
}
-
+ input.close();
}
}
\ No newline at end of file
diff --git a/InsertionSortInteger.java b/InsertionSortInteger.java
index 7f4cfce2951d..fa31ac2560b6 100644
--- a/InsertionSortInteger.java
+++ b/InsertionSortInteger.java
@@ -11,6 +11,12 @@
public class InsertionSortInteger {
+ /**
+ * This method implements insertion sort by integer
+ *
+ * @param initialArray array to be sorted
+ * @return sorted array
+ */
public int[] insertionIntArraySort(int[] initialArray){
int[] sortedArray = new int[initialArray.length];
diff --git a/LinearSearch.java b/LinearSearch.java
index f74f4ad096e6..cac1d4995be5 100644
--- a/LinearSearch.java
+++ b/LinearSearch.java
@@ -27,7 +27,8 @@ public static void main(String[] args){
//Output array and index of target element, if found
printarray(myArray);
System.out.printf("The integer %d is found in index %d\n", key, linearsearch(myArray, key));
-
+
+ input.close();
}
/**
diff --git a/OctalToBinary.java b/OctalToBinary.java
new file mode 100644
index 000000000000..23c9a46adf8e
--- /dev/null
+++ b/OctalToBinary.java
@@ -0,0 +1,34 @@
+import java.util.Scanner;
+
+/**
+ * Converts any Octal number to a Binary number
+ *
+ * @author Zachary Jones
+ *
+ */
+public class OctalToBinary {
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int o = sc.nextInt();
+ System.out.println("Binary equivalent: " + convertOctalToBinary(o));
+ sc.close();
+ }
+
+ /**
+ * This method converts an octal number
+ * to a binary number.
+ *
+ * @param o The octal number
+ * @return The binary number
+ */
+ public static int convertOctalToBinary(int o) {
+
+ }
+
+}
diff --git a/OctalToDecimal.java b/OctalToDecimal.java
new file mode 100644
index 000000000000..fe82b5fff48e
--- /dev/null
+++ b/OctalToDecimal.java
@@ -0,0 +1,34 @@
+import java.util.Scanner;
+
+/**
+ * Converts any Octal Number to a Decimal Number
+ *
+ * @author Zachary Jones
+ *
+ */
+public class OctalToDecimal {
+
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int o = sc.nextInt();
+ System.out.println("Decimal equivalent: " + convertOctalToDecimal(o));
+ sc.close();
+ }
+
+ /**
+ * This method converts an octal number to
+ * a decimal number.
+ *
+ * @param o The octal number
+ * @return The decimal number
+ */
+ public static int convertOctalToDecimal(int o) {
+
+ }
+
+}
diff --git a/Quicksort.java b/Quicksort.java
index 5b5896f8a12e..886f0e772a4f 100644
--- a/Quicksort.java
+++ b/Quicksort.java
@@ -38,6 +38,8 @@ public static void main(String[] args){
System.out.println("The sorted array is: ");
printarray(array);
System.out.println();
+
+ input.close();
}
/**
diff --git a/ReverseString.java b/ReverseString.java
index e8a75b3ed99e..409735502ba1 100644
--- a/ReverseString.java
+++ b/ReverseString.java
@@ -18,7 +18,7 @@ class ReverseString
*/
static String reverseString(String str)
{
- String reverse=" ";
+ String reverse="";
if(str.length()==1)
{
return str;
@@ -42,6 +42,7 @@ public static void main(String args[]) throws IOException
System.out.println("Enter the string");
String srr=br.readLine();
System.out.println("Reverse="+reverseString(srr));
+ br.close();
}
}
\ No newline at end of file
diff --git a/SelectionSort.java b/SelectionSort.java
index d8e1e0032df0..82fecda12a15 100644
--- a/SelectionSort.java
+++ b/SelectionSort.java
@@ -47,6 +47,7 @@ public static void main(String[] args)
{
System.out.print(array[i]+"\t");
}
-
+
+ input.close();
}
}
\ No newline at end of file
diff --git a/bfs.java b/bfs.java
index 085e302cc100..90ff4eca87ef 100644
--- a/bfs.java
+++ b/bfs.java
@@ -15,7 +15,7 @@ public class bfs{
* @param vertices The vertices to use
* @param source The Source
*/
- public static void bfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
+ public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
@@ -23,17 +23,17 @@ public static void bfs(byte [][] a,int vertices,int source){ //passing adjacenc
0 = waiting
1 = processed */
- Queue st=new Queue<>(); //operational stack
- st.add(source); //assigning source
+ Stack st = new Stack(vertices); //operational stack
+ st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
- System.out.println(st.element());
- int pop=st.element();
+ System.out.println(st.peek());
+ int pop=st.peek();
b[pop]=(byte)1; //assigning processed status
- st.remove(); //removing head of the queue
+ st.pop(); //removing head of the queue
for(int i=0;i maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
diff --git a/data_structures/heaps/MinHeap.java b/data_structures/heaps/MinHeap.java
index 5793bb92f215..fbf2b86ffc3e 100644
--- a/data_structures/heaps/MinHeap.java
+++ b/data_structures/heaps/MinHeap.java
@@ -91,7 +91,6 @@ public void deleteElement(int elementIndex) {
try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
diff --git a/dfs.java b/dfs.java
index 023e1d5ffc59..8ceba166e149 100644
--- a/dfs.java
+++ b/dfs.java
@@ -16,7 +16,7 @@ public class dfs{
* @param vertices The vertices
* @param source The source
*/
- public static void dfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
+ public static void dfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
@@ -25,7 +25,7 @@ public static void dfs(byte [][] a,int vertices,int source){ //passin
1 = processed */
- Stack st=new Stack<>(); //operational stack
+ Stack st=new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
@@ -57,5 +57,7 @@ public static void main(String args[]){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
- bfs(a,vertices,source); //function call
- }}
+ dfsImplement(a,vertices,source); //function call
+ in.close();
+ }
+}
From 410d2e3e8b63d59a710de36c19ed1a1877f94aae Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Sat, 22 Apr 2017 14:50:28 +0100
Subject: [PATCH 0033/2305] Create radixSort.java
---
radixSort.java | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 67 insertions(+)
create mode 100644 radixSort.java
diff --git a/radixSort.java b/radixSort.java
new file mode 100644
index 000000000000..572917b52edb
--- /dev/null
+++ b/radixSort.java
@@ -0,0 +1,67 @@
+
+import java.io.*;
+import java.util.*;
+
+class Radix {
+
+
+ static int getMax(int arr[], int n)
+ {
+ int mx = arr[0];
+ for (int i = 1; i < n; i++)
+ if (arr[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
Date: Sun, 23 Apr 2017 18:44:51 +0100
Subject: [PATCH 0034/2305] Create AVLTree.java
---
data_structures/AVLTree.java | 212 +++++++++++++++++++++++++++++++++++
1 file changed, 212 insertions(+)
create mode 100644 data_structures/AVLTree.java
diff --git a/data_structures/AVLTree.java b/data_structures/AVLTree.java
new file mode 100644
index 000000000000..a3bde289fe15
--- /dev/null
+++ b/data_structures/AVLTree.java
@@ -0,0 +1,212 @@
+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();
+ }
+}
From 8426d22e8105064dac7b462d229ae55ebd3d10ce Mon Sep 17 00:00:00 2001
From: Mayank Kumar Jha
Date: Mon, 24 Apr 2017 19:13:31 +0530
Subject: [PATCH 0035/2305] Add files via upload
---
Dijkshtra.java | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 Dijkshtra.java
diff --git a/Dijkshtra.java b/Dijkshtra.java
new file mode 100644
index 000000000000..93c58d670805
--- /dev/null
+++ b/Dijkshtra.java
@@ -0,0 +1,38 @@
+public static void main(String[] args) throws IOException {
+ Reader in=new Reader();
+ int t1=in.nextInt();
+ for(int gj=0;gjcmp){
+ w[x][y]=cmp; w[y][x]=cmp;
+ }
+ }
+ 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
Date: Mon, 24 Apr 2017 19:24:24 +0530
Subject: [PATCH 0036/2305] Dijkshtra's Algorithm
---
Dijkshtra.java | 30 ++++++++++++++++++++----------
1 file changed, 20 insertions(+), 10 deletions(-)
diff --git a/Dijkshtra.java b/Dijkshtra.java
index 93c58d670805..ed05ef343b24 100644
--- a/Dijkshtra.java
+++ b/Dijkshtra.java
@@ -1,20 +1,28 @@
public static void main(String[] args) throws IOException {
Reader in=new Reader();
int t1=in.nextInt();
- for(int gj=0;gjcmp){
- w[x][y]=cmp; w[y][x]=cmp;
+ if(w[x][y]>cmp){ //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++){
@@ -30,9 +38,11 @@ public static void main(String[] args) throws IOException {
min=(int) w[src][t.elementAt(i)];loc=i;}
}
p.push(t.elementAt(loc));t.removeElementAt(loc);}
+
+ //Printing shortest path from the given source src
for(int i=1;i<=n;i++){
if(i!=src && w[src][i]!=1000000l){System.out.print(w[src][i]+" ");}
- else if(i!=src){System.out.print("-1"+" ");}
- }System.out.println();
+ else if(i!=src){System.out.print("-1"+" ");} //Printing -1 if there is no path b/w given pair of edges
}
+
}
From 1857fac133de94ce5003cef025e0efaa16284a7c Mon Sep 17 00:00:00 2001
From: Mayank Kumar Jha
Date: Mon, 24 Apr 2017 19:25:18 +0530
Subject: [PATCH 0037/2305] Dijkshtra.java
---
Dijkshtra.java | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/Dijkshtra.java b/Dijkshtra.java
index ed05ef343b24..7b4f19738606 100644
--- a/Dijkshtra.java
+++ b/Dijkshtra.java
@@ -1,7 +1,6 @@
public static void main(String[] args) throws IOException {
- Reader in=new Reader();
- int t1=in.nextInt();
-
+ 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
From a7cef0c4e4ce9e32cf0f6bf6197fde683c5f3452 Mon Sep 17 00:00:00 2001
From: Mayank Kumar Jha
Date: Mon, 24 Apr 2017 19:27:05 +0530
Subject: [PATCH 0038/2305] Dijkshtra.java
---
Dijkshtra.java | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/Dijkshtra.java b/Dijkshtra.java
index 7b4f19738606..377c487ee35a 100644
--- a/Dijkshtra.java
+++ b/Dijkshtra.java
@@ -1,3 +1,11 @@
+/*
+@author : Mayank K Jha
+
+*/
+
+
+public class Solution {
+
public static void main(String[] args) throws IOException {
Scanner in =new Scanner(System.in);
@@ -45,3 +53,4 @@ public static void main(String[] args) throws IOException {
}
}
+}
From 324e48903b25833af0c5dc176d23c98e79f98e2d Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:18:36 +0100
Subject: [PATCH 0039/2305] Rename BinarySearch.java to
Searches/BinarySearch.java
---
BinarySearch.java => Searches/BinarySearch.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename BinarySearch.java => Searches/BinarySearch.java (100%)
diff --git a/BinarySearch.java b/Searches/BinarySearch.java
similarity index 100%
rename from BinarySearch.java
rename to Searches/BinarySearch.java
From 66d46798d0aee64c7500d45784d5b1dc85c7c39b Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:18:48 +0100
Subject: [PATCH 0040/2305] Rename LinearSearch.java to
Searches/LinearSearch.java
---
LinearSearch.java => Searches/LinearSearch.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename LinearSearch.java => Searches/LinearSearch.java (99%)
diff --git a/LinearSearch.java b/Searches/LinearSearch.java
similarity index 99%
rename from LinearSearch.java
rename to Searches/LinearSearch.java
index cac1d4995be5..0a1bb7cc58cc 100644
--- a/LinearSearch.java
+++ b/Searches/LinearSearch.java
@@ -59,4 +59,4 @@ public static void printarray(int[] a){
}
System.out.println();
}
-}
\ No newline at end of file
+}
From 0fdf57d75b2627adaefecd66561d6bc0f9011bcb Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:19:39 +0100
Subject: [PATCH 0041/2305] Rename BinaryToDecimal.java to
Conversions/BinaryToDecimal.java
---
BinaryToDecimal.java => Conversions/BinaryToDecimal.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename BinaryToDecimal.java => Conversions/BinaryToDecimal.java (100%)
diff --git a/BinaryToDecimal.java b/Conversions/BinaryToDecimal.java
similarity index 100%
rename from BinaryToDecimal.java
rename to Conversions/BinaryToDecimal.java
From 27cfc289f98848fb64d0f53732c42dab630bdb14 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:20:32 +0100
Subject: [PATCH 0042/2305] Rename BinaryToOctal.java to
Conversions/BinaryToOctal.java
---
BinaryToOctal.java => Conversions/BinaryToOctal.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename BinaryToOctal.java => Conversions/BinaryToOctal.java (100%)
diff --git a/BinaryToOctal.java b/Conversions/BinaryToOctal.java
similarity index 100%
rename from BinaryToOctal.java
rename to Conversions/BinaryToOctal.java
From 953db7566da1d1113a32cda98236df8b92f54a96 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:20:58 +0100
Subject: [PATCH 0043/2305] Rename DecimalToBinary.java to
Conversions/DecimalToBinary.java
---
DecimalToBinary.java => Conversions/DecimalToBinary.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename DecimalToBinary.java => Conversions/DecimalToBinary.java (100%)
diff --git a/DecimalToBinary.java b/Conversions/DecimalToBinary.java
similarity index 100%
rename from DecimalToBinary.java
rename to Conversions/DecimalToBinary.java
From bf1c1a26771af28f26833e1b5fba6244607d7b99 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:21:14 +0100
Subject: [PATCH 0044/2305] Rename OctalToBinary.java to
Conversions/OctalToBinary.java
---
OctalToBinary.java => Conversions/OctalToBinary.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename OctalToBinary.java => Conversions/OctalToBinary.java (100%)
diff --git a/OctalToBinary.java b/Conversions/OctalToBinary.java
similarity index 100%
rename from OctalToBinary.java
rename to Conversions/OctalToBinary.java
From 97b748012cdb1d7da887d476b146f6a306c474bc Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:23:09 +0100
Subject: [PATCH 0045/2305] Rename OctalToDecimal.java to
Conversions/OctalToDecimal.java
---
OctalToDecimal.java => Conversions/OctalToDecimal.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename OctalToDecimal.java => Conversions/OctalToDecimal.java (100%)
diff --git a/OctalToDecimal.java b/Conversions/OctalToDecimal.java
similarity index 100%
rename from OctalToDecimal.java
rename to Conversions/OctalToDecimal.java
From 04f120c83038bff865d6c1d8651f1a6cc4eccfe7 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:25:43 +0100
Subject: [PATCH 0046/2305] Rename BubbleSort.java to Sorts/BubbleSort.java
---
BubbleSort.java => Sorts/BubbleSort.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename BubbleSort.java => Sorts/BubbleSort.java (100%)
diff --git a/BubbleSort.java b/Sorts/BubbleSort.java
similarity index 100%
rename from BubbleSort.java
rename to Sorts/BubbleSort.java
From 899eae0423e02daab9df6a22cb345ff569d45e53 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:26:05 +0100
Subject: [PATCH 0047/2305] Rename HeapSort.java to Sorts/HeapSort.java
---
HeapSort.java => Sorts/HeapSort.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename HeapSort.java => Sorts/HeapSort.java (100%)
diff --git a/HeapSort.java b/Sorts/HeapSort.java
similarity index 100%
rename from HeapSort.java
rename to Sorts/HeapSort.java
From 440ba12ec0d9b05a5894ed0e59b45c1e3c023612 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:27:23 +0100
Subject: [PATCH 0048/2305] Rename InsertionSort.java to
Sorts/InsertionSort.java
---
InsertionSort.java => Sorts/InsertionSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename InsertionSort.java => Sorts/InsertionSort.java (99%)
diff --git a/InsertionSort.java b/Sorts/InsertionSort.java
similarity index 99%
rename from InsertionSort.java
rename to Sorts/InsertionSort.java
index 0fa34c2b46ef..d9d86566354b 100644
--- a/InsertionSort.java
+++ b/Sorts/InsertionSort.java
@@ -46,4 +46,4 @@ public static void main(String[] args)
}
input.close();
}
-}
\ No newline at end of file
+}
From ff6dceb9d61d4971ad62ae36736e4d2ae2502ffd Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:28:20 +0100
Subject: [PATCH 0049/2305] Rename InsertionSortInteger.java to
Sorts/InsertionSortInteger.java
---
InsertionSortInteger.java => Sorts/InsertionSortInteger.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename InsertionSortInteger.java => Sorts/InsertionSortInteger.java (100%)
diff --git a/InsertionSortInteger.java b/Sorts/InsertionSortInteger.java
similarity index 100%
rename from InsertionSortInteger.java
rename to Sorts/InsertionSortInteger.java
From e99bf76fe7c194a008a42869f785f637f01e7bf7 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:28:55 +0100
Subject: [PATCH 0050/2305] Rename MergeSort.java to Sorts/MergeSort.java
---
MergeSort.java => Sorts/MergeSort.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename MergeSort.java => Sorts/MergeSort.java (100%)
diff --git a/MergeSort.java b/Sorts/MergeSort.java
similarity index 100%
rename from MergeSort.java
rename to Sorts/MergeSort.java
From 7d586be1deab37a92ff2e71ffe09da6ac262aaf1 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:29:16 +0100
Subject: [PATCH 0051/2305] Rename Quicksort.java to Sorts/Quicksort.java
---
Quicksort.java => Sorts/Quicksort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename Quicksort.java => Sorts/Quicksort.java (99%)
diff --git a/Quicksort.java b/Sorts/Quicksort.java
similarity index 99%
rename from Quicksort.java
rename to Sorts/Quicksort.java
index 886f0e772a4f..11533f0b0e6d 100644
--- a/Quicksort.java
+++ b/Sorts/Quicksort.java
@@ -99,4 +99,4 @@ public static void printarray(int[] array){
System.out.print(data + " ");
}
}
-}
\ No newline at end of file
+}
From 88338805a325c4097e1456e3c6c4f3c25bbe4f15 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:29:41 +0100
Subject: [PATCH 0052/2305] Rename SelectionSort.java to
Sorts/SelectionSort.java
---
SelectionSort.java => Sorts/SelectionSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename SelectionSort.java => Sorts/SelectionSort.java (99%)
diff --git a/SelectionSort.java b/Sorts/SelectionSort.java
similarity index 99%
rename from SelectionSort.java
rename to Sorts/SelectionSort.java
index 82fecda12a15..955e7d65b9f7 100644
--- a/SelectionSort.java
+++ b/Sorts/SelectionSort.java
@@ -50,4 +50,4 @@ public static void main(String[] args)
input.close();
}
-}
\ No newline at end of file
+}
From 3ead086ef3f54af8f09201b6c5b5f60c183bebd7 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:30:05 +0100
Subject: [PATCH 0053/2305] Rename radixSort.java to Sorts/radixSort.java
---
radixSort.java => Sorts/radixSort.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename radixSort.java => Sorts/radixSort.java (100%)
diff --git a/radixSort.java b/Sorts/radixSort.java
similarity index 100%
rename from radixSort.java
rename to Sorts/radixSort.java
From ced637c301bf01a62d2af2d05270023169391162 Mon Sep 17 00:00:00 2001
From: James Mc Dermott
Date: Thu, 27 Apr 2017 15:45:42 +0100
Subject: [PATCH 0054/2305] Rename data_structures/BinaryTree.java to
data_structures/Trees/BinaryTree.java
---
data_structures/{ => Trees}/BinaryTree.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
rename data_structures/{ => Trees}/BinaryTree.java (99%)
diff --git a/data_structures/BinaryTree.java b/data_structures/Trees/BinaryTree.java
similarity index 99%
rename from data_structures/BinaryTree.java
rename to data_structures/Trees/BinaryTree.java
index b26525cfc730..3d05f1767819 100644
--- a/data_structures/BinaryTree.java
+++ b/data_structures/Trees/BinaryTree.java
@@ -267,4 +267,4 @@ public void postOrder(Node localRoot){
System.out.print(localRoot.data + " ");
}
}
-}
\ No newline at end of file
+}
From e5dd6eff0257cda48fe92fa5e905fc3c82f98bfd Mon Sep 17 00:00:00 2001
From: UsernameToLon
Date: Thu, 18 May 2017 14:11:47 -0400
Subject: [PATCH 0055/2305] Updated to more efficient version if array size is
scaled.
Changed loop from "for" to "do-while". Added decrement at end of do loop to decrease size of array tested after each iteration.
---
Sorts/BubbleSort.java | 34 +++++++++++++++++++++-------------
1 file changed, 21 insertions(+), 13 deletions(-)
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index 7e7c72f6ad87..1abe69368045 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -16,8 +16,12 @@ class BubbleSort
*/
public static void main(String[] args)
{
- int array[]=new int[6];
+ int size = 6;
+ int array[]=new int[size];
+ boolean swap;
+ int last = size - 1;
Scanner input=new Scanner(System.in);
+
//Input
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
@@ -27,18 +31,22 @@ public static void main(String[] args)
}
//Sorting
- for(int i=0; i<5; i++)
- {
- for(int j=i+1; j<6; j++)
- {
- if(array[j]>array[i])
- {
- int temp=array[j];
- array[j]=array[i];
- array[i]=temp;
- }
- }
- }
+ do
+ {
+ swap = false;
+ for (int count = 0; count < last; count++)
+ {
+ if (array[count] > array[count + 1])
+ {
+ int temp = array[count];
+ array[count] = array[count + 1];
+ array[count + 1] = temp;
+ swap = true;
+ }
+ }
+
+ last--;
+ } while (swap);
//Output
for(int i=0; i<6; i++)
From 10889f4993fa90527de9ba9307a6e65fdffd9bce Mon Sep 17 00:00:00 2001
From: Eric Ruggieri
Date: Wed, 24 May 2017 13:46:54 -0400
Subject: [PATCH 0056/2305] Update BinaryToOctal.java
added logic to convert binary to octal
---
Conversions/BinaryToOctal.java | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/Conversions/BinaryToOctal.java b/Conversions/BinaryToOctal.java
index 1e2dcd8182b5..cb04fe54be5a 100644
--- a/Conversions/BinaryToOctal.java
+++ b/Conversions/BinaryToOctal.java
@@ -29,7 +29,15 @@ public static void main(String args[]) {
* @return The octal number
*/
public static int convertBinaryToOctal(int b) {
-
+ int o = 0, r=0, j =1 ;
+ while(b!=0)
+ {
+ r = b % 10;
+ o = o + r * j;
+ j = j * 2;
+ b = b / 10;
+ }
+ return o;
}
}
From 149e5d2abc347d08ed33adb4f3c33472ee3e47ba Mon Sep 17 00:00:00 2001
From: MarcHines
Date: Wed, 31 May 2017 19:38:17 -0400
Subject: [PATCH 0057/2305] Update Factorial.java
The factorial method can be simplified to 2 lines, which I believe is easier to read. Also, in previous version, if user enters two negative numbers back to back, the program crashes. We need a while loop to prompt the user until they actually enter the correct input, instead of only prompting them once. Also, if user enters a character instead of an integer, program crashes with no error message. We should fail more gracefully.
---
Factorial.java | 55 ++++++++++++++++++++++++--------------------------
1 file changed, 26 insertions(+), 29 deletions(-)
diff --git a/Factorial.java b/Factorial.java
index a3b4052eda8f..b7cc906ae8dd 100644
--- a/Factorial.java
+++ b/Factorial.java
@@ -1,10 +1,11 @@
+package factorial;
import java.util.Scanner;
/**
* This program will print out the factorial of any non-negative
* number that you input into it.
*
- * @author Unknown
+ * @author Marcus
*
*/
public class Factorial{
@@ -15,24 +16,27 @@ public class Factorial{
* @param args Command line arguments
*/
public static void main(String[] args){
- Scanner input = new Scanner(System.in);
- //Prompt user to enter integer
- System.out.print("Enter a non-negative integer: ");
-
- //Proceed with factorial calculation only if inputted number is not negative
- if(input.hasNextInt()){
- int number = input.nextInt();
- if (number < 0){
- System.out.print("Cannot execute. Please enter a non-negative integer: ");
- number = input.nextInt();
- } else {
- //Output of factorial for any non-negative number
- System.out.println("The factorial of "+number+" will yield: "+factorial(number));
- }
- }
- input.close();
- }
-
+ Scanner input = new Scanner(System.in);
+ System.out.print("Enter a non-negative integer: ");
+
+ //If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
+ try{
+ int number = input.nextInt();
+
+ //We keep prompting the user until they enter a positive number
+ while(number < 0){
+ System.out.println("Your input must be non-negative. Please enter a positive number: ");
+ number = input.nextInt();
+ }
+ //Display the result
+ System.out.println("The factorial of " + number + " will yield: " + factorial(number));
+
+ }catch(Exception e){
+ System.out.println("Error: You did not enter an integer. Program has terminated.");
+ }
+ input.close();
+ }
+
/**
* Recursive Factorial Method
*
@@ -40,14 +44,7 @@ public static void main(String[] args){
* @return The factorial of the number
*/
public static long factorial(int n){
-
- if (n==0){
- return 1;
- } else if (n==1){
- return 1;
- } else {
- return n * factorial(n-1);
- }
-
+ if(n == 0 || n == 1) return 1;
+ return n * factorial(n - 1);
}
-}
\ No newline at end of file
+}
From 56ca966d478795fdbc444779aa8e37f153f4ba65 Mon Sep 17 00:00:00 2001
From: MarcHines
Date: Wed, 31 May 2017 19:59:11 -0400
Subject: [PATCH 0058/2305] Update countwords.java
Easier to read.
---
countwords.java | 39 +++++++++++++++------------------------
1 file changed, 15 insertions(+), 24 deletions(-)
diff --git a/countwords.java b/countwords.java
index c11540de32f8..5d18ae52b728 100644
--- a/countwords.java
+++ b/countwords.java
@@ -4,30 +4,21 @@
* You enter a string into this program, and it will return how
* many words were in that particular string
*
- * @author Unknown
+ * @author Marcus
*
*/
-class CountTheWords
-{
- /**
- * The main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[])
- {
- System.out.println("Enter the string");
- Scanner sc = new Scanner(System.in);
- String s=sc.nextLine();
- int count = 1;
- for (int i = 0; i < s.length()-1; i++)
- {
- if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
- {
- count++;
- }
+ public static void main(String[] args){
+ Scanner input = new Scanner(System.in);
+ System.out.println("Enter your text: ");
+ String str = input.nextLine();
+
+ System.out.println("Your text has " + wordCount(str) + " word(s)");
+ input.close();
+ }
+
+ public static int wordCount(String s){
+ if(s.isEmpty() || s == null) return -1;
+ return s.trim().split("[\\s]+").length;
}
- System.out.println("Number of words in the string = "+count);
- sc.close();
- }
-}
\ No newline at end of file
+
+ }
From abc0e4593d9e6ac3a32aefd125ca0635eb4a8993 Mon Sep 17 00:00:00 2001
From: MarcHines
Date: Thu, 1 Jun 2017 00:17:06 -0400
Subject: [PATCH 0059/2305] Update countwords.java
Class was added back.
---
countwords.java | 2 ++
1 file changed, 2 insertions(+)
diff --git a/countwords.java b/countwords.java
index 5d18ae52b728..065c9a1030a3 100644
--- a/countwords.java
+++ b/countwords.java
@@ -7,6 +7,8 @@
* @author Marcus
*
*/
+ class CountTheWords{
+
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your text: ");
From 066dd615a66baea8b2c8a007d23c25377368fc05 Mon Sep 17 00:00:00 2001
From: MarcHines
Date: Thu, 1 Jun 2017 08:09:19 -0400
Subject: [PATCH 0060/2305] Update ReverseString.java
Using recursion for reversing a String serves us no benifit. It places extra load on the stack, and it is less efficient than doing so iteratively. I understand now that we can not use built in reverse function, but using recursion is still the worst way we could do the task of String reversal. Everytime we call the reverse method we are placing an extra frame on our stack. This uses space. We also create another string that we are appending our result to with the recursive solution, which is slow because under the hood, Java will create a new empty String and then append each character to the new String, one char at a time. If we do this for each character, then asymtotically we now have time complexity of O(n^2). Recursion in this case also does not make our solution "simpler" or "more elegant". We want to use recursion when it is advantageous to do so....like traversing trees
---
ReverseString.java | 26 ++++++++++++--------------
1 file changed, 12 insertions(+), 14 deletions(-)
diff --git a/ReverseString.java b/ReverseString.java
index 409735502ba1..81498858c376 100644
--- a/ReverseString.java
+++ b/ReverseString.java
@@ -16,19 +16,17 @@ class ReverseString
* @param str String to be reversed
* @return Reversed string
*/
- static String reverseString(String str)
- {
- String reverse="";
- if(str.length()==1)
- {
- return str;
- }
- else
- {
- reverse=reverse+str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1));
- return reverse;
- }
- }
+ 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
@@ -45,4 +43,4 @@ public static void main(String args[]) throws IOException
br.close();
}
}
-
\ No newline at end of file
+
From ec8b8c056adf936100fbad67298219a1ca8c799b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Andr=C3=A9s=20Jozef=20Jim=C3=A9nez=20Leandro?=
Date: Fri, 9 Jun 2017 16:50:42 -0600
Subject: [PATCH 0061/2305] Conversions Works
Finished some unfinished conversions in Octal system.
Added Decimal to HexaDecimal conversion.
---
Conversions/DecimalToHexaDecimal.java | 33 +++++++++++++++++++++++++++
Conversions/OctalToBinary.java | 19 +++++++++++++--
Conversions/OctalToDecimal.java | 20 +++++++++++++---
3 files changed, 67 insertions(+), 5 deletions(-)
create mode 100644 Conversions/DecimalToHexaDecimal.java
diff --git a/Conversions/DecimalToHexaDecimal.java b/Conversions/DecimalToHexaDecimal.java
new file mode 100644
index 000000000000..3072dec0b1a7
--- /dev/null
+++ b/Conversions/DecimalToHexaDecimal.java
@@ -0,0 +1,33 @@
+import java.lang.StringBuilder;
+import java.util.Scanner;
+
+class Test {
+ private static final int sizeOfIntInHalfBytes = 8;
+ private static final int numberOfBitsInAHalfByte = 4;
+ private static final int halfByte = 0x0F;
+ private static final char[] hexDigits = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+
+ public static String decToHex(int dec) {
+ StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
+ hexBuilder.setLength(sizeOfIntInHalfBytes);
+ for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
+ {
+ int j = dec & halfByte;
+ hexBuilder.setCharAt(i, hexDigits[j]);
+ dec >>= numberOfBitsInAHalfByte;
+ }
+ return hexBuilder.toString();
+ }
+
+ public static void main(String[] args) {
+ Scanner sc = new Scanner(System.in);
+ System.out.println("Write your Number to convert into HexaDecimal: ")
+ int dec = 305445566;
+ String hex = Integer.toHexString(dec);
+ String hex = decToHex(dec);
+ System.out.println(hex);
+ }
+}
\ No newline at end of file
diff --git a/Conversions/OctalToBinary.java b/Conversions/OctalToBinary.java
index 23c9a46adf8e..6a011c094cab 100644
--- a/Conversions/OctalToBinary.java
+++ b/Conversions/OctalToBinary.java
@@ -28,7 +28,22 @@ public static void main(String args[]) {
* @return The binary number
*/
public static int convertOctalToBinary(int o) {
+ Scanner scan;
+ int num;
+
+ void getVal() {
+
+ System.out.println("Octal to Binary");
+ scan = new Scanner(System.in);
+ // Entering the needed number
+ System.out.println("\nEnter the number : ");
+ num = Integer.parseInt(scan.nextLine(), 8);
+ }
+ void convert() {
+
+ String binary = Integer.toBinaryString(num);
+ System.out.println("Binary Value is : " + binary);
+ }
}
-
-}
+}
\ No newline at end of file
diff --git a/Conversions/OctalToDecimal.java b/Conversions/OctalToDecimal.java
index fe82b5fff48e..637b8f2ec6dc 100644
--- a/Conversions/OctalToDecimal.java
+++ b/Conversions/OctalToDecimal.java
@@ -28,7 +28,21 @@ public static void main(String args[]) {
* @return The decimal number
*/
public static int convertOctalToDecimal(int o) {
-
+ System.out.print("Octal Input: ");
+ // Read the input from the console which we are expecting as an octal number:
+ Scanner s = new Scanner(System.in);
+ String inputHex = s.nextLine();
+ try{
+ // Actual conversion of Octal to Decimal:
+ Integer outputDecimal = Integer.parseInt(inputHex, 8);
+ System.out.println("Decimal Equivalent : " + outputDecimal);
+ }
+ catch(NumberFormatException ne){
+ // Printing a warning message if the input is not a valid octal number:
+ System.out.println("Invalid Input, Expecting octal number 0-7");
+ }
+ finally{
+ s.close();
+ }
}
-
-}
+}
\ No newline at end of file
From d89189a5d16115e2f9a570504a00763da08e6542 Mon Sep 17 00:00:00 2001
From: Ashish Agarwal
Date: Fri, 16 Jun 2017 16:47:35 +0530
Subject: [PATCH 0062/2305] floyd triangle
---
.DS_Store | Bin 8196 -> 8196 bytes
ft.java | 19 +++++++++++++++++++
2 files changed, 19 insertions(+)
create mode 100644 ft.java
diff --git a/.DS_Store b/.DS_Store
index dd05b9be5a8cdaa608a8a520040e4f99e574da1b..27875fa6e0825fbffd3779ceb1765c6599a40067 100644
GIT binary patch
delta 104
zcmZp1XmOa}&nUDpU^hRb&}JTiR3>J2hP25ILJ}PRpNmD
diff --git a/ft.java b/ft.java
new file mode 100644
index 000000000000..843f4a559bde
--- /dev/null
+++ b/ft.java
@@ -0,0 +1,19 @@
+import java.util.Scanner;
+ class FloydTriangle
+ {
+ public static void main(String[] args)
+ {
+Scanner sc = new Scanner(System.in);
+System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
+int r = sc.nextInt();
+int n=0;
+for(int i=0; i<r; i++)
+{
+for(int j=0; j<=i; j++)
+{
+System.out.print(++n+" ");
+}
+System.out.println();
+}
+}
+}
\ No newline at end of file
From b8d98f933708f1b5fa66f875bc5857af80b95e6c Mon Sep 17 00:00:00 2001
From: Ashish Agarwal
Date: Fri, 16 Jun 2017 17:05:39 +0530
Subject: [PATCH 0063/2305] krishnamurthy
---
krishnamurthy.java | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)
create mode 100644 krishnamurthy.java
diff --git a/krishnamurthy.java b/krishnamurthy.java
new file mode 100644
index 000000000000..f8137513dc2b
--- /dev/null
+++ b/krishnamurthy.java
@@ -0,0 +1,29 @@
+import java.util.Scanner;
+class krishnamurthy
+{
+ 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");
+ }
+}
From cc5c1fe62e1684a07de8aa108da41cbf6555537c Mon Sep 17 00:00:00 2001
From: cosmeoes
Date: Tue, 20 Jun 2017 23:13:22 -0600
Subject: [PATCH 0064/2305] Added a few edge cases in the stack class
Added an if statement to:
>The push method to make sure the stack wasn't full.
>The pop method to make sure the stack wasn't empty.
> The peek method to make sure the stack wasn't empty.
---
data_structures/Stacks.java | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/data_structures/Stacks.java b/data_structures/Stacks.java
index dbb2a6217bcf..4e2b08545721 100644
--- a/data_structures/Stacks.java
+++ b/data_structures/Stacks.java
@@ -38,8 +38,12 @@ public Stack(int size){
* @param value The element added
*/
public void push(int value){
- top++;
- stackArray[top] = value;
+ if(!isFull()){ //Checks for a full stack
+ top++;
+ stackArray[top] = value;
+ }else{
+ System.out.prinln("The stack is full, can't insert value");
+ }
}
/**
@@ -48,7 +52,12 @@ public void push(int value){
* @return value popped off the Stack
*/
public int pop(){
- return stackArray[top--];
+ if(!isEmpty()){ //Checks for an empty stack
+ return stackArray[top--];
+ }else{
+ System.out.println("The stack is already empty");
+ return -1;
+ }
}
/**
@@ -57,7 +66,12 @@ public int pop(){
* @return element at the top of the stack
*/
public int peek(){
- return stackArray[top];
+ if(!isEmpty()){ //Checks for an empty stack
+ return stackArray[top];
+ }else{
+ System.out.println("The stack is empty, cant peek");
+ return -1;
+ }
}
/**
From 542f68790dbb1ba3f8493e6cde1a8f6023de9774 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Tue, 27 Jun 2017 12:02:37 +0530
Subject: [PATCH 0065/2305] Create removeDuplicateFromString.java
An algorithm which removes duplicates from a given input string
---
removeDuplicateFromString.java | 45 ++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
create mode 100644 removeDuplicateFromString.java
diff --git a/removeDuplicateFromString.java b/removeDuplicateFromString.java
new file mode 100644
index 000000000000..ce8f3499cede
--- /dev/null
+++ b/removeDuplicateFromString.java
@@ -0,0 +1,45 @@
+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();
+ }
+}
From 71332126303df59385dec83b32753c9df5cc8645 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Wed, 28 Jun 2017 11:01:07 +0530
Subject: [PATCH 0066/2305] Created AnyBaseToDecimal.java
An algorithm which can convert a given number of any base to its decimal value
---
Conversions/AnyBaseToDecimal.java | 59 +++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
create mode 100644 Conversions/AnyBaseToDecimal.java
diff --git a/Conversions/AnyBaseToDecimal.java b/Conversions/AnyBaseToDecimal.java
new file mode 100644
index 000000000000..5e04bcf18218
--- /dev/null
+++ b/Conversions/AnyBaseToDecimal.java
@@ -0,0 +1,59 @@
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
+/**
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
+ *
+ */
+
+// Driver program
+public class AnyBaseToDecimal {
+ public static void main (String[] args) throws Exception{
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+
+ String inp = br.readLine();
+ int base = Integer.parseInt(br.readLine());
+
+ System.out.println("Input in base " + base + " is: " + inp);
+ System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base));
+
+ br.close();
+ }
+
+ /**
+ * This method produces a decimal value of any given input number of any base
+ * @param inp_num String of which we need the decimal value and base in integer format
+ * @return string format of the decimal value
+ */
+
+ public static String convertToDecimal(String inp_num, int base) {
+ int len = inp_num.length();
+ int num = 0;
+ int pow = 1;
+
+ for (int i=len-1; i>=0; i--) {
+ if (valOfChar(inp_num.charAt(i)) >= base) {
+ return "Invalid Number";
+ }
+ num += valOfChar(inp_num.charAt(i))*pow;
+ pow *= base;
+ }
+ return String.valueOf(num);
+ }
+
+ /**
+ * This method produces integer value of the input character and returns it
+ * @param c Char of which we need the integer value of
+ * @return integer value of input char
+ */
+
+ public static int valOfChar(char c) {
+ if (c >= '0' && c <= '9') {
+ return (int)c - '0';
+ }
+ else {
+ return (int)c - 'A' + 10;
+ }
+ }
+}
From aa6f2a75168f59eacd3ababcde6e87df74e9b176 Mon Sep 17 00:00:00 2001
From: Ramshankar Yadhunath
Date: Mon, 3 Jul 2017 20:50:53 +0530
Subject: [PATCH 0067/2305] Inserting and deleting an element in java array
---
insert_delete_in_array.java | 46 +++++++++++++++++++++++++++++++++++++
1 file changed, 46 insertions(+)
create mode 100644 insert_delete_in_array.java
diff --git a/insert_delete_in_array.java b/insert_delete_in_array.java
new file mode 100644
index 000000000000..12bbdc192b1e
--- /dev/null
+++ b/insert_delete_in_array.java
@@ -0,0 +1,46 @@
+import java.util.*;
+public class Array {
+
+ public static void main(String[] args) {
+ Scanner s = new Scanner(System.in); // Input statement
+ System.out.println("Enter the size of the array");
+ int size = s.nextInt();
+ int a[] = new int[size];
+ int i;
+
+ // To enter the initial elements
+ for(i=0;i
Date: Fri, 7 Jul 2017 18:12:14 -0700
Subject: [PATCH 0068/2305] Count character algo added
---
CountChar.java | 42 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
create mode 100644 CountChar.java
diff --git a/CountChar.java b/CountChar.java
new file mode 100644
index 000000000000..dfdc0684d201
--- /dev/null
+++ b/CountChar.java
@@ -0,0 +1,42 @@
+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();
+
+ System.out.println("There are " + CountCharacters(str) + " characters.");
+ }
+
+
+
+ /**
+ * @param str: String to count the characters
+ *
+ * @return int: Number of characters in the passed string
+ * */
+
+ public static int CountCharacters(String str) {
+
+ int count = 0;
+
+ if(str.isEmpty() || str == null)
+ return -1;
+
+ for(int i = 0; i < str.length(); i++)
+ if(!Character.isWhitespace(str.charAt(i)))
+ count++;
+
+ return count;
+ }
+}
From 1af3806a881e20e6b84cb1d7dfd36603029bd154 Mon Sep 17 00:00:00 2001
From: KylerSmith
Date: Fri, 7 Jul 2017 18:24:45 -0700
Subject: [PATCH 0069/2305] Clean up FloydTriangle (ft.java)
---
.DS_Store | Bin 8196 -> 6148 bytes
ft.java | 32 +++++++++++++++-----------------
2 files changed, 15 insertions(+), 17 deletions(-)
diff --git a/.DS_Store b/.DS_Store
index 27875fa6e0825fbffd3779ceb1765c6599a40067..4510cdaa3c92eed37289c2ac12b58a82591e3985 100644
GIT binary patch
delta 139
zcmZp1XfcprU|?W$DortDU=RQ@Ie-{MGjUEV6q~50D9Q$s2aA<3lr!Wr6fvYQ6mKkC
z&dA6%`Hn#S;7em$mUf>j1Thf{ugEy;f8D^won4rY@8i&YSaoB*UrWpmVRiIh;3#3z1!@P@G1m
zU8KX|Vy{ga0VA+TKx+2}S{Pu&n!Q-RkI}RRghKgAn*@8HY5R=yagi9=>Op|$Ln0m+Y6?;oLsqL=4*t8EUY;ajCM$Qos~0$L;ur^b#eH)`
zz0Y%(Ebdp0_Bcdqa)#$T-$G2dMU=AVWySl;SB&$NoPSX>HYLzhN^)A|q}-RgoV?rY
z{R`aQ{|eNE5qNL{>psG+)c*(N-~S&x4+~%fjKJR`;A-uYc8l>{Ne)tLN9
Date: Sat, 8 Jul 2017 20:10:43 -0700
Subject: [PATCH 0070/2305] Create Matrix data structure.
---
.DS_Store | Bin 6148 -> 8196 bytes
data_structures/Matrix/Matrix.java | 197 +++++++++++++++++++++++++++++
2 files changed, 197 insertions(+)
create mode 100644 data_structures/Matrix/Matrix.java
diff --git a/.DS_Store b/.DS_Store
index 4510cdaa3c92eed37289c2ac12b58a82591e3985..f28585d78e4c824a62c4e8ee30d752891efb7b22 100644
GIT binary patch
literal 8196
zcmeHM-A)rh6h6a`Y(oSBCU9l;#>5LkAVdilQDFL7Yiu&g|~_&YAtr{Pb*zNR-;{8qpFFS*R@MrqTSS
z@N=$1WlY~;umGOu4LNj7&Q1{3hP2HM!+>GHFkl!k3>XHk0s}a+xmY>pzItj}!+>Gn
zzhr>-2OE`TQOmxPa_c}NQvk>b+?EA>#czu+q`N++w%8zP`R}Z`|uG+uhAgbnkDj^?H`IcxUb5&SCT9efLA}KYk6N4GGqYj_UVW_Nw}@&(#?{I5MGrFTdWIfjq&y3FHu-YYdE;ci
z=@~H(tdDu@%C=6s(n6Ex(kTA}@45gR0eqjp%Dx^!NOj!vV50`0$m
zNbaF!_&mbf`FKZORUUYV@vKP|8A0Z?o;Mm^o0&J-gN3ub+4~b4LmXN_c^FHK5jD`u
zaLy;fK=db}&vPcpYBE=On%8ufNO6(b5kSS2D&uN2OPv32=YRjdQe!rQF$@?6E|&o@
zQLdCruzB`_Hfx@9Z5#Cvl?&_jm6Q-PG98DM={V&1ABO1LP-RR}%f6DhgYx%31Y}N2
QbN-V#|1UA~`$x|IpZ9>FN&o-=
delta 206
zcmZp1XfcprU|?W$DortDU=RQ@Ie-{MGjUEV6q~50D9Q$s2aA<3lr!Wr6fvYQ6mKkC
z&dA6%`H-Li7vl|}d<9Su`{X}@rmR6gmd0cr5pzzUID-ZdvrhIAv1WAxvSv)aB%;Rg
z9||VBi0be#0@X8u>}31@e`Dc7mc{HG9D>Y1J`f0S0|{4 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 + m3:\n" + m2.plus(m3));
+ System.out.println("m2 - m3:\n" + m2.minus(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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * Checks if the matrix passed is equal to this matrix
+ *
+ * @param other : the other matrix
+ * @return boolean
+ */
+ public boolean equals(Matrix other) {
+ return this == other;
+ }
+
+ /**
+ * Returns the Matrix as a String in the following format
+ *
+ * [ a b c ] ...
+ * [ x y z ] ...
+ * [ i j k ] ...
+ * ...
+ *
+ * @return Matrix as String
+ * TODO: Work formatting for different digit sizes
+ */
+ public String toString() {
+ String str = "";
+
+ for(int i = 0; i < this.data.length; i++) {
+ str += "[ ";
+ for(int j = 0; j < this.data[0].length; j++) {
+ str += data[i][j];
+ str += " ";
+ }
+ str += "]";
+ str += "\n";
+ }
+
+ return str;
+ }
+}
From ae7aba0b4483deff74b623fb229f43008aec0dd3 Mon Sep 17 00:00:00 2001
From: KylerSmith
Date: Sun, 9 Jul 2017 16:29:00 -0700
Subject: [PATCH 0071/2305] File clean-up
---
.DS_Store | Bin 8196 -> 8196 bytes
.../DecimalToOctal.java | 0
CountChar.java => Misc/CountChar.java | 0
Dijkshtra.java => Misc/Dijkshtra.java | 0
Factorial.java => Misc/Factorial.java | 0
FindingPrimes.java => Misc/FindingPrimes.java | 0
ReverseString.java => Misc/ReverseString.java | 0
countwords.java => Misc/countwords.java | 0
ft.java => Misc/ft.java | 0
krishnamurthy.java => Misc/krishnamurthy.java | 0
.../removeDuplicateFromString.java | 0
data_structures/{ => Graphs}/Graphs.java | 0
bfs.java => data_structures/Graphs/bfs.java | 28 +++++++++---------
dfs.java => data_structures/Graphs/dfs.java | 0
.../{ => Lists}/CircleLinkedList.java | 0
.../{ => Lists}/DoublyLinkedList.java | 0
.../{ => Lists}/SinglyLinkedList.java | 0
.../{ => Queues}/PriorityQueues.java | 0
data_structures/{ => Queues}/Queues.java | 0
data_structures/{ => Stacks}/Stacks.java | 0
data_structures/{ => Trees}/AVLTree.java | 0
21 files changed, 14 insertions(+), 14 deletions(-)
rename DecimalToOctal.java => Conversions/DecimalToOctal.java (100%)
rename CountChar.java => Misc/CountChar.java (100%)
rename Dijkshtra.java => Misc/Dijkshtra.java (100%)
rename Factorial.java => Misc/Factorial.java (100%)
rename FindingPrimes.java => Misc/FindingPrimes.java (100%)
rename ReverseString.java => Misc/ReverseString.java (100%)
rename countwords.java => Misc/countwords.java (100%)
rename ft.java => Misc/ft.java (100%)
rename krishnamurthy.java => Misc/krishnamurthy.java (100%)
rename removeDuplicateFromString.java => Misc/removeDuplicateFromString.java (100%)
rename data_structures/{ => Graphs}/Graphs.java (100%)
rename bfs.java => data_structures/Graphs/bfs.java (85%)
rename dfs.java => data_structures/Graphs/dfs.java (100%)
rename data_structures/{ => Lists}/CircleLinkedList.java (100%)
rename data_structures/{ => Lists}/DoublyLinkedList.java (100%)
rename data_structures/{ => Lists}/SinglyLinkedList.java (100%)
rename data_structures/{ => Queues}/PriorityQueues.java (100%)
rename data_structures/{ => Queues}/Queues.java (100%)
rename data_structures/{ => Stacks}/Stacks.java (100%)
rename data_structures/{ => Trees}/AVLTree.java (100%)
diff --git a/.DS_Store b/.DS_Store
index f28585d78e4c824a62c4e8ee30d752891efb7b22..08cfaf755976285dd6706dd9a6835e8362d21b2b 100644
GIT binary patch
delta 869
zcmbVK&ubG=5T4hjW~;{RCfPJp!O$SKG>4Q`1A@3o3mQcdni3KkZL^z~WN~-jc6Za7
z#+V#>5Kq^uA6Z&h;z2Nc_+sv&}T>Wb(TWSrXUE>upq=*(Qq>!k43{*
zglnx9!^~Y;xslq|8vD)1ttYP?k-LcAQ1+5D?W_GC`-N|zt;oBEq!Nh^+La7dvFupv
z8_S}pY1hmtH#2+s%vsMlFU$G-T!7jNSIbEq(*v^mD
zg`S;k5>?F*OR*KA7m9s*8*3@OLa1eLgtXCvtQTi#4k{KRg93nI(S}ZROu@|HEh63>f($G}
z0=tluy6{19PJ`F6!LjFV9@3^k>~*@CY4tK6c%q-!5Uy=OnFvlKSum3M%I@
literal 8196
zcmeHM-A)rh6h6a`Y(oSBCU9l;#>5LkAVdilQDFL7Yiu&g|~_&YAtr{Pb*zNR-;{8qpFFS*R@MrqTSS
z@N=$1WlY~;umGOu4LNj7&Q1{3hP2HM!+>GHFkl!k3>XHk0s}a+xmY>pzItj}!+>Gn
zzhr>-2OE`TQOmxPa_c}NQvk>b+?EA>#czu+q`N++w%8zP`R}Z`|uG+uhAgbnkDj^?H`IcxUb5&SCT9efLA}KYk6N4GGqYj_UVW_Nw}@&(#?{I5MGrFTdWIfjq&y3FHu-YYdE;ci
z=@~H(tdDu@%C=6s(n6Ex(kTA}@45gR0eqjp%Dx^!NOj!vV50`0$m
zNbaF!_&mbf`FKZORUUYV@vKP|8A0Z?o;Mm^o0&J-gN3ub+4~b4LmXN_c^FHK5jD`u
zaLy;fK=db}&vPcpYBE=On%8ufNO6(b5kSS2D&uN2OPv32=YRjdQe!rQF$@?6E|&o@
zQLdCruzB`_Hfx@9Z5#Cvl?&_jm6Q-PG98DM={V&1ABO1LP-RR}%f6DhgYx%31Y}N2
QbN-V#|1UA~`$x|IpZ9>FN&o-=
diff --git a/DecimalToOctal.java b/Conversions/DecimalToOctal.java
similarity index 100%
rename from DecimalToOctal.java
rename to Conversions/DecimalToOctal.java
diff --git a/CountChar.java b/Misc/CountChar.java
similarity index 100%
rename from CountChar.java
rename to Misc/CountChar.java
diff --git a/Dijkshtra.java b/Misc/Dijkshtra.java
similarity index 100%
rename from Dijkshtra.java
rename to Misc/Dijkshtra.java
diff --git a/Factorial.java b/Misc/Factorial.java
similarity index 100%
rename from Factorial.java
rename to Misc/Factorial.java
diff --git a/FindingPrimes.java b/Misc/FindingPrimes.java
similarity index 100%
rename from FindingPrimes.java
rename to Misc/FindingPrimes.java
diff --git a/ReverseString.java b/Misc/ReverseString.java
similarity index 100%
rename from ReverseString.java
rename to Misc/ReverseString.java
diff --git a/countwords.java b/Misc/countwords.java
similarity index 100%
rename from countwords.java
rename to Misc/countwords.java
diff --git a/ft.java b/Misc/ft.java
similarity index 100%
rename from ft.java
rename to Misc/ft.java
diff --git a/krishnamurthy.java b/Misc/krishnamurthy.java
similarity index 100%
rename from krishnamurthy.java
rename to Misc/krishnamurthy.java
diff --git a/removeDuplicateFromString.java b/Misc/removeDuplicateFromString.java
similarity index 100%
rename from removeDuplicateFromString.java
rename to Misc/removeDuplicateFromString.java
diff --git a/data_structures/Graphs.java b/data_structures/Graphs/Graphs.java
similarity index 100%
rename from data_structures/Graphs.java
rename to data_structures/Graphs/Graphs.java
diff --git a/bfs.java b/data_structures/Graphs/bfs.java
similarity index 85%
rename from bfs.java
rename to data_structures/Graphs/bfs.java
index 90ff4eca87ef..4f3bd62d339c 100644
--- a/bfs.java
+++ b/data_structures/Graphs/bfs.java
@@ -2,27 +2,27 @@
/**
* Implementation of a Breadth First Search
- *
+ *
* @author Unknown
*
*/
public class bfs{
-
+
/**
- * The BFS implemented in code to use.
- *
- * @param a Structure to perform the search on
+ * The BFS implemented in code to use.
+ *
+ * @param a Structure to perform the search on a graph, adjacency matrix etc.
* @param vertices The vertices to use
* @param source The Source
*/
public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
- /* code status
+ /* code status
-1 = ready
0 = waiting
1 = processed */
-
+
Stack st = new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
@@ -30,18 +30,18 @@ public static void bfsImplement(byte [][] a,int vertices,int source){ //passing
System.out.println(st.peek());
int pop=st.peek();
b[pop]=(byte)1; //assigning processed status
- st.pop(); //removing head of the queue
+ st.pop(); //removing head of the queue
for(int i=0;i
Date: Sun, 9 Jul 2017 17:11:57 -0700
Subject: [PATCH 0072/2305] Syntax fix
---
data_structures/Stacks/Stacks.class | Bin 0 -> 993 bytes
data_structures/Stacks/Stacks.java | 62 ++++++++++++++--------------
2 files changed, 31 insertions(+), 31 deletions(-)
create mode 100644 data_structures/Stacks/Stacks.class
diff --git a/data_structures/Stacks/Stacks.class b/data_structures/Stacks/Stacks.class
new file mode 100644
index 0000000000000000000000000000000000000000..260579a9d9d0f1ad6341f432d55d1663c37156c5
GIT binary patch
literal 993
zcma)**-sNu6vltI&<-uNR5n*+aiO%83gTJ>2|_|r#iYgrOiTtGaiE*+RKt_cKKtym
z&+t$ZNKA}N6g9>r?thE%+-Zc6^uasHIo~<=yWgF2&dlbY^{2oPV*%RfH0TQ8pO7XfAh6WeXWA
zYvml%vGciF?5M$+AZIxjm2zF(LB)7Ynd+@6yX5@OrT^qg
zitu(*rso!|c}F@HnQ}W?D3|W+Af%T|j+K>;=gUHCtM=2*C$35}9cig$W|N8*S8-=r
zVH7keBa>*0)EIG+EAMBraIilDj!2wvaE-O`CjZdU;TK
zT4MJ})FEDp_eR%HD*_bz#roXjI(`mtP_R%{4|Vdu>IR+}V~x60tf4}EEbLmZ3;kkO
z@izM^7~*3UWYb?ofi2WnAz01r+CnPTt
z1hrH(1hsCVow@D0Zc6F!OzL_rKgbJOc`3EMqLbJ3@`eF6N%EEn-Z9O4X83@~M{e_p
j44=8n7w+?w2Yllp-+9Cj9`lnY{9=XQ(y0#7_i*ShC^XL&
literal 0
HcmV?d00001
diff --git a/data_structures/Stacks/Stacks.java b/data_structures/Stacks/Stacks.java
index 4e2b08545721..2158563173ba 100644
--- a/data_structures/Stacks/Stacks.java
+++ b/data_structures/Stacks/Stacks.java
@@ -3,13 +3,13 @@
/**
* 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
*
*/
@@ -23,7 +23,7 @@ class Stack{
/**
* Constructor
- *
+ *
* @param size Size of the Stack
*/
public Stack(int size){
@@ -34,7 +34,7 @@ public Stack(int size){
/**
* Adds an element to the top of the stack
- *
+ *
* @param value The element added
*/
public void push(int value){
@@ -42,13 +42,13 @@ public void push(int value){
top++;
stackArray[top] = value;
}else{
- System.out.prinln("The stack is full, can't insert value");
+ System.out.println("The stack is full, can't insert value");
}
}
/**
* Removes the top element of the stack and returns the value you've removed
- *
+ *
* @return value popped off the Stack
*/
public int pop(){
@@ -62,7 +62,7 @@ public int pop(){
/**
* Returns the element at the top of the stack
- *
+ *
* @return element at the top of the stack
*/
public int peek(){
@@ -76,7 +76,7 @@ public int peek(){
/**
* Returns true if the stack is empty
- *
+ *
* @return true if the stack is empty
*/
public boolean isEmpty(){
@@ -85,16 +85,16 @@ public boolean isEmpty(){
/**
* 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
@@ -108,41 +108,41 @@ public void makeEmpty(){ //Doesn't delete elements in the array but if you call
/**
* 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;
@@ -151,25 +151,25 @@ int pop(){
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(){
@@ -179,14 +179,14 @@ int peek(){
/**
* 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[]){
@@ -196,21 +196,21 @@ public static void main(String args[]){
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
From 96e89dbaac08cd2db4419fc9364823e81a7b6088 Mon Sep 17 00:00:00 2001
From: KylerSmith
Date: Sun, 9 Jul 2017 17:12:59 -0700
Subject: [PATCH 0073/2305] Remove .class file
---
data_structures/Stacks/Stacks.class | Bin 993 -> 0 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 data_structures/Stacks/Stacks.class
diff --git a/data_structures/Stacks/Stacks.class b/data_structures/Stacks/Stacks.class
deleted file mode 100644
index 260579a9d9d0f1ad6341f432d55d1663c37156c5..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 993
zcma)**-sNu6vltI&<-uNR5n*+aiO%83gTJ>2|_|r#iYgrOiTtGaiE*+RKt_cKKtym
z&+t$ZNKA}N6g9>r?thE%+-Zc6^uasHIo~<=yWgF2&dlbY^{2oPV*%RfH0TQ8pO7XfAh6WeXWA
zYvml%vGciF?5M$+AZIxjm2zF(LB)7Ynd+@6yX5@OrT^qg
zitu(*rso!|c}F@HnQ}W?D3|W+Af%T|j+K>;=gUHCtM=2*C$35}9cig$W|N8*S8-=r
zVH7keBa>*0)EIG+EAMBraIilDj!2wvaE-O`CjZdU;TK
zT4MJ})FEDp_eR%HD*_bz#roXjI(`mtP_R%{4|Vdu>IR+}V~x60tf4}EEbLmZ3;kkO
z@izM^7~*3UWYb?ofi2WnAz01r+CnPTt
z1hrH(1hsCVow@D0Zc6F!OzL_rKgbJOc`3EMqLbJ3@`eF6N%EEn-Z9O4X83@~M{e_p
j44=8n7w+?w2Yllp-+9Cj9`lnY{9=XQ(y0#7_i*ShC^XL&
From 8dcd01ef5f310f509f9b3447b532f137112e2b85 Mon Sep 17 00:00:00 2001
From: KylerSmith
Date: Mon, 10 Jul 2017 07:31:42 -0700
Subject: [PATCH 0074/2305] Added NodeStack.java, another stack implementation
---
data_structures/Stacks/NodeStack.java | 183 ++++++++++++++++++++++++++
1 file changed, 183 insertions(+)
create mode 100644 data_structures/Stacks/NodeStack.java
diff --git a/data_structures/Stacks/NodeStack.java b/data_structures/Stacks/NodeStack.java
new file mode 100644
index 000000000000..c598bb8fcba1
--- /dev/null
+++ b/data_structures/Stacks/NodeStack.java
@@ -0,0 +1,183 @@
+/**
+* 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;
+ }
+}
From 60f6dda70ac929d9daa27a533479c8604e0646ff Mon Sep 17 00:00:00 2001
From: Matheus Serrao
Date: Sun, 16 Jul 2017 04:28:01 -0400
Subject: [PATCH 0075/2305] Simplifies the readability of the static method BS
---
Searches/BinarySearch.java | 49 ++++++++++++++++----------------------
1 file changed, 21 insertions(+), 28 deletions(-)
diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java
index 54f2c4c81d55..e665dadd6a59 100644
--- a/Searches/BinarySearch.java
+++ b/Searches/BinarySearch.java
@@ -17,25 +17,19 @@ class BinarySearch
* @return the location of the key
**/
public static int BS(int array[], int key, int lb, int ub)
- { if (lb>ub)
- {
+ {
+ if ( lb > ub)
return -1;
- }
+
+ int mid = (lb + ub) / 2;
- int mid=(lb+ub)/2;
-
- if (keyarray[mid])
- {
- return (BS(array, key, mid+1, ub));
- }
- else
- {
- return mid;
- }
+
+ if (key > array[mid])
+ return (BS(array, key, mid + 1, ub));
+
+ return mid;
}
@@ -54,22 +48,21 @@ public static void main(String[] args)
//Input
System.out.println("Enter an array of 10 numbers : ");
- for (int i=0; i<10 ;i++ )
- {
- array[i]=input.nextInt();
- }
+
+ for (int i = 0; i < 10 ; i++ )
+ array[i] = input.nextInt();
+
System.out.println("Enter the number to be searched : ");
- key=input.nextInt();
+
+ key = input.nextInt();
int index=BS(array, key, 0, 9);
- if (index!=-1)
- {
- System.out.println("Number found at index number : " + index);
- }
- else
- {
+
+ if (index != -1)
+ System.out.println("Number found at index number : " + index);
+ else
System.out.println("Not found");
- }
+
input.close();
}
}
From 6d3c8464c453b5d5fff1536c2709d77b3d4b60c9 Mon Sep 17 00:00:00 2001
From: earngpi
Date: Sun, 16 Jul 2017 22:14:29 +0700
Subject: [PATCH 0076/2305] create Palindrome.java
---
Misc/Palindrome.java | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
create mode 100644 Misc/Palindrome.java
diff --git a/Misc/Palindrome.java b/Misc/Palindrome.java
new file mode 100644
index 000000000000..6017f0880a61
--- /dev/null
+++ b/Misc/Palindrome.java
@@ -0,0 +1,16 @@
+class Palindrome {
+
+ public 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 isPalindrome(String x){ //*palindrome method, returns true if palindrome
+ return (x.equalsIgnoreCase(reverseString(x)));
+ }
+
+ }
From d6b9e548eff15c3d0e56892f7b2fbf2c25c5c69d Mon Sep 17 00:00:00 2001
From: earngpi
Date: Sun, 16 Jul 2017 22:19:30 +0700
Subject: [PATCH 0077/2305] update singly linked list
---
data_structures/Lists/SinglyLinkedList.java | 30 ++++++++++-----------
1 file changed, 15 insertions(+), 15 deletions(-)
diff --git a/data_structures/Lists/SinglyLinkedList.java b/data_structures/Lists/SinglyLinkedList.java
index 4523739b3a98..c5a4ae08a444 100644
--- a/data_structures/Lists/SinglyLinkedList.java
+++ b/data_structures/Lists/SinglyLinkedList.java
@@ -14,7 +14,7 @@
*/
class SinglyLinkedList{
/**Head refered to the front of the list */
- private LinkForLinkedList head;
+ private Node head;
/**
* Constructor of SinglyLinkedList
@@ -29,9 +29,9 @@ public SinglyLinkedList(){
* @param x Element to be added
*/
public void insertHead(int x){
- LinkForLinkedList newLink = new LinkForLinkedList(x); //Create a new link with a value attached to it
- newLink.next = head; //Set the new link to point to the current head
- head = newLink; //Now set the new link to be the head
+ 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
}
/**
@@ -39,8 +39,8 @@ public void insertHead(int x){
*
* @return The element deleted
*/
- public LinkForLinkedList deleteHead(){
- LinkForLinkedList temp = head;
+ 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;
}
@@ -58,9 +58,9 @@ public boolean isEmpty(){
* Prints contents of the list
*/
public void display(){
- LinkForLinkedList current = head;
+ Node current = head;
while(current!=null){
- current.displayLink();
+ System.out.print(current.getValue()+" ");
current = current.next;
}
System.out.println();
@@ -96,26 +96,26 @@ public static void main(String args[]){
* @author Unknown
*
*/
-class LinkForLinkedList{
+class Node{
/** The value of the node */
public int value;
/** Point to the next node */
- public LinkForLinkedList next; //This is what the link will point to
+ public Node next; //This is what the link will point to
/**
* Constructor
*
* @param valuein Value to be put in the node
*/
- public LinkForLinkedList(int valuein){
+ public Node(int valuein){
value = valuein;
}
/**
- * Prints out the value of the node
+ * Returns value of the node
*/
- public void displayLink(){
- System.out.print(value+" ");
+ public int getValue(){
+ return value;
}
-}
\ No newline at end of file
+}
From fdc48cbc20eaf27d8fa95c9765a112fa6d57d47c Mon Sep 17 00:00:00 2001
From: CalebConner13 <30534014+CalebConner13@users.noreply.github.com>
Date: Wed, 2 Aug 2017 14:10:09 -0400
Subject: [PATCH 0078/2305] Updated syntax / whitespace
---
Misc/CountChar.java | 15 ++++++++-------
1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/Misc/CountChar.java b/Misc/CountChar.java
index dfdc0684d201..1c8dcfea9dd9 100644
--- a/Misc/CountChar.java
+++ b/Misc/CountChar.java
@@ -17,9 +17,7 @@ public static void main(String[] args) {
System.out.println("There are " + CountCharacters(str) + " characters.");
}
-
-
-
+
/**
* @param str: String to count the characters
*
@@ -30,12 +28,15 @@ public static int CountCharacters(String str) {
int count = 0;
- if(str.isEmpty() || str == null)
- return -1;
+ if(str == "" || str == null) //Exceptions
+ {
+ return 0;
+ }
- for(int i = 0; i < str.length(); i++)
- if(!Character.isWhitespace(str.charAt(i)))
+ for(int i = 0; i < str.length(); i++) {
+ if(!Character.isWhitespace(str.charAt(i))) {
count++;
+ }}
return count;
}
From df34c3fdd14d6abeb0208202e0ed114cfbf91fae Mon Sep 17 00:00:00 2001
From: ParitoshAggarwal
Date: Sun, 6 Aug 2017 19:46:08 +0530
Subject: [PATCH 0079/2305] Add files via upload
HashMap implemented
Code is working and checked twice to avoid any errors
---
data_structures/HashMap/HashMap.java | 141 +++++++++++++++++++++++++++
1 file changed, 141 insertions(+)
create mode 100644 data_structures/HashMap/HashMap.java
diff --git a/data_structures/HashMap/HashMap.java b/data_structures/HashMap/HashMap.java
new file mode 100644
index 000000000000..50856d5232d4
--- /dev/null
+++ b/data_structures/HashMap/HashMap.java
@@ -0,0 +1,141 @@
+package hashmap;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+
+public class HashMap {
+ public class hmnodes{ //HashMap nodes
+ K key;
+ V value;
+ }
+
+ private int size=0; //size of hashmap
+ private LinkedList buckets[]; //array of addresses of list
+
+ public HashMap(){
+ buckets=new LinkedList[4]; //initially create bucket of any size
+ for(int i=0;i<4;i++)
+ buckets[i]=new LinkedList<>();
+ }
+
+ public void put(K key,V value) throws Exception{
+ int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
+ int fountAt=find(bi,key); //check if key already exists or not
+ if(fountAt==-1){
+ hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
+ temp.key=key;
+ temp.value=value;
+ buckets[bi].addLast(temp);
+ this.size++;
+ }else{
+ buckets[bi].get(fountAt).value=value;//if already exist modify the value
+ }
+
+ double lambda = (this.size*1.0)/this.buckets.length;
+ if(lambda>2.0){
+ rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
+ }
+
+ return;
+ }
+
+
+ public V get(K key) throws Exception{
+ int bi=bucketIndex(key);
+ int fountAt=find(bi,key);
+ if(fountAt==-1){
+ return null;
+ }else{
+ return buckets[bi].get(fountAt).value;
+ }
+ }
+
+ public V remove(K key) throws Exception{
+ int bi=bucketIndex(key);
+ int fountAt=find(bi,key);
+ if(fountAt==-1){
+ return null;
+ }else{
+ this.size--;
+ return buckets[bi].remove(fountAt).value;
+ }
+ }
+
+ public boolean containskey(K key) throws Exception{
+ int bi=bucketIndex(key);
+ int fountAt=find(bi,key);
+ if(fountAt==-1){
+ return false;
+ }else{
+ return true;
+ }
+ }
+
+ public int size(){
+ return this.size;
+ }
+
+
+ public boolean isempty(){
+ return this.size==0;
+ }
+
+ public ArrayList keyset() throws Exception{
+ ArrayList arr=new ArrayList<>();
+ for(int i=0;i valueset() throws Exception{
+ ArrayList arr=new ArrayList<>();
+ for(int i=0;i"+temp.value+"]");
+ }
+ System.out.println();
+ }
+ }
+
+ public int find(int bi,K key) throws Exception{
+ for(int i=0;i ob[]= buckets;
+ buckets=new LinkedList[ob.length*2];
+ for(int i=0;i();
+
+ size = 0;
+ for(int i=0;i
Date: Sun, 6 Aug 2017 19:58:15 +0530
Subject: [PATCH 0080/2305] Update HashMap.java
---
data_structures/HashMap/HashMap.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/data_structures/HashMap/HashMap.java b/data_structures/HashMap/HashMap.java
index 50856d5232d4..efb55c358d6c 100644
--- a/data_structures/HashMap/HashMap.java
+++ b/data_structures/HashMap/HashMap.java
@@ -1,4 +1,4 @@
-package hashmap;
+
import java.util.ArrayList;
import java.util.LinkedList;
From c993087737f1b7de8714a87700be017bf1d007cf Mon Sep 17 00:00:00 2001
From: ParitoshAggarwal
Date: Sun, 6 Aug 2017 20:32:48 +0530
Subject: [PATCH 0081/2305] Add files via upload
Generic tree updated
---
data_structures/Trees/GenericTree.Java | 226 +++++++++++++++++++++++++
1 file changed, 226 insertions(+)
create mode 100644 data_structures/Trees/GenericTree.Java
diff --git a/data_structures/Trees/GenericTree.Java b/data_structures/Trees/GenericTree.Java
new file mode 100644
index 000000000000..061403c2864b
--- /dev/null
+++ b/data_structures/Trees/GenericTree.Java
@@ -0,0 +1,226 @@
+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);
+ }
+ }
+
From 43bfe47036152dda81b114ac9c00596bd29b9856 Mon Sep 17 00:00:00 2001
From: Rohit Gupta
Date: Tue, 8 Aug 2017 13:23:32 +0530
Subject: [PATCH 0082/2305] Delete .DS_Store
---
.DS_Store | Bin 8196 -> 0 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 .DS_Store
diff --git a/.DS_Store b/.DS_Store
deleted file mode 100644
index 08cfaf755976285dd6706dd9a6835e8362d21b2b..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 8196
zcmeHM%}*0S6n}%LTM=0hgs6vKc5mAXNz(V=X1x7z3e1A%JzeJCu#vow~aP5iz}(
z82$)Bs0J1y!Yng*O@ncQve|8iai1_
z000_hj(P_cTO=;$xhb_pE!~I&?ExtG5P$;=ye4hcpcqgLCc`XflcOb%}h8SA5?!$Zc&}pdbuk(-*cH)L=A4;1vZ!vV$S13NQloN6|fL1SfkKDDd|UxIHlWI|Ett)vuwv&
ziFOouS=&(`biKZ(_H^v++}EXd_w4WP?e6RAJJ8=Z&~xxmUf*9Zt(!%k?~ZZiGC%EB
zXkPCMaQ9^`=1uu@1^3o$NNT`TF%V(}T#R4aEm^Zf|Mh|Hz>n$-HkIaBTHnVf4@0(tcrq>o-
zvq0TRFU`V`m1Z4W1)sSXGFLV&$14t=|Ae~=Q(`c6OxAQ5lokA~uag;%c@%|HvTZPR
zITC7c94XfK7pWne6n%k@K45u^^MAi#MLSWS
zp?28lDd22t&6rnsT{|AX%i;D%4tMkv_qStX=zC9(jWqe&$Krcv?Qgk1j&aejKculL
zf0%(CvWEd4|4+1j|Nr4}R0oOy#lWA-0BO(UGHIM&?GA68Dvz}d%r`Le#PzBYg$WiS
s97h!4IAZ+|L#!L9%572+RwZH!reFUMpzePje*KhyOWprsPyY?YH$tL5-~a#s
From fde8712d79701622f97faae359a7225ba884aca3 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Wed, 9 Aug 2017 11:08:10 +0530
Subject: [PATCH 0083/2305] Create TreeTraversal.java
---
data_structures/Trees/TreeTraversal.java | 92 ++++++++++++++++++++++++
1 file changed, 92 insertions(+)
create mode 100644 data_structures/Trees/TreeTraversal.java
diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java
new file mode 100644
index 000000000000..c4ff92d03baa
--- /dev/null
+++ b/data_structures/Trees/TreeTraversal.java
@@ -0,0 +1,92 @@
+/**
+ *
+ * @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(7);
+
+ // Prints 3 5 7
+ tree.printInOrder();
+ System.out.println();
+
+ // Prints 5 3 7
+ tree.printPreOrder();
+ System.out.println();
+
+ // Prints 3 7 5
+ tree.printPostOrder();
+ 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
+ */
+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 + " ");
+ }
+}
+
From 017f47cf61e17fb7a1526d1d3c258c2c73ec2df7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Harvey=20G=C3=B3mez?=
Date: Wed, 9 Aug 2017 12:59:02 -0600
Subject: [PATCH 0084/2305] HexaDecimal To Binary conversion created
---
Conversions/HexaDecimalToBinary.java | 37 ++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
create mode 100644 Conversions/HexaDecimalToBinary.java
diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java
new file mode 100644
index 000000000000..e43bb1de7861
--- /dev/null
+++ b/Conversions/HexaDecimalToBinary.java
@@ -0,0 +1,37 @@
+import java.lang.StringBuilder;
+import java.util.*;
+import java.util.Scanner;
+import javax.swing.*;
+
+public class HexaToBin {
+
+ private final int LONG_BITS = 8;
+
+ public void convert(String numHex) {
+ //String a HexaDecimal:
+ int conHex = Integer.parseInt(numHex, 16);
+ //Hex a Binary:
+ String binary = Integer.toBinaryString(conHex);
+ //Presentation:
+ System.out.println(numHex + " = " + completeDigits(binary));
+ }
+
+ public String completeDigits(String binNum) {
+ for (int i = binNum.length(); i < LONG_BITS; i++) {
+ binNum = "0" + binNum;
+ }
+ return binNum;
+ }
+
+ public static void main(String[] args) {
+
+ //Testing Numbers:
+ String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB",
+ "19", "01", "02", "03", "04"};
+ Convert objConvert = new Convert();
+
+ for (String num : hexNums) {
+ objConvert.convert(num);
+ }
+ }
+}
\ No newline at end of file
From ee5974a04e5093c32303fafdbecb48b0074d7e5c Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Sun, 13 Aug 2017 12:03:28 -0700
Subject: [PATCH 0085/2305] Updated LinearSearch.java
Converted integer linear search to a generic linear search and added faster input method
---
Searches/LinearSearch.java | 133 +++++++++++++++++++++----------------
1 file changed, 74 insertions(+), 59 deletions(-)
diff --git a/Searches/LinearSearch.java b/Searches/LinearSearch.java
index 0a1bb7cc58cc..6c5322520ac6 100644
--- a/Searches/LinearSearch.java
+++ b/Searches/LinearSearch.java
@@ -1,62 +1,77 @@
-import java.util.Scanner;
+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){
-
- Scanner input = new Scanner(System.in);
- int[] myArray;
- int size = 0;
-
- //Prompt user to create array and its elements
- System.out.print("Enter the array size: ");
- size = input.nextInt();
- myArray = new int[size];
- for (int i = 0; i < size; i++){
- System.out.print("For index " + i + ", enter an integer: ");
- myArray[i] = input.nextInt();
- }
-
- //Prompt user to search for particular element
- System.out.print("Enter integer to search for: ");
- int key = input.nextInt();
-
- //Output array and index of target element, if found
- printarray(myArray);
- System.out.printf("The integer %d is found in index %d\n", key, linearsearch(myArray, key));
-
- input.close();
- }
-
- /**
- * Linear search method
- *
- * @param list List to be searched
- * @param key Key being searched for
- * @return Location of the key
- */
- public static int linearsearch(int[] list, int key){
-
- for (int i = 0; i< list.length; i++){
- if (list[i] == key){
- return i;
- }
-
- } return -1;
- }
- /**
- * Helper Method
- *
- * @param a array to be printed
- */
- public static void printarray(int[] a){
- System.out.print("The array is: ");
- for( int d: a){
- System.out.print(d+" ");
- }
- System.out.println();
- }
+ /**
+ * 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;
+ }
}
From 13bd0365f398bf85291d7c8b671fb03448e525f3 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Sun, 13 Aug 2017 12:37:54 -0700
Subject: [PATCH 0086/2305] Create DecimalToAnyBase.java
A program to convert a decimal number to any given base
---
Conversions/DecimalToAnyBase.java | 65 +++++++++++++++++++++++++++++++
1 file changed, 65 insertions(+)
create mode 100644 Conversions/DecimalToAnyBase.java
diff --git a/Conversions/DecimalToAnyBase.java b/Conversions/DecimalToAnyBase.java
new file mode 100644
index 000000000000..d3927ff8d9e2
--- /dev/null
+++ b/Conversions/DecimalToAnyBase.java
@@ -0,0 +1,65 @@
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+
+/**
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
+ *
+ */
+
+// Driver Program
+public class DecimalToAnyBase {
+ public static void main (String[] args) throws Exception{
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+ System.out.println("Enter the decimal input below: ");
+ int decInput = Integer.parseInt(br.readLine());
+ System.out.println();
+
+ System.out.println("Enter the base below: ");
+ int base = Integer.parseInt(br.readLine());
+ System.out.println();
+
+ System.out.println("Decimal Input" + " is: " + decInput);
+ System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
+
+ br.close();
+ }
+
+ /**
+ * This method produces a String value of any given input decimal in any base
+ * @param inp Decimal of which we need the value in base in String format
+ * @return string format of the converted value in the given base
+ */
+
+ public static String convertToAnyBase(int inp, int base) {
+ ArrayList charArr = new ArrayList<>();
+
+ while (inp > 0) {
+ charArr.add(reVal(inp%base));
+ inp /= base;
+ }
+
+ StringBuilder str = new StringBuilder(charArr.size());
+
+ for(Character ch: charArr)
+ {
+ str.append(ch);
+ }
+
+ return str.reverse().toString();
+ }
+
+ /**
+ * This method produces character value of the input integer and returns it
+ * @param num integer of which we need the character value of
+ * @return character value of input integer
+ */
+
+ public static char reVal(int num) {
+ if (num >= 0 && num <= 9)
+ return (char)(num + '0');
+ else
+ return (char)(num - 10 + 'A');
+ }
+}
From 1e9b5724dfafc69c3daabd02c3e7c3379f52dd60 Mon Sep 17 00:00:00 2001
From: Atishaya Jain
Date: Tue, 15 Aug 2017 23:04:08 +0530
Subject: [PATCH 0087/2305] Added function to insert a node at specified
position in linked list
---
data_structures/Lists/SinglyLinkedList.java | 30 +++++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/data_structures/Lists/SinglyLinkedList.java b/data_structures/Lists/SinglyLinkedList.java
index c5a4ae08a444..32747cf2830f 100644
--- a/data_structures/Lists/SinglyLinkedList.java
+++ b/data_structures/Lists/SinglyLinkedList.java
@@ -34,6 +34,36 @@ public void insertHead(int x){
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
*
From 22350eaf6be3642984d42d4535506fb15664b786 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Thu, 17 Aug 2017 06:57:00 -0700
Subject: [PATCH 0088/2305] Update BinarySearch.java
Converted integer binary search to generic binary search
---
Searches/BinarySearch.java | 123 +++++++++++++++++++------------------
1 file changed, 63 insertions(+), 60 deletions(-)
diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java
index e665dadd6a59..3949f6a86f02 100644
--- a/Searches/BinarySearch.java
+++ b/Searches/BinarySearch.java
@@ -1,68 +1,71 @@
import java.util.Scanner;
/**
- * Implements a Binary Search in Java
*
- * @author unknown
+ * @author Varun Upadhyay (https://github.com/varunu28)
+ *
*/
+
class BinarySearch
{
- /**
- * This method implements the 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 up The upper bound
- * @return the location of the key
- **/
- public static int BS(int array[], int key, int lb, int ub)
- {
- if ( lb > ub)
- return -1;
-
- int mid = (lb + ub) / 2;
-
- if (key < array[mid])
- return (BS(array, key, lb, mid-1));
-
- if (key > array[mid])
- return (BS(array, key, mid + 1, ub));
-
- return mid;
- }
-
-
- /**
- * This is the main method of Binary Search
- *
- * @author Unknown
- * @param args Command line parameters
- */
-
- public static void main(String[] args)
- {
- Scanner input=new Scanner(System.in);
- int array[]=new int[10] ;
- int key;
-
- //Input
- System.out.println("Enter an array of 10 numbers : ");
-
- for (int i = 0; i < 10 ; i++ )
- array[i] = input.nextInt();
-
- System.out.println("Enter the number to be searched : ");
-
- key = input.nextInt();
-
- int index=BS(array, key, 0, 9);
-
- if (index != -1)
- System.out.println("Number found at index number : " + index);
- else
- System.out.println("Not found");
-
- input.close();
- }
+ /**
+ * 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)/2;
+ 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();
+ }
}
From 9f0d7b651844f7b002f33c21e62d0c3a984b05c2 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Sat, 19 Aug 2017 07:41:14 -0700
Subject: [PATCH 0089/2305] Updated BubbleSort.java
Updated BubbleSort.java to its generic version
---
Sorts/BubbleSort.java | 114 +++++++++++++++++++++++-------------------
1 file changed, 63 insertions(+), 51 deletions(-)
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index 1abe69368045..6485010773e3 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -1,58 +1,70 @@
-import java.util.Scanner;
-
/**
- * This class implements BubbleSort
- *
- * @author Unknown
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
*
*/
class BubbleSort
{
- /**
- * Main Method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args)
- {
- int size = 6;
- int array[]=new int[size];
- boolean swap;
- int last = size - 1;
- Scanner input=new Scanner(System.in);
-
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- do
- {
- swap = false;
- for (int count = 0; count < last; count++)
- {
- if (array[count] > array[count + 1])
- {
- int temp = array[count];
- array[count] = array[count + 1];
- array[count + 1] = temp;
- swap = true;
- }
- }
-
- last--;
- } while (swap);
-
- //Output
- for(int i=0; i<6; i++)
- {
- System.out.print(array[i]+"\t");
- }
- input.close();
- }
+ /**
+ * This method implements the Generic Bubble Sort
+ *
+ * @param array The array to make the binary search
+ * @param last The count of total number of elements in array
+ * Sorts the array in increasing order
+ **/
+
+ public static > 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
Date: Sun, 20 Aug 2017 07:48:19 -0700
Subject: [PATCH 0090/2305] Updated Insertion Sort
Updated Insertion Sort to its Generic version
---
Sorts/InsertionSort.java | 104 ++++++++++++++++++++++-----------------
1 file changed, 59 insertions(+), 45 deletions(-)
diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java
index d9d86566354b..ee33a03fd52b 100644
--- a/Sorts/InsertionSort.java
+++ b/Sorts/InsertionSort.java
@@ -1,49 +1,63 @@
-import java.util.Scanner;
-
/**
- * This class implements Insertion Sort
- *
- * @author Unknown
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
*
*/
-class InsertionSort
-{
- /**
- * Main Method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args)
- {
- int array[]=new int[6];
- Scanner input=new Scanner(System.in);
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- for(int i=0; i<6; i++)
- {
- int temp=array[i];
- int j=i-1;
- while(j>=0 && temp> 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
Date: Sun, 20 Aug 2017 07:50:29 -0700
Subject: [PATCH 0091/2305] Update InsertionSort.java
---
Sorts/InsertionSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java
index ee33a03fd52b..c77b895f7a9d 100644
--- a/Sorts/InsertionSort.java
+++ b/Sorts/InsertionSort.java
@@ -9,7 +9,7 @@ class InsertionSort {
/**
* This method implements the Generic Insertion Sort
*
- * @param array The array to make the binary search
+ * @param array The array to be sorted
* @param last The count of total number of elements in array
* Sorts the array in increasing order
**/
From 96af9a7d63eee7fa978d24ac941193ff9136ab6b Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Sun, 20 Aug 2017 07:51:16 -0700
Subject: [PATCH 0092/2305] Update BubbleSort.java
Changed the method description
---
Sorts/BubbleSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index 6485010773e3..93364369a517 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -9,7 +9,7 @@ class BubbleSort
/**
* This method implements the Generic Bubble Sort
*
- * @param array The array to make the binary search
+ * @param array The array to be sorted
* @param last The count of total number of elements in array
* Sorts the array in increasing order
**/
From 07d5d9ea6dafaa5885960d9421136d08b0706ca1 Mon Sep 17 00:00:00 2001
From: Joseph M Pignataro
Date: Mon, 21 Aug 2017 13:35:38 -0400
Subject: [PATCH 0093/2305] Create Node.java
A node class to be used for the binary tree sorting algorithm. I will put up the sorting algorithm ASAP.
---
Misc/Node.java | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
create mode 100644 Misc/Node.java
diff --git a/Misc/Node.java b/Misc/Node.java
new file mode 100644
index 000000000000..ab495b77de01
--- /dev/null
+++ b/Misc/Node.java
@@ -0,0 +1,16 @@
+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;
+ }
+}
From f16117e1092f4a8f2c10698772991d3480a2d774 Mon Sep 17 00:00:00 2001
From: Joseph M Pignataro
Date: Mon, 21 Aug 2017 13:51:57 -0400
Subject: [PATCH 0094/2305] Tree search
Uses Node class in misc.
---
Sorts/BinaryTreeSearch.java | 80 +++++++++++++++++++++++++++++++++++++
1 file changed, 80 insertions(+)
create mode 100644 Sorts/BinaryTreeSearch.java
diff --git a/Sorts/BinaryTreeSearch.java b/Sorts/BinaryTreeSearch.java
new file mode 100644
index 000000000000..e6a80f62abdc
--- /dev/null
+++ b/Sorts/BinaryTreeSearch.java
@@ -0,0 +1,80 @@
+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
Date: Mon, 21 Aug 2017 13:53:15 -0400
Subject: [PATCH 0095/2305] Delete BinaryTreeSearch.java
Wrong title
---
Sorts/BinaryTreeSearch.java | 80 -------------------------------------
1 file changed, 80 deletions(-)
delete mode 100644 Sorts/BinaryTreeSearch.java
diff --git a/Sorts/BinaryTreeSearch.java b/Sorts/BinaryTreeSearch.java
deleted file mode 100644
index e6a80f62abdc..000000000000
--- a/Sorts/BinaryTreeSearch.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
Date: Mon, 21 Aug 2017 13:54:34 -0400
Subject: [PATCH 0096/2305] Remake of TreeSort
Uses Node class in misc files. Remade after a typo in the last file.
---
Sorts/BinaryTreeSort.java | 80 +++++++++++++++++++++++++++++++++++++++
1 file changed, 80 insertions(+)
create mode 100644 Sorts/BinaryTreeSort.java
diff --git a/Sorts/BinaryTreeSort.java b/Sorts/BinaryTreeSort.java
new file mode 100644
index 000000000000..e6a80f62abdc
--- /dev/null
+++ b/Sorts/BinaryTreeSort.java
@@ -0,0 +1,80 @@
+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
Date: Mon, 21 Aug 2017 11:20:04 -0700
Subject: [PATCH 0097/2305] Updated QuickSort.java
Updated quicksort to its generic version and changed the filename according to convention
---
Sorts/QuickSort.java | 93 +++++++++++++++++++++++++++++++++++++++
Sorts/Quicksort.java | 102 -------------------------------------------
2 files changed, 93 insertions(+), 102 deletions(-)
create mode 100644 Sorts/QuickSort.java
delete mode 100644 Sorts/Quicksort.java
diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java
new file mode 100644
index 000000000000..ec05938fa2c9
--- /dev/null
+++ b/Sorts/QuickSort.java
@@ -0,0 +1,93 @@
+/**
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
+ *
+ */
+
+class QuickSort {
+
+ /**
+ * This method implements the Generic Quick Sort
+ *
+ * @param array The array to be sorted
+ * @param start The first index of an array
+ * @param end The last index of an array
+ * Sorts the array in increasing order
+ **/
+
+ public static > void QS(T array[], int start, int end) {
+ if (start < end) {
+ int PIndex = partition(array, start, end);
+ QS(array, start, PIndex - 1);
+ QS(array, PIndex + 1, end);
+ }
+ }
+
+ /**
+ * 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(T array[], int start, int end) {
+ T pivot = array[end];
+ int PIndex = start;
+ for (int i=start;i> void swap(T[] array, int initial, int fin) {
+ T temp = array[initial];
+ array[initial] = array[fin];
+ array[fin] = temp;
+ }
+
+ // Driver Program
+ public static void main(String[] args) {
+
+ // For integer input
+ int[] arr = {3,4,1,32,0,2,44,111,5};
+ Integer[] array = new Integer[arr.length];
+ for (int i=0;i 0 1 2 3 4 5 32 44 111
+ for (int i=0;i a b c d e
+ for(int i=0; i= 1){
- int pivot = ar[end];
- while (i< j){
- while (ar[i]=pivot && j>start){
- j--;
- }
- if (i
Date: Fri, 25 Aug 2017 11:43:44 -0700
Subject: [PATCH 0098/2305] Updated MergeSort.java
Updated MergeSort into its generic form
---
Sorts/MergeSort.java | 155 ++++++++++++++++++++-----------------------
1 file changed, 73 insertions(+), 82 deletions(-)
diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java
index f574281d65c0..b53451af806b 100644
--- a/Sorts/MergeSort.java
+++ b/Sorts/MergeSort.java
@@ -1,109 +1,100 @@
-import java.util.Scanner;
-
/**
- * This class implements MergeSort
- * @author Unknown
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
*
*/
-public class MergeSort {
- /** Array for mergeSort*/
- private int[] array;
- /** Temp Merge Array*/
- private int[] tempMergArr;
- /** Length of the array*/
- private int length;
- /**
- * Sorts inputArr with merge sort algorithm
- *
- * @param inputArr Array to be sorted
- */
- public final void sort(int inputArr[]) {
- this.array = inputArr;
- this.length = inputArr.length;
- this.tempMergArr = new int[this.length];
- this.mergeSort(0, this.length - 1);
- }
+class MergeSort {
/**
- * Partitions Array into recursively smaller pieces
+ * This method implements the Generic Merge Sort
*
- * @param lowerIndex lower bound to include in the first partition
- * @param higherIndex upper bound to include in the third partition
- */
- private void mergeSort(int lowerIndex, int higherIndex) {
- if (lowerIndex < higherIndex) {
- int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
- // Below step sorts the left side of the array
- this.mergeSort(lowerIndex, middle);
- // Below step sorts the right side of the array
- this.mergeSort(middle + 1, higherIndex);
- // Now merge both sides
- this.mergeParts(lowerIndex, middle, higherIndex);
+ * @param arr The array to be sorted
+ * @param temp The copy of the actual array
+ * @param left The first index of the array
+ * @param right The last index of the array
+ * Recursively sorts the array in increasing order
+ **/
+
+ public static > 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);
}
+
}
/**
- * Merges partitions
+ * This method implements the merge step of the merge sort
*
- * @param lowerIndex The lower index
- * @param middle The middle index
- * @param higherIndex The higher index
- */
- private void mergeParts(int lowerIndex, int middle, int higherIndex) {
- for (int i = lowerIndex; i <= higherIndex; i++) {
- this.tempMergArr[i] = this.array[i];
+ * @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 = lowerIndex;
- int j = middle + 1;
- int k = lowerIndex;
- while (i <= middle && j <= higherIndex) {
- if (this.tempMergArr[i] <= this.tempMergArr[j]) {
- this.array[k] = this.tempMergArr[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 {
- this.array[k] = this.tempMergArr[j];
+ }
+ else {
+ arr[k] = temp[j];
j++;
}
k++;
}
- while (i <= middle) {
- this.array[k] = this.tempMergArr[i];
- k++;
+
+ while (i <= mid) {
+ arr[k] = temp[i];
i++;
+ k++;
}
-
}
- /**
- * 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();
+ // 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
Date: Tue, 29 Aug 2017 19:42:53 +0530
Subject: [PATCH 0099/2305] Add files via upload
---
max_sub_array.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
create mode 100644 max_sub_array.py
diff --git a/max_sub_array.py b/max_sub_array.py
new file mode 100644
index 000000000000..653bb66e0896
--- /dev/null
+++ b/max_sub_array.py
@@ -0,0 +1,59 @@
+"""
+author : Mayank Kumar Jha (mk9440)
+"""
+
+import time
+import matplotlib.pyplot as plt
+from random import randint
+def find_max_sub_array(A,low,high):
+ if low==high:
+ return low,high,A[low]
+ else :
+ mid=(low+high)//2
+ left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
+ right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
+ cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
+ if left_sum>=right_sum and left_sum>=cross_sum:
+ return left_low,left_high,left_sum
+ elif right_sum>=left_sum and right_sum>=cross_sum :
+ return right_low,right_high,right_sum
+ else:
+ return cross_left,cross_right,cross_sum
+
+def find_max_cross_sum(A,low,mid,high):
+ left_sum,max_left=-999999999,-1
+ right_sum,max_right=-999999999,-1
+ summ=0
+ for i in range(mid,low-1,-1):
+ summ+=A[i]
+ if summ > left_sum:
+ left_sum=summ
+ max_left=i
+ summ=0
+ for i in range(mid+1,high+1):
+ summ+=A[i]
+ if summ > right_sum:
+ right_sum=summ
+ max_right=i
+ return max_left,max_right,(left_sum+right_sum)
+
+
+if __name__=='__main__':
+ inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
+ tim=[]
+ for i in inputs:
+ li=[randint(1,i) for j in range(i)]
+ strt=time.time()
+ (find_max_sub_array(li,0,len(li)-1))
+ end=time.time()
+ tim.append(end-strt)
+ print("No of Inputs Time Taken")
+ for i in range(len(inputs)):
+ print(inputs[i],'\t\t',tim[i])
+ plt.plot(inputs,tim)
+ plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
+ plt.show()
+
+
+
+
From 86f5fd28c2ce79e73c3d66ea33b2fdbe93595b39 Mon Sep 17 00:00:00 2001
From: Mayank Kumar Jha
Date: Tue, 29 Aug 2017 19:43:25 +0530
Subject: [PATCH 0100/2305] Delete max_sub_array.py
---
max_sub_array.py | 59 ------------------------------------------------
1 file changed, 59 deletions(-)
delete mode 100644 max_sub_array.py
diff --git a/max_sub_array.py b/max_sub_array.py
deleted file mode 100644
index 653bb66e0896..000000000000
--- a/max_sub_array.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""
-author : Mayank Kumar Jha (mk9440)
-"""
-
-import time
-import matplotlib.pyplot as plt
-from random import randint
-def find_max_sub_array(A,low,high):
- if low==high:
- return low,high,A[low]
- else :
- mid=(low+high)//2
- left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
- right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
- cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
- if left_sum>=right_sum and left_sum>=cross_sum:
- return left_low,left_high,left_sum
- elif right_sum>=left_sum and right_sum>=cross_sum :
- return right_low,right_high,right_sum
- else:
- return cross_left,cross_right,cross_sum
-
-def find_max_cross_sum(A,low,mid,high):
- left_sum,max_left=-999999999,-1
- right_sum,max_right=-999999999,-1
- summ=0
- for i in range(mid,low-1,-1):
- summ+=A[i]
- if summ > left_sum:
- left_sum=summ
- max_left=i
- summ=0
- for i in range(mid+1,high+1):
- summ+=A[i]
- if summ > right_sum:
- right_sum=summ
- max_right=i
- return max_left,max_right,(left_sum+right_sum)
-
-
-if __name__=='__main__':
- inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
- tim=[]
- for i in inputs:
- li=[randint(1,i) for j in range(i)]
- strt=time.time()
- (find_max_sub_array(li,0,len(li)-1))
- end=time.time()
- tim.append(end-strt)
- print("No of Inputs Time Taken")
- for i in range(len(inputs)):
- print(inputs[i],'\t\t',tim[i])
- plt.plot(inputs,tim)
- plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
- plt.show()
-
-
-
-
From 0d4cfbabe6786dd5b0ec8de05c9a864f648d85e7 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Mon, 4 Sep 2017 14:08:12 -0700
Subject: [PATCH 0101/2305] Added Fibanacci using memoization
---
Dynamic Programming/Fibonacci.java | 49 ++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)
create mode 100644 Dynamic Programming/Fibonacci.java
diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java
new file mode 100644
index 000000000000..844beabb4299
--- /dev/null
+++ b/Dynamic Programming/Fibonacci.java
@@ -0,0 +1,49 @@
+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 {
+
+ public 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(fib(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
+ **/
+
+ public static int fib(int n) {
+ if (map.containsKey(n)) {
+ return map.get(n);
+ }
+
+ int f;
+
+ if (n <= 2) {
+ f = 1;
+ }
+ else {
+ f = fib(n-1) + fib(n-2);
+ map.put(n,f);
+ }
+
+ return f;
+ }
+}
+
From 73e05940eae0a46fa4921ef1ecfb81fab4f91a76 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Mon, 4 Sep 2017 14:40:12 -0700
Subject: [PATCH 0102/2305] Added bottom up approach
---
Dynamic Programming/Fibonacci.java | 30 ++++++++++++++++++++++++++++--
1 file changed, 28 insertions(+), 2 deletions(-)
diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java
index 844beabb4299..72048153de74 100644
--- a/Dynamic Programming/Fibonacci.java
+++ b/Dynamic Programming/Fibonacci.java
@@ -18,7 +18,8 @@ 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(fib(n)); // Returns 8 for n = 6
+ System.out.println(fibMemo(n)); // Returns 8 for n = 6
+ System.out.println(fibBotUp(n)); // Returns 8 for n = 6
}
/**
@@ -28,7 +29,7 @@ public static void main(String[] args) throws Exception {
* Outputs the nth fibonacci number
**/
- public static int fib(int n) {
+ public static int fibMemo(int n) {
if (map.containsKey(n)) {
return map.get(n);
}
@@ -45,5 +46,30 @@ public static int fib(int n) {
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
+ **/
+
+ public static int fibBotUp(int n) {
+
+ Map fib = new HashMap();
+
+ for (int i=1;i
Date: Thu, 7 Sep 2017 19:11:35 -0700
Subject: [PATCH 0103/2305] Updated SelectionSort.java
Updated SelectionSort.java to its generic version
---
Sorts/SelectionSort.java | 116 +++++++++++++++++++++++----------------
1 file changed, 68 insertions(+), 48 deletions(-)
diff --git a/Sorts/SelectionSort.java b/Sorts/SelectionSort.java
index 955e7d65b9f7..21fa71514cc6 100644
--- a/Sorts/SelectionSort.java
+++ b/Sorts/SelectionSort.java
@@ -1,53 +1,73 @@
-import java.util.Scanner;
-
/**
- * This class implements Selection Sort
- *
- * @author Unknown
+ *
+ * @author Varun Upadhyay (https://github.com/varunu28)
*
*/
-class SelectionSort
-{
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args)
- {
- int array[]=new int[6];
- Scanner input=new Scanner(System.in);
-
- //Input
- System.out.println("Enter any 6 Numbers for Unsorted Array : ");
- for(int i=0; i<6; i++)
- {
- array[i]=input.nextInt();
- }
-
- //Sorting
- for(int i=0; i<6; i++)
- {
- int min=i;
- for(int j=i+1; j<6; j++)
- {
- if(array[j]> 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
Date: Fri, 22 Sep 2017 01:21:56 +0530
Subject: [PATCH 0104/2305] Add files via upload
Huffman Encoding with Proper comments
---
Huffman.java | 158 +++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 158 insertions(+)
create mode 100644 Huffman.java
diff --git a/Huffman.java b/Huffman.java
new file mode 100644
index 000000000000..b93b7e7c082a
--- /dev/null
+++ b/Huffman.java
@@ -0,0 +1,158 @@
+
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Scanner;
+import java.util.Stack;
+/**
+ *
+ * @author Mayank Kumar (mk9440)
+ */
+/*
+Output :
+
+Enter number of distinct letters
+6
+Enter letters with its frequncy to encode
+Enter letter : a
+Enter frequncy : 45
+
+Enter letter : b
+Enter frequncy : 13
+
+Enter letter : c
+Enter frequncy : 12
+
+Enter letter : d
+Enter frequncy : 16
+
+Enter letter : e
+Enter frequncy : 9
+
+Enter letter : f
+Enter frequncy : 5
+
+Letter Encoded Form
+a 0
+b 1 0 1
+c 1 0 0
+d 1 1 1
+e 1 1 0 1
+f 1 1 0 0
+
+*/
+
+class Node{
+String letr="";
+int freq=0,data=0;
+Node left=null,right=null;
+}
+
+//A comparator class to sort list on the basis of their frequency
+class comp implements Comparator{
+ @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
Date: Thu, 28 Sep 2017 10:15:39 -0500
Subject: [PATCH 0105/2305] add adjacency list implementation for graphs
---
data_structures/Graphs/Graphs.java | 136 ++++++++++++++++++++++++-----
data_structures/Graphs/makefile | 3 +
2 files changed, 116 insertions(+), 23 deletions(-)
create mode 100644 data_structures/Graphs/makefile
diff --git a/data_structures/Graphs/Graphs.java b/data_structures/Graphs/Graphs.java
index a3eb0ff6b8ba..aa964f7e1205 100644
--- a/data_structures/Graphs/Graphs.java
+++ b/data_structures/Graphs/Graphs.java
@@ -1,32 +1,122 @@
+import java.util.ArrayList;
+import java.lang.StringBuilder;
-/**
- * This class implements the Graph data structure
- * using the classes Graph and Graphs.
- *
- * @author Zachary Jones
- *
- */
-class Graph {
+class AdjacencyListGraph> {
-}
+ ArrayList verticies;
+
+ public AdjacencyListGraph() {
+ verticies = new ArrayList<>();
+ }
+
+ private class Vertex {
+ E data;
+ ArrayList adjacentVerticies;
+
+ public Vertex(E data) {
+ adjacentVerticies = new ArrayList<>();
+ this.data = data;
+ }
-/**
- * This class is used to test the Graph
- * class above.
- *
- * @author Zachary Jones
- *
- */
+ public boolean addAdjacentVertex(Vertex to) {
+ for (Vertex v: adjacentVerticies) {
+ if (v.data.compareTo(to.data) == 0) {
+ return false; // the edge already exists
+ }
+ }
+ return adjacentVerticies.add(to); // this will return true;
+ }
+
+ public boolean removeAdjacentVertex(E to) {
+ // use indexes here so it is possible to
+ // remove easily without implementing
+ // equals method that ArrayList.remove(Object o) uses
+ for (int i = 0; i < adjacentVerticies.size(); i++) {
+ if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
+ adjacentVerticies.remove(i);
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ /**
+ * @param from the data of the vertex the edge is from
+ * @param to the data of the vertex the edge is going to
+ * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
+ */
+ public boolean removeEdge(E from, E to) {
+ Vertex fromV = null;
+ for (Vertex v: verticies) {
+ if (from.compareTo(v.data) == 0) {
+ fromV = v;
+ break;
+ }
+ }
+ if (fromV == null) return false;
+ return fromV.removeAdjacentVertex(to);
+ }
+ /**
+ * @param from the data of the vertex the edge is from
+ * @param to the data of the vertex the edge is going to
+ * @return returns true if the edge did not exist, return false if it already did
+ */
+ public boolean addEdge(E from, E to) {
+ Vertex fromV = null, toV = null;
+ for (Vertex v: verticies) {
+ if (from.compareTo(v.data) == 0) { // see if from vertex already exists
+ fromV = v;
+ } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
+ toV = v;
+ }
+ if (fromV != null && toV != null) break; // both nodes exist so stop searching
+ }
+ if (fromV == null) {
+ fromV = new Vertex(from);
+ verticies.add(fromV);
+ }
+ if (toV == null) {
+ toV = new Vertex(to);
+ verticies.add(toV);
+ }
+ return fromV.addAdjacentVertex(toV);
+ }
+
+ /**
+ *
+ * @return returns a string describing this graph
+ */
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ for (Vertex v: verticies) {
+ sb.append("Vertex: ");
+ sb.append(v.data);
+ sb.append("\n");
+ sb.append("Adjacent verticies: ");
+ for (Vertex v2: v.adjacentVerticies) {
+ sb.append(v2.data);
+ sb.append(" ");
+ }
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+}
public class Graphs {
- /**
- * Main method
- *
- * @param args Command line arguments
- */
public static void main(String args[]) {
-
- }
+ AdjacencyListGraph graph = new AdjacencyListGraph<>();
+ assert graph.addEdge(1, 2);
+ assert graph.addEdge(1, 5);
+ assert graph.addEdge(2, 5);
+ assert !graph.addEdge(1, 2);
+ assert graph.addEdge(2, 3);
+ assert graph.addEdge(3, 4);
+ assert graph.addEdge(4, 1);
+ assert !graph.addEdge(2, 3);
+ System.out.println(graph);
+ }
}
diff --git a/data_structures/Graphs/makefile b/data_structures/Graphs/makefile
new file mode 100644
index 000000000000..7361b405c487
--- /dev/null
+++ b/data_structures/Graphs/makefile
@@ -0,0 +1,3 @@
+test:
+ javac Graphs.java
+ java -ea Graphs
From 9b566f94416a1f3c555a934ee6e1f2574beae1f6 Mon Sep 17 00:00:00 2001
From: rei2hu
Date: Thu, 28 Sep 2017 10:40:18 -0500
Subject: [PATCH 0106/2305] remove makefile and update docs
---
data_structures/Graphs/Graphs.java | 7 +++++++
data_structures/Graphs/makefile | 3 ---
2 files changed, 7 insertions(+), 3 deletions(-)
delete mode 100644 data_structures/Graphs/makefile
diff --git a/data_structures/Graphs/Graphs.java b/data_structures/Graphs/Graphs.java
index aa964f7e1205..2e5db70866e3 100644
--- a/data_structures/Graphs/Graphs.java
+++ b/data_structures/Graphs/Graphs.java
@@ -42,6 +42,9 @@ public boolean removeAdjacentVertex(E to) {
}
/**
+ * this method removes an edge from the graph between two specified
+ * verticies
+ *
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
@@ -58,6 +61,9 @@ public boolean removeEdge(E from, E to) {
return fromV.removeAdjacentVertex(to);
}
/**
+ * this method adds an edge to the graph between two specified
+ * verticies
+ *
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
@@ -84,6 +90,7 @@ public boolean addEdge(E from, E to) {
}
/**
+ * this gives a list of verticies in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
diff --git a/data_structures/Graphs/makefile b/data_structures/Graphs/makefile
deleted file mode 100644
index 7361b405c487..000000000000
--- a/data_structures/Graphs/makefile
+++ /dev/null
@@ -1,3 +0,0 @@
-test:
- javac Graphs.java
- java -ea Graphs
From f7f70b575bee5d01ecc5ca1b1541b31146776053 Mon Sep 17 00:00:00 2001
From: Dusan Punosevac
Date: Thu, 28 Sep 2017 18:33:36 +0200
Subject: [PATCH 0107/2305] Added Shell Sort
---
Sorts/ShellSort.java | 68 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
create mode 100644 Sorts/ShellSort.java
diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java
new file mode 100644
index 000000000000..3a777c2cd797
--- /dev/null
+++ b/Sorts/ShellSort.java
@@ -0,0 +1,68 @@
+package Sorts;
+
+/**
+ * @author dpunosevac
+ */
+public class ShellSort {
+
+ /**
+ * This method implements Generic Shell Sort.
+ * @param array The array to be sorted
+ */
+ public static void shellSort(Comparable[] array) {
+ int N = array.length;
+ int h = 1;
+
+ while (h < N/3) {
+ h = 3 * h + 1;
+ }
+
+ while (h >= 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
Date: Fri, 29 Sep 2017 00:43:08 +0800
Subject: [PATCH 0108/2305] added levenshtein distance dp implementation
---
Dynamic Programming/Levenshtein_distance.java | 55 +++++++++++++++++++
1 file changed, 55 insertions(+)
create mode 100644 Dynamic Programming/Levenshtein_distance.java
diff --git a/Dynamic Programming/Levenshtein_distance.java b/Dynamic Programming/Levenshtein_distance.java
new file mode 100644
index 000000000000..5bff389fbebf
--- /dev/null
+++ b/Dynamic Programming/Levenshtein_distance.java
@@ -0,0 +1,55 @@
+/**
+ *
+ * @author Kshitij VERMA (github.com/kv19971)
+ * LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
+ *
+ *
+ */
+
+public class Levenshtein_distance{
+ private int minimum(int a, int b, int c){
+ if(a < b && a < c){
+ return a;
+ }else if(b < a && b < c){
+ return b;
+ }else{
+ return c;
+ }
+ }
+ public int calculate_distance(String a, String b){
+ len_a = a.length() + 1;
+ len_b = b.length() + 1;
+ int [][] distance_mat = new int[len_a][len_b];
+ for(int i = 0; i < len_a; i++){
+ distance_mat[i][0] = i;
+ }
+ for(int j = 0; j < len_b; j++){
+ distance_mat[0][j] = j;
+ }
+ for(int i = 0; i < len_a; i++){
+ for(int j = 0; i < len_b; j++){
+ int cost;
+ if (a.charAt(i) == b.charAt(j)){
+ cost = 0;
+ }else{
+ cost = 1;
+ }
+ distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost;
+
+
+ }
+
+ }
+ return distance_mat[len_a-1][len_b-1];
+
+ }
+ public static void main(String [] args){
+ String a = ""; // enter your string here
+ String b = ""; // enter your string here
+
+ System.out.print("Levenshtein distance between "+a + " and "+b+ " is: ");
+ System.out.println(calculate_distance(a,b));
+
+
+ }
+}
From 1e52ba37c31c7af29e2c36e6b93193f052ca9da6 Mon Sep 17 00:00:00 2001
From: Miki Pokryvailo
Date: Thu, 28 Sep 2017 14:11:35 -0400
Subject: [PATCH 0109/2305] Added level order traversal, and more nodes in main
method
---
data_structures/Trees/TreeTraversal.java | 36 ++++++++++++++++++++----
1 file changed, 30 insertions(+), 6 deletions(-)
diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java
index c4ff92d03baa..8e73134e17d9 100644
--- a/data_structures/Trees/TreeTraversal.java
+++ b/data_structures/Trees/TreeTraversal.java
@@ -1,3 +1,5 @@
+import java.util.LinkedList;
+
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
@@ -9,19 +11,27 @@ 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 3 5 7
- tree.printInOrder();
+ System.out.println("Pre order traversal:");
+ tree.printPreOrder();
System.out.println();
- // Prints 5 3 7
- tree.printPreOrder();
+ System.out.println("In order traversal:");
+ tree.printInOrder();
System.out.println();
- // Prints 3 7 5
+ System.out.println("Post order traversal:");
tree.printPostOrder();
System.out.println();
+
+ System.out.println("Level order traversal:");
+ tree.printLevelOrder();
+ System.out.println();
}
}
@@ -88,5 +98,19 @@ public void printPostOrder() {
}
System.out.print(data + " ");
}
-}
+ public void printLevelOrder() {
+ LinkedList queue = new LinkedList<>();
+ queue.add(this);
+ while (queue.size() > 0) {
+ Node head = queue.remove();
+ System.out.print(head.data + " ");
+ if (head.left != null) {
+ queue.add(head.left);
+ }
+ if (head.right != null) {
+ queue.add(head.right);
+ }
+ }
+ }
+}
From 701d5d1855d9e371e718ea7442f34b688332e7c9 Mon Sep 17 00:00:00 2001
From: Varun Upadhyay
Date: Thu, 28 Sep 2017 11:38:20 -0700
Subject: [PATCH 0110/2305] Added SieveOfEratosthenes.java
---
Others/SieveOfEratosthenes.java | 49 +++++++++++++++++++++++++++++++++
1 file changed, 49 insertions(+)
create mode 100644 Others/SieveOfEratosthenes.java
diff --git a/Others/SieveOfEratosthenes.java b/Others/SieveOfEratosthenes.java
new file mode 100644
index 000000000000..4b6fd5b78491
--- /dev/null
+++ b/Others/SieveOfEratosthenes.java
@@ -0,0 +1,49 @@
+/**
+ *
+ * @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
Date: Thu, 28 Sep 2017 21:29:36 +0100
Subject: [PATCH 0111/2305] added interpolationSearch.java
---
Searches/interpolationSearch.java | 53 +++++++++++++++++++++++++++++++
1 file changed, 53 insertions(+)
create mode 100644 Searches/interpolationSearch.java
diff --git a/Searches/interpolationSearch.java b/Searches/interpolationSearch.java
new file mode 100644
index 000000000000..b8041ae6cf16
--- /dev/null
+++ b/Searches/interpolationSearch.java
@@ -0,0 +1,53 @@
+
+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.");
+ }
+}
+
From e416be63bb7d684d4bb9d6e443addbf33c3d4b69 Mon Sep 17 00:00:00 2001
From: Oskar Enmalm
Date: Fri, 29 Sep 2017 00:49:28 +0200
Subject: [PATCH 0112/2305] Create Abecedarian.java
---
Misc/Abecedarian.java | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 Misc/Abecedarian.java
diff --git a/Misc/Abecedarian.java b/Misc/Abecedarian.java
new file mode 100644
index 000000000000..8e4a179325e8
--- /dev/null
+++ b/Misc/Abecedarian.java
@@ -0,0 +1,21 @@
+//Oskar Enmalm 29/9/17
+//An Abecadrian is a word where each letter is in alphabetical order
+
+class Abecedarian{
+
+ public static boolean isAbecedarian(String s){
+ int index = s.length() - 1;
+
+ for(int i =0; i
Date: Fri, 29 Sep 2017 01:04:24 +0200
Subject: [PATCH 0113/2305] Update Abecedarian.java
Removed unnecessary println and compacted it
---
Misc/Abecedarian.java | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
diff --git a/Misc/Abecedarian.java b/Misc/Abecedarian.java
index 8e4a179325e8..6507411b4dec 100644
--- a/Misc/Abecedarian.java
+++ b/Misc/Abecedarian.java
@@ -10,12 +10,8 @@ public static boolean isAbecedarian(String s){
if(s.charAt(i)<=s.charAt(i + 1)){} //Need to check if each letter for the whole word is less than the one before it
- else{
- System.out.println("That is not abecedarian");
- return false;
+ else{return false;}
}
-
}
- System.out.println("Wow, that number is abecedarian");
return true;
- }
+}
From 658ed90553f40fd5df53edcea2503131bc73e282 Mon Sep 17 00:00:00 2001
From: Michael Rolland
Date: Thu, 28 Sep 2017 21:32:55 -0400
Subject: [PATCH 0114/2305] Create LowestBasePalindrome.java
Algorithm for determining the lowest base in which a given integer is a palindrome.
NOTE: Has room for error, see note at line 63.
---
Misc/LowestBasePalindrome.java | 144 +++++++++++++++++++++++++++++++++
1 file changed, 144 insertions(+)
create mode 100644 Misc/LowestBasePalindrome.java
diff --git a/Misc/LowestBasePalindrome.java b/Misc/LowestBasePalindrome.java
new file mode 100644
index 000000000000..fce2d2168465
--- /dev/null
+++ b/Misc/LowestBasePalindrome.java
@@ -0,0 +1,144 @@
+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 (any number n in base n is 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;
+ }
+}
From dc8114c17d0664f459d0c59e59a7e6f562530395 Mon Sep 17 00:00:00 2001
From: icalF
Date: Fri, 29 Sep 2017 10:47:05 +0700
Subject: [PATCH 0115/2305] Add longest increasing subsequence
---
.../LongestIncreasingSubsequence.java | 62 +++++++++++++++++++
1 file changed, 62 insertions(+)
create mode 100644 Dynamic Programming/LongestIncreasingSubsequence.java
diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java
new file mode 100644
index 000000000000..1616c246e273
--- /dev/null
+++ b/Dynamic Programming/LongestIncreasingSubsequence.java
@@ -0,0 +1,62 @@
+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;
+ }
+
+ public 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
From b64b92b378860855a08eb827807ae7ac0ccef7e7 Mon Sep 17 00:00:00 2001
From: Fahri YARDIMCI
Date: Fri, 29 Sep 2017 12:33:32 +0300
Subject: [PATCH 0116/2305] Creating ciphers and adding Caesar Cipher
---
ciphers/Caesar.java | 117 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 117 insertions(+)
create mode 100644 ciphers/Caesar.java
diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java
new file mode 100644
index 000000000000..32bc87b86e95
--- /dev/null
+++ b/ciphers/Caesar.java
@@ -0,0 +1,117 @@
+/**
+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
From e5381585a5329af6a1ad2d0b5ababef11cba4062 Mon Sep 17 00:00:00 2001
From: mpokryva
Date: Fri, 29 Sep 2017 11:21:47 -0400
Subject: [PATCH 0117/2305] Changed find(int key) method to return null when
node is not found, and updated docs accordingly. Issue #104.
---
data_structures/Trees/BinaryTree.java | 278 +++++++++++++-------------
1 file changed, 138 insertions(+), 140 deletions(-)
diff --git a/data_structures/Trees/BinaryTree.java b/data_structures/Trees/BinaryTree.java
index 3d05f1767819..a20d24eebc35 100644
--- a/data_structures/Trees/BinaryTree.java
+++ b/data_structures/Trees/BinaryTree.java
@@ -1,20 +1,20 @@
/**
- * 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 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
- *
- */
+* 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;
@@ -26,10 +26,10 @@ class Node{
public Node parent;
/**
- * Constructor of Node
- *
- * @param value Value to put in the node
- */
+ * Constructor of Node
+ *
+ * @param value Value to put in the node
+ */
public Node(int value){
data = value;
left = null;
@@ -40,56 +40,54 @@ public Node(int value){
/**
- * 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
- *
- */
+* 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
- */
+ * 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){
+ * 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;
- Node last = root;
- while(current != null){
- last = current;
- if(key < current.data)
+ while (current != null) {
+ if(key < current.data) {
current = current.left;
- else if(key > current.data)
+ } else if(key > current.data) {
current = current.right;
- //If you find the value return it
- else
+ } else { // If you find the value return it
return current;
+ }
}
- return last;
+ return null;
}
/**
- * Inserts certain value into the Binary Tree
- *
- * @param value Value to be inserted
- */
+ * 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;
+ root = newNode;
else{
//This will return the soon to be parent of the value you're inserting
Node parent = find(value);
@@ -109,29 +107,29 @@ public void put(int value){
}
/**
- * Deletes a given value from the Binary Tree
- *
- * @param value Value to be deleted
- * @return If the value was deleted
- */
+ * 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;
+ return false;
//No children
if(temp.right == null && temp.left == null){
if(temp == root)
- root = null;
+ 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;
+ temp.parent.right = null;
else
- temp.parent.left = null;
+ temp.parent.left = null;
return true;
}
@@ -162,9 +160,9 @@ else if(temp.left != null && temp.right != null){
//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;
+ temp.parent.right = successor;
else
- temp.parent.left = successor;
+ temp.parent.left = successor;
return true;
}
}
@@ -175,96 +173,96 @@ else if(temp.left != null && temp.right != null){
if(temp == root){
root = temp.right; return true;}
- temp.right.parent = temp.parent;
+ temp.right.parent = temp.parent;
- //Assigns temp to left or right child
- if(temp.data < temp.parent.data)
+ //Assigns temp to left or right child
+ if(temp.data < temp.parent.data)
temp.parent.left = temp.right;
- else
+ else
temp.parent.right = temp.right;
- return true;
+ 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;
+ }
+ }
}
- //If it has a left child
- else{
- if(temp == root){
- root = temp.left; return true;}
- temp.left.parent = temp.parent;
+ /**
+ * 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;
+ }
- //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;
+ /**
+ * Returns the root of the Binary Tree
+ *
+ * @return the root of the Binary Tree
+ */
+ public Node getRoot(){
+ return root;
}
- }
- }
- /**
- * 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;
- }
+ /**
+ * 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);
+ }
+ }
- /**
- * Returns the root of the Binary Tree
- *
- * @return the root of the Binary Tree
- */
- public Node getRoot(){
- return root;
- }
+ /**
+ * 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 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 + " ");
+ /**
+ * 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 + " ");
+ }
+ }
}
- }
-}
From 22c48e09253e43e499e94324e3baf0d8fddf0c58 Mon Sep 17 00:00:00 2001
From: Michael Rolland
Date: Fri, 29 Sep 2017 14:31:26 -0400
Subject: [PATCH 0118/2305] Create AnyBaseToAnyBase
Class for converting a number between any two bases, by going through decimal.
---
Conversions/AnyBaseToAnyBase | 87 ++++++++++++++++++++++++++++++++++++
1 file changed, 87 insertions(+)
create mode 100644 Conversions/AnyBaseToAnyBase
diff --git a/Conversions/AnyBaseToAnyBase b/Conversions/AnyBaseToAnyBase
new file mode 100644
index 000000000000..9f3f37041a5b
--- /dev/null
+++ b/Conversions/AnyBaseToAnyBase
@@ -0,0 +1,87 @@
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+/**
+ * Class for converting from any base to any other base, though it's unclear how digits greater than
+ * 36 would be represented in bases >36.
+ *
+ * @author Michael Rolland
+ * @version 2017.09.29
+ *
+ */
+public class AnyBaseToAnyBase {
+
+ // Driver
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+ System.out.print("Enter number: ");
+ String n = in.nextLine();
+ int b1=0,b2=0;
+ while (true) {
+ try {
+ System.out.print("Enter beginning base: ");
+ b1 = in.nextInt();
+ System.out.print("Enter end base: ");
+ b2 = in.nextInt();
+ break;
+ } catch (InputMismatchException e) {
+ System.out.println("Invalid input.");
+ in.next();
+ }
+ }
+ System.out.println(base2base(n, b1, b2));
+ }
+
+ /**
+ * Method to convert any integer from base b1 to base b2. Works by converting from b1 to decimal,
+ * then decimal to b2.
+ * @param n The integer to be converted.
+ * @param b1 Beginning base.
+ * @param b2 End base.
+ * @return n in base b2.
+ */
+ public 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;
+ }
+}
From 2d300b340a531988b55d00a71fd1ec9eda1d9e56 Mon Sep 17 00:00:00 2001
From: Michael Rolland
Date: Fri, 29 Sep 2017 14:32:47 -0400
Subject: [PATCH 0119/2305] Update LowestBasePalindrome.java
Very, very minor documentation edit
---
Misc/LowestBasePalindrome.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Misc/LowestBasePalindrome.java b/Misc/LowestBasePalindrome.java
index fce2d2168465..d0df5c30f511 100644
--- a/Misc/LowestBasePalindrome.java
+++ b/Misc/LowestBasePalindrome.java
@@ -46,7 +46,7 @@ public static int lowestBasePalindrome(int num) {
String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while (!foundBase) {
- // Try from bases 2 to num (any number n in base n is 1)
+ // Try from bases 2 to num-1
for (base=2; base0) {
From 1e99c48d4a3346476d7d48b8b03ae8ddea27569c Mon Sep 17 00:00:00 2001
From: Manmeet Singh
Date: Sun, 1 Oct 2017 00:17:23 +0530
Subject: [PATCH 0120/2305] Tower of Hanoi using Recursion
---
Misc/TowerOfHanoiUsingRecursion | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
create mode 100644 Misc/TowerOfHanoiUsingRecursion
diff --git a/Misc/TowerOfHanoiUsingRecursion b/Misc/TowerOfHanoiUsingRecursion
new file mode 100644
index 000000000000..60778fc9abe6
--- /dev/null
+++ b/Misc/TowerOfHanoiUsingRecursion
@@ -0,0 +1,26 @@
+package com.manmeet;
+
+import java.util.Scanner;
+
+public 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
+ }
+}
From dad4c69c98629a4ceb2dc8e1515400a8851cdd84 Mon Sep 17 00:00:00 2001
From: Nimit Arora
Date: Sun, 1 Oct 2017 12:39:38 +0530
Subject: [PATCH 0121/2305] Added algorithm to reverse a stack using recursion
---
Misc/ReverseStackUsingRecursion.java | 74 ++++++++++++++++++++++++++++
1 file changed, 74 insertions(+)
create mode 100644 Misc/ReverseStackUsingRecursion.java
diff --git a/Misc/ReverseStackUsingRecursion.java b/Misc/ReverseStackUsingRecursion.java
new file mode 100644
index 000000000000..4bcdeb25ea23
--- /dev/null
+++ b/Misc/ReverseStackUsingRecursion.java
@@ -0,0 +1,74 @@
+package stacks_and_queues;
+
+
+import java.util.Stack;
+
+public class ReverseStackUsingRecursion {
+
+ //Stack
+ private static Stack 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())
+ {
+ 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);
+
+ stack.push(temp);
+ }
+
+ }
+
+
+
+
+
+}
From 727769c06f45bf007cf2d229deb3fde46559bb87 Mon Sep 17 00:00:00 2001
From: Nimit Arora
Date: Sun, 1 Oct 2017 12:45:13 +0530
Subject: [PATCH 0122/2305] Added algorithm to reverse a stack using recursion
---
Misc/ReverseStackUsingRecursion.java | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/Misc/ReverseStackUsingRecursion.java b/Misc/ReverseStackUsingRecursion.java
index 4bcdeb25ea23..bb9f606a3ab9 100644
--- a/Misc/ReverseStackUsingRecursion.java
+++ b/Misc/ReverseStackUsingRecursion.java
@@ -1,4 +1,4 @@
-package stacks_and_queues;
+/* Program to reverse a Stack using Recursion*/
import java.util.Stack;
@@ -38,7 +38,7 @@ public static void main(String[] args) {
//Function Used to reverse Stack Using Recursion
private static void reverseUsingRecursion(Stack stack) {
- if(stack.isEmpty())
+ if(stack.isEmpty()) // If stack is empty then return
{
return;
}
@@ -60,7 +60,7 @@ private static void insertAtEnd(int temptop) {
int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
stack.pop();
- insertAtEnd(temptop);
+ insertAtEnd(temptop); //Recursive call
stack.push(temp);
}
From f6c64409c0f794e0dd5c3a8787a6dcacddcce636 Mon Sep 17 00:00:00 2001
From: Dheeraj Kumar Barnwal
Date: Sun, 1 Oct 2017 22:55:25 +0530
Subject: [PATCH 0123/2305] Corrected method call
---
Dynamic Programming/Fibonacci.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java
index 72048153de74..17c11d8d6ab6 100644
--- a/Dynamic Programming/Fibonacci.java
+++ b/Dynamic Programming/Fibonacci.java
@@ -40,7 +40,7 @@ public static int fibMemo(int n) {
f = 1;
}
else {
- f = fib(n-1) + fib(n-2);
+ f = fibMemo(n-1) + fibMemo(n-2);
map.put(n,f);
}
From 84b2b8ad9411ffeded1ba81168fcc9202a0a2794 Mon Sep 17 00:00:00 2001
From: Nimit Arora
Date: Sun, 1 Oct 2017 23:31:01 +0530
Subject: [PATCH 0124/2305] Added Algorithm to Return Subsequences
---
Misc/ReturnSubsequence.java | 59 +++++++++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
create mode 100644 Misc/ReturnSubsequence.java
diff --git a/Misc/ReturnSubsequence.java b/Misc/ReturnSubsequence.java
new file mode 100644
index 000000000000..ef3aaed09dd9
--- /dev/null
+++ b/Misc/ReturnSubsequence.java
@@ -0,0 +1,59 @@
+/*
+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
Date: Mon, 2 Oct 2017 00:42:20 +0530
Subject: [PATCH 0125/2305] Postfix Notation using Stack
Note- Give input in the form like "1 21 + 45 13 + *"
#96
---
Misc/StackPostfixNotation | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 Misc/StackPostfixNotation
diff --git a/Misc/StackPostfixNotation b/Misc/StackPostfixNotation
new file mode 100644
index 000000000000..c04b0ac6b44d
--- /dev/null
+++ b/Misc/StackPostfixNotation
@@ -0,0 +1,38 @@
+import java.util.*;
+
+public class Postfix {
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
+ System.out.println(postfixEvaluate(post));
+ }
+
+ // Evaluates the given postfix expression string and returns the result.
+ public static int postfixEvaluate(String exp) {
+ Stack