From 40620aea1b728c9a8fd1f931ec503660dd06e8c9 Mon Sep 17 00:00:00 2001 From: joshiujjawal22 Date: Mon, 18 May 2020 23:24:57 +0530 Subject: [PATCH 01/47] To find sum of triplets according to given value --- Others/3 sum.java | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Others/3 sum.java diff --git a/Others/3 sum.java b/Others/3 sum.java new file mode 100644 index 000000000000..3c008ff78360 --- /dev/null +++ b/Others/3 sum.java @@ -0,0 +1,48 @@ +package Others; + +import java.util.Scanner; +import java.util.Arrays; + +/** + * To find triplet equals to given sum in complexity O(n*log(n)) + * + * + * Array must be sorted + * + * @author Ujjawal Joshi + * @date 2020.05.18 + */ + + +class threesum{ + public static void main(String args[]) + { + Scanner sc =new Scanner(System.in); + int n=sc.nextInt(); //Length of an array + + int a[]=new int[n]; + + for(int i=0;i Date: Mon, 18 May 2020 23:35:06 +0530 Subject: [PATCH 02/47] Rotation of an array without using extra space --- ...on of array without using extra space.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Others/Rotation of array without using extra space.java diff --git a/Others/Rotation of array without using extra space.java b/Others/Rotation of array without using extra space.java new file mode 100644 index 000000000000..c25dbaefc8c9 --- /dev/null +++ b/Others/Rotation of array without using extra space.java @@ -0,0 +1,54 @@ +package Others; + +import java.util.*; + +/** + * Rotation of array without using extra space + * + * + * @author Ujjawal Joshi + * @date 2020.05.18 + */ + +class main{ + public static void main(String[] args) + { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int a[][]=new int[n][n]; + + for(int i=0;i Date: Fri, 22 May 2020 02:28:42 +0530 Subject: [PATCH 03/47] Create BucketSort.java --- Sorts/BucketSort.java | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Sorts/BucketSort.java diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java new file mode 100644 index 000000000000..58127927ee58 --- /dev/null +++ b/Sorts/BucketSort.java @@ -0,0 +1,68 @@ + +import java.util.Random; + +public class Bucket_Sort +{ + static int[] sort(int[] sequence, int maxValue) + { + // Bucket Sort + int[] Bucket = new int[maxValue + 1]; + int[] sorted_sequence = new int[sequence.length]; + + for (int i = 0; i < sequence.length; i++) + Bucket[sequence[i]]++; + + int outPos = 0; + for (int i = 0; i < Bucket.length; i++) + for (int j = 0; j < Bucket[i]; j++) + sorted_sequence[outPos++] = i; + + return sorted_sequence; + } + + static void printSequence(int[] sorted_sequence) + { + for (int i = 0; i < sorted_sequence.length; i++) + System.out.print(sorted_sequence[i] + " "); + } + + static int maxValue(int[] sequence) + { + int maxValue = 0; + for (int i = 0; i < sequence.length; i++) + if (sequence[i] > maxValue) + maxValue = sequence[i]; + return maxValue; + } + + public static void main(String args[]) + { + System.out.println("Sorting of randomly generated numbers using BUCKET SORT"); + Random random = new Random(); + int N = 20; + int[] sequence = new int[N]; + + for (int i = 0; i < N; i++) + sequence[i] = Math.abs(random.nextInt(100)); + + int maxValue = maxValue(sequence); + + System.out.println("\nOriginal Sequence: "); + printSequence(sequence); + + System.out.println("\nSorted Sequence: "); + printSequence(sort(sequence, maxValue)); + } +} + +#Output: + +$ javac Bucket_Sort.java +$ java Bucket_Sort + +Sorting of randomly generated numbers using BUCKET SORT + +Original Sequence: +95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66 +Sorted Sequence: +8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95 From 627115b3368f38e45f9a2b0928cab0ad8d790cf4 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Fri, 22 May 2020 16:23:41 +0530 Subject: [PATCH 04/47] Created Graph Algos it contains Dijkstra, Prims, dft, bft, dfs, bfs and many more. --- DataStructures/Graphs/GraphAlgos | 437 +++++++++++++++++++++++++++++++ 1 file changed, 437 insertions(+) create mode 100644 DataStructures/Graphs/GraphAlgos diff --git a/DataStructures/Graphs/GraphAlgos b/DataStructures/Graphs/GraphAlgos new file mode 100644 index 000000000000..780a73e45540 --- /dev/null +++ b/DataStructures/Graphs/GraphAlgos @@ -0,0 +1,437 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import Heaps.GenericHeap; +public class Graph { + private class vertex{ + HashMap nbrs=new HashMap<>(); + } + HashMap vertcs; + public Graph(){ + vertcs=new HashMap<>(); + } + public int numVertex() { + return this.vertcs.size(); + } + public boolean containsVertex(String vname) { + return this.vertcs.containsKey(vname); + } + public void addVertex(String vname) { + + vertex vtx=new vertex(); + this.vertcs.put(vname,vtx); + } + public void removeVertex(String vname) { + vertex vtx=this.vertcs.get(vname); + ArrayList keys=new ArrayList<>(vtx.nbrs.keySet()); + for(String key:keys) { + vertex nbrvtx=this.vertcs.get(key); + nbrvtx.nbrs.remove(vname); + } + this.vertcs.remove(vname); + } + + public int numEdge() { + int count=0; + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + vertex vtx=this.vertcs.get(key); + count+=vtx.nbrs.size(); + } + return count/2; + } + public boolean containsEdge(String vname1,String vname2) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2)) + return false; + return true; + } + public void addEdge(String vname1,String vname2,int cost) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||vtx1.nbrs.containsKey(vname2)) + return; + vtx1.nbrs.put(vname2,cost); + vtx2.nbrs.put(vname1,cost); + } + public void removeEdge(String vname1,String vname2) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2)) + return; + vtx1.nbrs.remove(vname2); + vtx2.nbrs.remove(vname1); + } + + public void display() { + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + vertex vtx=this.vertcs.get(key); + System.out.println(key+" := "+vtx.nbrs); + } + } + + public boolean hasPath(String source ,String dest,HashMap processed) { + processed.put(source, true); + if(containsEdge(source,dest)) { + return true; + } + vertex vtx=this.vertcs.get(source); + ArrayList keys=new ArrayList<>(vtx.nbrs.keySet()); + for(String key:keys) { + if(!processed.containsKey(key) && hasPath(key,dest,processed)) + return true; + } + return false; + + } + private class pair{ + String vname; + String psf; + } + public boolean bfs(String source,String dest) { // breadth first search + HashMap processed=new HashMap<>(); + + LinkedList queue=new LinkedList<>(); + pair sp=new pair(); + sp.vname=source; + sp.psf=source; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + if(containsEdge(rp.vname,dest)) { + System.out.println(rp.psf+dest); + return true; + } + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + return false; + } + public boolean dfs(String source,String dest) { //deapth first search + LinkedList stack=new LinkedList<>(); + HashMap processed=new HashMap<>(); + pair sp=new pair(); + sp.vname=source; + sp.psf=source; + stack.addFirst(sp); + while(!stack.isEmpty()) { + pair rp=stack.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + if(containsEdge(rp.vname,dest)) { + System.out.println(rp.psf+dest); + return true; + } + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + stack.addFirst(np); + } + } + + } + return false; + } + public void bft() { //breadth first traversal + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + System.out.println(rp.vname+" via "+rp.psf); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + } + public void dft() { //deapt first traversal + HashMap processed=new HashMap<>(); + LinkedList stack=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + stack.addFirst(sp); + + while(!stack.isEmpty()) { + pair rp=stack.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + System.out.println(rp.vname+" via "+rp.psf); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + stack.addFirst(np); + } + } + } + } + } + + + public boolean isCyclic() { + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + return true; + processed.put(rp.vname,true); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + return false; + } + public boolean isConnected() { + int flag=0; + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + flag++; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + if(flag>=2) + return false; + else + return true; + } + public boolean isTree() { + return !isCyclic()&&isConnected(); + } + public ArrayList> getConnectedComp() { + ArrayList> ans=new ArrayList<>(); + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + ArrayList subans=new ArrayList<>(); + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + subans.add(rp.vname); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + ans.add(subans); + } + return ans; + } + private class PrimsPair implements Comparable{ + String vname; + String acqvname; + int cost; + public int compareTo(PrimsPair o) { + return o.cost-this.cost; + } + + } + public Graph prims() { + HashMap map=new HashMap<>(); + GenericHeap heap=new GenericHeap<>(); + Graph mst=new Graph(); + for(String vrtx:this.vertcs.keySet()) { + PrimsPair np=new PrimsPair(); + np.acqvname=null; + np.vname=vrtx; + np.cost=Integer.MAX_VALUE; + heap.add(np); + map.put(vrtx, np); + } + while(!heap.isEmpty()) { + PrimsPair rp=heap.remove(); + map.remove(rp.vname); + + if(rp.acqvname==null) { + mst.addVertex(rp.vname); + }else { + mst.addVertex(rp.vname); + mst.addEdge(rp.vname, rp.acqvname, rp.cost); + } + + for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) { + if(map.containsKey(nbr)) { + //old cost that is from diff path stored in map + int oc=map.get(nbr).cost; + // cost that present vname need cost to go to nbr + int nc=this.vertcs.get(rp.vname).nbrs.get(nbr); + if(nc{ + String vname; + String psf; + int cost; + public int compareTo(DijktsraPair o) { + return o.cost-this.cost; + } + + } + public HashMap Dijktsra(String source) { + HashMap map=new HashMap<>(); + GenericHeap heap=new GenericHeap<>(); + HashMap ans =new HashMap<>(); + for(String vrtx:this.vertcs.keySet()) { + DijktsraPair np=new DijktsraPair(); + np.psf=""; + np.vname=vrtx; + np.cost=Integer.MAX_VALUE; + if(vrtx==source) { + np.cost=0; + np.psf=source; + } + heap.add(np); + map.put(vrtx, np); + } + while(!heap.isEmpty()) { + DijktsraPair rp=heap.remove(); + map.remove(rp.vname); + + ans.put(rp.vname,rp.cost); + + for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) { + if(map.containsKey(nbr)) { + //old cost that is from diff path stored in map + int oc=map.get(nbr).cost; + // cost that present vname need cost to go to nbr + int nc=rp.cost+this.vertcs.get(rp.vname).nbrs.get(nbr); + if(nc Date: Sat, 23 May 2020 05:30:43 +0530 Subject: [PATCH 05/47] Create SinglyLinkedList --- DataStructures/Lists/SinglyLinkedList | 101 ++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 DataStructures/Lists/SinglyLinkedList diff --git a/DataStructures/Lists/SinglyLinkedList b/DataStructures/Lists/SinglyLinkedList new file mode 100644 index 000000000000..0b51813037f4 --- /dev/null +++ b/DataStructures/Lists/SinglyLinkedList @@ -0,0 +1,101 @@ +package LinkedList; +import java.util.*; +import java.lang.*; +import java.io.*; +class LinkedList { + private class Node{ + int data; + Node next; + + Node(int data) { + this.data = data; + this.next = null; + } + } + public Node head = null; + public Node tail = null; + private int size=0; + + public void addLast(int data) { + Node newNode = new Node(data); + + if(this.head == null) { + this.head = newNode; + this.tail = newNode; + this.size++; + } + else { + this.tail.next = newNode; + this.tail = newNode; + this.size++; + } + } + + + public void display() { + Node current = this.head; + if(this.head == null) { + return; + } + while(current != null) { + System.out.print(current.data + " "); + current = current.next; + } + System.out.println(); + } + + public void formLL2(LinkedList LL1) { + Node current=LL1.head; + while(current.next!=null&¤t.next.next!=null) { + int sum=current.data+current.next.next.data; + this.addLast(sum); + current=current.next.next; + } + } + public void formLL3(LinkedList LL1) { + Node current=LL1.head.next; + while(current.next!=null&¤t.next.next!=null) { + int sum=current.data+current.next.next.data; + this.addLast(sum); + current=current.next.next; + } + } + public Node mid() { + Node slow=this.head; + Node fast=this.head; + while(fast.next!=null && fast.next.next!=null) { + slow=slow.next; + fast=fast.next.next; + } + return slow; + } + public Node midValue() { + int sum=this.head.data+this.tail.data; + Node mid=new Node(sum); + return mid; + } + public void formRes(LinkedList LL1,LinkedList LL2,LinkedList LL3,Node MID) { + Node LL1mid=LL1.mid(); + Node currentLL1=LL1.head; + Node currentLL2=LL2.head; + Node currentLL3=LL3.head; + while(currentLL1!=null) { + this.addLast(currentLL1.data); + + if(currentLL2!=null) { + this.addLast(currentLL2.data); + currentLL2=currentLL2.next; + }else if(currentLL1.equals(LL1mid)) { + this.addLast(MID.data); + } + else if(currentLL2==null&¤tLL3!=null) { + this.addLast(currentLL3.data); + currentLL3=currentLL3.next; + } + currentLL1=currentLL1.next; + } + } + public void Size() { + System.out.println(this.size); + } + } From 4842a4ca61d4721aa48af740e483569d3c304a07 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Sat, 23 May 2020 05:32:30 +0530 Subject: [PATCH 06/47] Update and rename SinglyLinkedList to ListAddnFun --- DataStructures/Lists/{SinglyLinkedList => ListAddnFun} | 1 - 1 file changed, 1 deletion(-) rename DataStructures/Lists/{SinglyLinkedList => ListAddnFun} (99%) diff --git a/DataStructures/Lists/SinglyLinkedList b/DataStructures/Lists/ListAddnFun similarity index 99% rename from DataStructures/Lists/SinglyLinkedList rename to DataStructures/Lists/ListAddnFun index 0b51813037f4..47553e184358 100644 --- a/DataStructures/Lists/SinglyLinkedList +++ b/DataStructures/Lists/ListAddnFun @@ -1,4 +1,3 @@ -package LinkedList; import java.util.*; import java.lang.*; import java.io.*; From ef2be071b09617df3f4354920d99d17dc9561feb Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Sat, 23 May 2020 05:33:40 +0530 Subject: [PATCH 07/47] Create AVLSimple --- DataStructures/Trees/AVLSimple | 106 +++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 DataStructures/Trees/AVLSimple diff --git a/DataStructures/Trees/AVLSimple b/DataStructures/Trees/AVLSimple new file mode 100644 index 000000000000..1f2c2bd6aba2 --- /dev/null +++ b/DataStructures/Trees/AVLSimple @@ -0,0 +1,106 @@ +public class AVLTree { + private class Node{ + int data; + int height; + Node left; + Node right; + Node(int data){ + this.data=data; + this.height=1; + } + + } + private Node root; + public void insert(int data) { + this.root=insert(this.root,data); + } + private Node insert(Node node,int item) { + if(node==null) { + Node add=new Node(item); + return add; + } + if(node.data>item) { + node.left=insert(node.left,item); + } + if(node.data1&&itemnode.right.data) + return leftRotate(node); + //RL case + if(bf<-1&&item1&&item>node.left.data) { + node.left=leftRotate(node.left); + return rightRotate(node); + } + + return node; + } + public void display() { + this.display(this.root); + System.out.println(this.root.height); + } + private void display (Node node) { + String str=""; + if(node.left!=null) + str+=node.left.data+"=>"; + else + str+="END=>"; + str+=node.data+""; + if(node.right!=null) + str+="<="+node.right.data; + else + str+="<=END"; + System.out.println(str); + if(node.left!=null) + display(node.left); + if(node.right!=null) + display(node.right); + } + private int height(Node node) { + if(node==null) { + return 0; + } + return node.height; + + } + private int bf(Node node) { + if(node==null) + return 0; + return height(node.left)-height(node.right); + } + + private Node rightRotate(Node c) { + Node b=c.left; + Node T3=b.right; + + b.right=c; + c.left=T3; + c.height=Math.max(height(c.left),height(c.right))+1; + b.height=Math.max(height(b.left),height(b.right))+1; + return b; + + } + private Node leftRotate(Node c) { + Node b=c.right; + Node T3=b.left; + + b.left=c; + c.right=T3; + c.height=Math.max(height(c.left),height(c.right))+1; + b.height=Math.max(height(b.left),height(b.right))+1; + return b; + + } + +} From 07aee8ba8129af1310b9e4fd08834214439f940c Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Sat, 23 May 2020 05:34:56 +0530 Subject: [PATCH 08/47] Create BoardPath --- DynamicProgramming/BoardPath | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 DynamicProgramming/BoardPath diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath new file mode 100644 index 000000000000..4b471a88ed64 --- /dev/null +++ b/DynamicProgramming/BoardPath @@ -0,0 +1,52 @@ + +public class BoardPath { + public static long startTime; + public static long endTime; + public static void startAlgo() { + startTime=System.currentTimeMillis(); + } + public static long endAlgo() { + endTime=System.currentTimeMillis(); + return endTime-startTime; + } + public static int bpR(int start,int end){ + if(start==end) { + return 1; + } + else if(start>end) + return 0; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpR(start+dice,end); + } + return count; + } + public static int bpRS(int curr,int end,int strg[]){ + if(curr==end) { + return 1; + } + else if(curr>end) + return 0; + if(strg[curr]!=0) + return strg[curr]; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpRS(curr+dice,end,strg); + } + strg[curr]=count; + return count; + } + public static int bpIS(int curr,int end,int[]strg){ + strg[end]=1; + for(int i=end-1;i>=0;i--) { + int count=0; + for(int dice=1;dice<=6&&dice+i Date: Sat, 23 May 2020 05:35:47 +0530 Subject: [PATCH 09/47] Create CountNumBinaryStrings --- DynamicProgramming/CountNumBinaryStrings | 69 ++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 DynamicProgramming/CountNumBinaryStrings diff --git a/DynamicProgramming/CountNumBinaryStrings b/DynamicProgramming/CountNumBinaryStrings new file mode 100644 index 000000000000..c71fbd63c682 --- /dev/null +++ b/DynamicProgramming/CountNumBinaryStrings @@ -0,0 +1,69 @@ +public class CountNumBinaryStr { + public static long startTime; + public static long endTime; + public static void startAlgo() { + startTime=System.currentTimeMillis(); + } + public static long endAlgo() { + endTime=System.currentTimeMillis(); + return endTime-startTime; + } + public static int numStrIS(int n) { + int[] zeros=new int[n]; + int []ones=new int[n]; + //seed + zeros[0]=1; + ones[0]=1; + for(int i=1;i Date: Sat, 23 May 2020 05:54:34 +0530 Subject: [PATCH 10/47] Delete LinkedList.java --- .../HashMap/Hashing/LinkedList.java | 63 ------------------- 1 file changed, 63 deletions(-) delete mode 100644 DataStructures/HashMap/Hashing/LinkedList.java diff --git a/DataStructures/HashMap/Hashing/LinkedList.java b/DataStructures/HashMap/Hashing/LinkedList.java deleted file mode 100644 index 4953551f7040..000000000000 --- a/DataStructures/HashMap/Hashing/LinkedList.java +++ /dev/null @@ -1,63 +0,0 @@ -package DataStructures.HashMap.Hashing; - -class LinkedList { - - private Node Head; - private int size; - - public LinkedList() { - Head = null; - size = 0; - } - - public void insert(int data) { - - Node newnode = new Node(data); - - size++; - - if(Head == null) { - Head = newnode; - } - else { - newnode.next = Head; - Head = newnode; - } - } - - public void delete(int data) { - if(size == 0) { - System.out.println("UnderFlow!"); - return; - } - - else { - Node curr = Head; - if (curr.data == data) { - Head = curr.next; - size--; - return; - } - else { - - while(curr.next.next != null) { - if(curr.next.data == data){ - curr.next = curr.next.next; - return; - } - } - - System.out.println("Key not Found"); - } - } - } - - public void display() { - Node temp = Head; - while(temp != null) { - System.out.printf("%d ",temp.data); - temp = temp.next; - } - System.out.println(); - } -} \ No newline at end of file From 3a234f0914198b6477445426a565c99e3dacae34 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Sat, 23 May 2020 05:56:23 +0530 Subject: [PATCH 11/47] Delete Node.java --- DataStructures/HashMap/Hashing/Node.java | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 DataStructures/HashMap/Hashing/Node.java diff --git a/DataStructures/HashMap/Hashing/Node.java b/DataStructures/HashMap/Hashing/Node.java deleted file mode 100644 index 74ab01f9d2a9..000000000000 --- a/DataStructures/HashMap/Hashing/Node.java +++ /dev/null @@ -1,11 +0,0 @@ -package DataStructures.HashMap.Hashing; - -class Node { - int data; - Node next; - - public Node(int data) { - this.data = data; - this.next = null; - } -} \ No newline at end of file From 01d5814557dbe674886def8ceef86208c8994bbc Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Sat, 23 May 2020 05:57:55 +0530 Subject: [PATCH 12/47] Create Intersection --- DataStructures/HashMap/Hashing/Intersection | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 DataStructures/HashMap/Hashing/Intersection diff --git a/DataStructures/HashMap/Hashing/Intersection b/DataStructures/HashMap/Hashing/Intersection new file mode 100644 index 000000000000..cfe1f74d73eb --- /dev/null +++ b/DataStructures/HashMap/Hashing/Intersection @@ -0,0 +1,37 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + +public class Intersection { + + public static ArrayList Main(int arr[],int arr2[]) { + HashMap hmap=new HashMap<>(); + HashMap hmap2=new HashMap<>(); + for(int i=0;i res=new ArrayList<>(); + for(int i=0;i0) { + int val=hmap.get(arr2[i]); + hmap.put(arr2[i],val-1); + res.add(arr2[i]); + } + + } + return res; + } + public Intersection() { + + } + + + +} From ed497cec3782086f6834c410af31f21b51778732 Mon Sep 17 00:00:00 2001 From: Vineet Rathor <35703327+THE-VR7@users.noreply.github.com> Date: Sat, 23 May 2020 13:16:09 +0530 Subject: [PATCH 13/47] Update BucketSort.java --- Sorts/BucketSort.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java index 58127927ee58..7556faf57406 100644 --- a/Sorts/BucketSort.java +++ b/Sorts/BucketSort.java @@ -55,6 +55,8 @@ public static void main(String args[]) } } + +/* #Output: $ javac Bucket_Sort.java @@ -66,3 +68,4 @@ public static void main(String args[]) 95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66 Sorted Sequence: 8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95 +*/ From 1ef46dbfd49245ba7c6b5adf29b914e3d4db8b2f Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 02:50:24 +0530 Subject: [PATCH 14/47] Update GraphAlgos --- DataStructures/Graphs/GraphAlgos | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/DataStructures/Graphs/GraphAlgos b/DataStructures/Graphs/GraphAlgos index 780a73e45540..19938c48f042 100644 --- a/DataStructures/Graphs/GraphAlgos +++ b/DataStructures/Graphs/GraphAlgos @@ -1,3 +1,53 @@ +package DataStructures.Graphs; +/* +Implementation of graph by using hashmap for vertices of class which contains hashmap for vertex and then algos like prims dijktsra ,depth for search and traversal ,breadth for search and traversal ,algo for cycle present or not ,connected or not ,if not connected then connect it +Test case +Graph gp=new Graph(); + gp.addVertex("A"); + gp.addVertex("B"); + gp.addVertex("C"); + gp.addVertex("D"); + gp.addVertex("E"); + gp.addVertex("F"); + gp.addVertex("G"); + gp.addEdge("A", "B", 2); + gp.addEdge("A", "D", 10); + gp.addEdge("B", "C", 3); + gp.addEdge("C", "D", 1); + gp.addEdge("D", "E", 8); + gp.addEdge("E", "F", 5); + gp.addEdge("E", "G", 6); + gp.addEdge("F", "G", 4); + +// gp.display(); +// System.out.println(gp.numVertex()); +// System.out.println(gp.numEdge()); +// System.out.println(gp.containsEdge("A", "C")); +// +// System.out.println(gp.containsEdge("E", "F")); +// gp.removeEdge("D", "E"); +// gp.display(); +// gp.removeVertex("F"); +// gp.addVertex("F"); +// gp.display(); +// System.out.println(gp.hasPath("A", "F", new HashMap<>())); +// System.out.println(gp.dfs("A", "F")); +// gp.bft(); +// gp.dft(); +// gp.removeEdge("B","C"); +// gp.removeEdge("F","G"); +// System.out.println(gp.isConnected()); +// System.out.println(gp.isCyclic()); +// System.out.println(gp.isTree()); +// System.out.println(gp.getConnectedComp()); +// gp.prims().display(); + System.out.println(gp.Dijktsra("A")); + + + +*/ + + import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; From a5f42e293bfbe2c16efdef8c837bf2e36dcc7750 Mon Sep 17 00:00:00 2001 From: Maria Lungeanu Date: Mon, 25 May 2020 00:21:28 +0300 Subject: [PATCH 15/47] Fixed Error:(6, 8) java: class algorithm is public, should be declared in a file named algorithm.java. Inside file PrimeFactorization, the name of public class was wrong. --- Conversions/DecimalToBinary.java | 4 +- Conversions/OctalToHexadecimal.java | 8 +- DataStructures/DynamicArray/DynamicArray.java | 4 +- DataStructures/Graphs/BellmanFord.java | 2 +- DataStructures/Graphs/MatrixGraphs.java | 3 +- DataStructures/Heaps/HeapElement.java | 18 +- DataStructures/Heaps/MaxHeap.java | 8 +- DataStructures/Heaps/MinHeap.java | 8 +- DataStructures/Lists/CircleLinkedList.java | 2 +- DataStructures/Lists/DoublyLinkedList.java | 12 +- DataStructures/Stacks/NodeStack.java | 4 +- DataStructures/Trees/LevelOrderTraversal.java | 4 +- .../Trees/LevelOrderTraversalQueue.java | 4 +- DataStructures/Trees/ValidBSTOrNot.java | 3 +- .../LongestIncreasingSubsequence.java | 2 +- .../MatrixChainMultiplication.java | 2 +- Maths/GCD.java | 2 +- Others/Dijkstra.java | 409 ++++++++++-------- Others/TopKWords.java | 3 +- Others/TowerOfHanoi.java | 2 +- Searches/IterativeBinarySearch.java | 2 +- Sorts/QuickSort.java | 2 +- ciphers/Caesar.java | 2 + ciphers/ColumnarTranspositionCipher.java | 2 +- divideconquer/ClosestPair.java | 19 +- 25 files changed, 293 insertions(+), 238 deletions(-) diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index ccd8c643fa9a..4dd1ba4f4414 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -27,7 +27,7 @@ public static void main(String args[]) { public static void conventionalConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf("Conventional conversion.\n\tEnter the decimal number: "); + System.out.printf("Conventional conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = n % 2; @@ -46,7 +46,7 @@ public static void conventionalConversion() { public static void bitwiseConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf("Bitwise conversion.\n\tEnter the decimal number: "); + System.out.printf("Bitwise conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = (n & 1); diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java index dd8d877109b5..4f15c488237b 100644 --- a/Conversions/OctalToHexadecimal.java +++ b/Conversions/OctalToHexadecimal.java @@ -15,7 +15,7 @@ public class OctalToHexadecimal { * @param s The Octal Number * @return The Decimal number */ - public static int OctToDec(String s) { + public static int octToDec(String s) { int i = 0; for (int j = 0; j < s.length(); j++) { char num = s.charAt(j); @@ -32,7 +32,7 @@ public static int OctToDec(String s) { * @param d The Decimal Number * @return The Hexadecimal number */ - public static String DecimalToHex(int d) { + public static String decimalToHex(int d) { String digits = "0123456789ABCDEF"; if (d <= 0) return "0"; @@ -54,10 +54,10 @@ public static void main(String args[]) { String oct = input.next(); // Pass the octal number to function and get converted deciaml form - int decimal = OctToDec(oct); + int decimal = octToDec(oct); // Pass the decimla number to function and get converted Hex form of the number - String hex = DecimalToHex(decimal); + String hex = decimalToHex(decimal); System.out.println("The Hexadecimal equivalant is: " + hex); input.close(); } diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java index 0a6a0723e2a1..f70c45cec815 100644 --- a/DataStructures/DynamicArray/DynamicArray.java +++ b/DataStructures/DynamicArray/DynamicArray.java @@ -41,7 +41,7 @@ public void add(final E element) { } public void put(final int index, E element) { - Objects.checkIndex(index, this.size); +// Objects.checkIndex(index, this.size); this.elements[index] = element; } @@ -79,7 +79,7 @@ private void fastRemove(final Object[] elements, final int index) { } private E getElement(final int index) { - Objects.checkIndex(index, this.size); +// Objects.checkIndex(index, this.size); return (E) this.elements[index]; } diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java index 6dffede9e606..41c89bb020ee 100644 --- a/DataStructures/Graphs/BellmanFord.java +++ b/DataStructures/Graphs/BellmanFord.java @@ -23,7 +23,7 @@ class Edge * @param v End vertex * @param c Weight */ - Edge(int a,int b,int c) + public Edge(int a,int b,int c) { u=a; v=b; diff --git a/DataStructures/Graphs/MatrixGraphs.java b/DataStructures/Graphs/MatrixGraphs.java index e7fb9cc4fb2f..32a7c990e3ef 100644 --- a/DataStructures/Graphs/MatrixGraphs.java +++ b/DataStructures/Graphs/MatrixGraphs.java @@ -127,8 +127,7 @@ public boolean removeEdge(int from, int to) { * @return returns a string describing this graph */ public String toString() { - String s = new String(); - s = " "; + String s = " "; for (int i = 0; i < this.numberOfVertices(); i++) { s = s + String.valueOf(i) + " "; } diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index 113146012918..028d9b3e67de 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -117,7 +117,21 @@ public String toString() { * @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)); + @Override + public boolean equals(Object o) { + if (o != null) { + if (!(o instanceof HeapElement)) return false; + HeapElement otherHeapElement = (HeapElement) o; + return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); + } + return false; + } + + @Override + public int hashCode() { + int result = 0; + result = 31*result + (int) key; + result = 31*result + (additionalInfo != null ? additionalInfo.hashCode() : 0); + return result; } } diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java index fed09bcba045..3945caa97fde 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -49,9 +49,9 @@ private void swap(int index1, int index2) { // 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); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } } @@ -101,7 +101,7 @@ public void deleteElement(int elementIndex) { 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); + if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) toggleUp(elementIndex); // ... or down ? else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java index 4b435e6d81d7..39ee6ebf7b8f 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -44,9 +44,9 @@ private void swap(int index1, int index2) { // 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); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } } @@ -96,7 +96,7 @@ public void deleteElement(int elementIndex) { 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); + if (getElementKey(elementIndex) < getElementKey((int)Math.floor(elementIndex / 2.0))) toggleUp(elementIndex); // ... or down ? else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) diff --git a/DataStructures/Lists/CircleLinkedList.java b/DataStructures/Lists/CircleLinkedList.java index 67235172dfb7..b46441a1fa47 100644 --- a/DataStructures/Lists/CircleLinkedList.java +++ b/DataStructures/Lists/CircleLinkedList.java @@ -14,7 +14,7 @@ private Node(E value, Node next) { //For better O.O design this should be private allows for better black box design private int size; //this will point to dummy node; - private Node head; + private Node head = null; //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; public CircleLinkedList() { diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index e1b0041dda39..706b33c7e10d 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -86,9 +86,12 @@ public void insertTail(int x) { public Link deleteHead() { Link temp = head; head = head.next; // oldHead <--> 2ndElement(head) - head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed - if (head == null) + + if (head == null) { tail = null; + } else { + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + } return temp; } @@ -100,10 +103,13 @@ public Link deleteHead() { public Link deleteTail() { Link temp = tail; tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null - tail.next = null; // 2ndLast(tail) --> null + if (tail == null) { head = null; + } else{ + tail.next = null; // 2ndLast(tail) --> null } + return temp; } diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java index 616e6a1e1548..0f1d58686b0d 100644 --- a/DataStructures/Stacks/NodeStack.java +++ b/DataStructures/Stacks/NodeStack.java @@ -74,7 +74,7 @@ public void push(Item item) { } else { newNs.setPrevious(NodeStack.head); NodeStack.head.setNext(newNs); - NodeStack.head = newNs; + NodeStack.head.setHead(newNs); } NodeStack.setSize(NodeStack.getSize() + 1); @@ -89,7 +89,7 @@ public Item pop() { Item item = (Item) NodeStack.head.getData(); - NodeStack.head = NodeStack.head.getPrevious(); + NodeStack.head.setHead(NodeStack.head.getPrevious()); NodeStack.head.setNext(null); NodeStack.setSize(NodeStack.getSize() - 1); diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index bcf172495d13..69e65fe64089 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -15,8 +15,8 @@ public Node(int item) { // Root of the Binary Tree Node root; - public LevelOrderTraversal() { - root = null; + public LevelOrderTraversal( Node root) { + this.root = root; } /* function to print level order traversal of tree*/ diff --git a/DataStructures/Trees/LevelOrderTraversalQueue.java b/DataStructures/Trees/LevelOrderTraversalQueue.java index d43d62d68f5f..5f85f987d673 100644 --- a/DataStructures/Trees/LevelOrderTraversalQueue.java +++ b/DataStructures/Trees/LevelOrderTraversalQueue.java @@ -19,11 +19,9 @@ public Node(int item) { } } - Node root; - /* Given a binary tree. Print its nodes in level order using array for implementing queue */ - void printLevelOrder() { + void printLevelOrder(Node root) { Queue queue = new LinkedList(); queue.add(root); while (!queue.isEmpty()) { diff --git a/DataStructures/Trees/ValidBSTOrNot.java b/DataStructures/Trees/ValidBSTOrNot.java index a1a737fe4fe9..ba50c079eac4 100644 --- a/DataStructures/Trees/ValidBSTOrNot.java +++ b/DataStructures/Trees/ValidBSTOrNot.java @@ -13,14 +13,13 @@ public Node(int item) { } //Root of the Binary Tree - Node root; /* can give min and max value according to your code or can write a function to find min and max value of tree. */ /* returns true if given search tree is binary search tree (efficient version) */ - boolean isBST() { + boolean isBST(Node root) { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java index c8296518590d..e30adfeffd39 100644 --- a/DynamicProgramming/LongestIncreasingSubsequence.java +++ b/DynamicProgramming/LongestIncreasingSubsequence.java @@ -22,7 +22,7 @@ public static void main(String[] args) { private static int upperBound(int[] ar, int l, int r, int key) { while (l < r - 1) { - int m = (l + r) / 2; + int m = (l + r) >>> 1; if (ar[m] >= key) r = m; else diff --git a/DynamicProgramming/MatrixChainMultiplication.java b/DynamicProgramming/MatrixChainMultiplication.java index 66b2a35824e2..9073400d3299 100644 --- a/DynamicProgramming/MatrixChainMultiplication.java +++ b/DynamicProgramming/MatrixChainMultiplication.java @@ -25,7 +25,7 @@ public static void main(String[] args) { count++; } for (Matrix m : mArray) { - System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row()); + System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); } size = mArray.size(); diff --git a/Maths/GCD.java b/Maths/GCD.java index fb9aeb21ee1b..bff1c33c80f5 100644 --- a/Maths/GCD.java +++ b/Maths/GCD.java @@ -52,6 +52,6 @@ public static void main(String[] args) { // call gcd function (input array) System.out.println(gcd(myIntArray)); // => 4 - System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8 + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 } } diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index af8e33b0b320..b1a0987d0245 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -1,192 +1,219 @@ -package Others; - - -/** - * Dijkstra's algorithm,is a graph search algorithm that solves the single-source - * shortest path problem for a graph with nonnegative edge path costs, producing - * a shortest path tree. - *

- * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting - * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node. - *

- * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java - * Also most of the comments are from RosettaCode. - */ - -import java.util.*; - -public class Dijkstra { - private static final Graph.Edge[] GRAPH = { - // Distance from node "a" to node "b" is 7. - // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), - // a new edge would be needed for that - new Graph.Edge("a", "b", 7), - new Graph.Edge("a", "c", 9), - new Graph.Edge("a", "f", 14), - new Graph.Edge("b", "c", 10), - new Graph.Edge("b", "d", 15), - new Graph.Edge("c", "d", 11), - new Graph.Edge("c", "f", 2), - new Graph.Edge("d", "e", 6), - new Graph.Edge("e", "f", 9), - }; - private static final String START = "a"; - private static final String END = "e"; - - /** - * main function - * Will run the code with "GRAPH" that was defined above. - */ - public static void main(String[] args) { - Graph g = new Graph(GRAPH); - g.dijkstra(START); - g.printPath(END); - //g.printAllPaths(); - } -} - -class Graph { - // mapping of vertex names to Vertex objects, built from a set of Edges - private final Map graph; - - /** - * One edge of the graph (only used by Graph constructor) - */ - public static class Edge { - public final String v1, v2; - public final int dist; - - public Edge(String v1, String v2, int dist) { - this.v1 = v1; - this.v2 = v2; - this.dist = dist; - } - } - - /** - * One vertex of the graph, complete with mappings to neighbouring vertices - */ - public static class Vertex implements Comparable { - public final String name; - // MAX_VALUE assumed to be infinity - public int dist = Integer.MAX_VALUE; - public Vertex previous = null; - public final Map neighbours = new HashMap<>(); - - public Vertex(String name) { - this.name = name; - } - - private void printPath() { - if (this == this.previous) { - System.out.printf("%s", this.name); - } else if (this.previous == null) { - System.out.printf("%s(unreached)", this.name); - } else { - this.previous.printPath(); - System.out.printf(" -> %s(%d)", this.name, this.dist); - } - } - - public int compareTo(Vertex other) { - if (dist == other.dist) - return name.compareTo(other.name); - - return Integer.compare(dist, other.dist); - } - - @Override - public String toString() { - return "(" + name + ", " + dist + ")"; - } - } - - /** - * Builds a graph from a set of edges - */ - public Graph(Edge[] edges) { - graph = new HashMap<>(edges.length); - - // one pass to find all vertices - for (Edge e : edges) { - if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); - if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); - } - - // another pass to set neighbouring vertices - for (Edge e : edges) { - graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); - // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph - } - } - - /** - * Runs dijkstra using a specified source vertex - */ - public void dijkstra(String startName) { - if (!graph.containsKey(startName)) { - System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); - return; - } - final Vertex source = graph.get(startName); - NavigableSet q = new TreeSet<>(); - - // set-up vertices - for (Vertex v : graph.values()) { - v.previous = v == source ? source : null; - v.dist = v == source ? 0 : Integer.MAX_VALUE; - q.add(v); - } - - dijkstra(q); - } - - /** - * Implementation of dijkstra's algorithm using a binary heap. - */ - private void dijkstra(final NavigableSet q) { - Vertex u, v; - while (!q.isEmpty()) { - // vertex with shortest distance (first iteration will return source) - u = q.pollFirst(); - if (u.dist == Integer.MAX_VALUE) - break; // we can ignore u (and any other remaining vertices) since they are unreachable - - // look at distances to each neighbour - for (Map.Entry a : u.neighbours.entrySet()) { - v = a.getKey(); // the neighbour in this iteration - - final int alternateDist = u.dist + a.getValue(); - if (alternateDist < v.dist) { // shorter path to neighbour found - q.remove(v); - v.dist = alternateDist; - v.previous = u; - q.add(v); - } - } - } - } - - /** - * Prints a path from the source to the specified vertex - */ - public void printPath(String endName) { - if (!graph.containsKey(endName)) { - System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); - return; - } - - graph.get(endName).printPath(); - System.out.println(); - } - - /** - * Prints the path from the source to every vertex (output order is not guaranteed) - */ - public void printAllPaths() { - for (Vertex v : graph.values()) { - v.printPath(); - System.out.println(); - } - } +package Others; + + +/** + * Dijkstra's algorithm,is a graph search algorithm that solves the single-source + * shortest path problem for a graph with nonnegative edge path costs, producing + * a shortest path tree. + *

+ * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting + * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node. + *

+ * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java + * Also most of the comments are from RosettaCode. + */ + +import java.util.*; + +public class Dijkstra { + private static final Graph.Edge[] GRAPH = { + // Distance from node "a" to node "b" is 7. + // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), + // a new edge would be needed for that + new Graph.Edge("a", "b", 7), + new Graph.Edge("a", "c", 9), + new Graph.Edge("a", "f", 14), + new Graph.Edge("b", "c", 10), + new Graph.Edge("b", "d", 15), + new Graph.Edge("c", "d", 11), + new Graph.Edge("c", "f", 2), + new Graph.Edge("d", "e", 6), + new Graph.Edge("e", "f", 9), + }; + private static final String START = "a"; + private static final String END = "e"; + + /** + * main function + * Will run the code with "GRAPH" that was defined above. + */ + public static void main(String[] args) { + Graph g = new Graph(GRAPH); + g.dijkstra(START); + g.printPath(END); + //g.printAllPaths(); + } +} + +class Graph { + // mapping of vertex names to Vertex objects, built from a set of Edges + private final Map graph; + + /** + * One edge of the graph (only used by Graph constructor) + */ + public static class Edge { + public final String v1, v2; + public final int dist; + + public Edge(String v1, String v2, int dist) { + this.v1 = v1; + this.v2 = v2; + this.dist = dist; + } + } + + /** + * One vertex of the graph, complete with mappings to neighbouring vertices + */ + public static class Vertex implements Comparable { + public final String name; + // MAX_VALUE assumed to be infinity + public int dist = Integer.MAX_VALUE; + public Vertex previous = null; + public final Map neighbours = new HashMap<>(); + + public Vertex(String name) { + this.name = name; + } + + private void printPath() { + if (this == this.previous) { + System.out.printf("%s", this.name); + } else if (this.previous == null) { + System.out.printf("%s(unreached)", this.name); + } else { + this.previous.printPath(); + System.out.printf(" -> %s(%d)", this.name, this.dist); + } + } + + public int compareTo(Vertex other) { + if (dist == other.dist) + return name.compareTo(other.name); + + return Integer.compare(dist, other.dist); + } + + @Override + public boolean equals(Object object) { + if (this == object) return true; + if (object == null || getClass() != object.getClass()) return false; + if (!super.equals(object)) return false; + + Vertex vertex = (Vertex) object; + + if (dist != vertex.dist) return false; + if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false; + if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) return false; + if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + dist; + result = 31 * result + (previous != null ? previous.hashCode() : 0); + result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "(" + name + ", " + dist + ")"; + } + } + + /** + * Builds a graph from a set of edges + */ + public Graph(Edge[] edges) { + graph = new HashMap<>(edges.length); + + // one pass to find all vertices + for (Edge e : edges) { + if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); + if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); + } + + // another pass to set neighbouring vertices + for (Edge e : edges) { + graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); + // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph + } + } + + /** + * Runs dijkstra using a specified source vertex + */ + public void dijkstra(String startName) { + if (!graph.containsKey(startName)) { + System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); + return; + } + final Vertex source = graph.get(startName); + NavigableSet q = new TreeSet<>(); + + // set-up vertices + for (Vertex v : graph.values()) { + v.previous = v == source ? source : null; + v.dist = v == source ? 0 : Integer.MAX_VALUE; + q.add(v); + } + + dijkstra(q); + } + + /** + * Implementation of dijkstra's algorithm using a binary heap. + */ + private void dijkstra(final NavigableSet q) { + Vertex u, v; + while (!q.isEmpty()) { + // vertex with shortest distance (first iteration will return source) + u = q.pollFirst(); + if (u.dist == Integer.MAX_VALUE) + break; // we can ignore u (and any other remaining vertices) since they are unreachable + + // look at distances to each neighbour + for (Map.Entry a : u.neighbours.entrySet()) { + v = a.getKey(); // the neighbour in this iteration + + final int alternateDist = u.dist + a.getValue(); + if (alternateDist < v.dist) { // shorter path to neighbour found + q.remove(v); + v.dist = alternateDist; + v.previous = u; + q.add(v); + } + } + } + } + + /** + * Prints a path from the source to the specified vertex + */ + public void printPath(String endName) { + if (!graph.containsKey(endName)) { + System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); + return; + } + + graph.get(endName).printPath(); + System.out.println(); + } + + /** + * Prints the path from the source to every vertex (output order is not guaranteed) + */ + public void printAllPaths() { + for (Vertex v : graph.values()) { + v.printPath(); + System.out.println(); + } + } + } \ No newline at end of file diff --git a/Others/TopKWords.java b/Others/TopKWords.java index 6cccfc27b95f..b3f0e5846b12 100644 --- a/Others/TopKWords.java +++ b/Others/TopKWords.java @@ -50,7 +50,8 @@ public Map getDictionary() { } finally { try { // you always have to close the I/O streams - fis.close(); + if (fis != null) + fis.close(); } catch (IOException e) { e.printStackTrace(); } diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java index 7d35ed36d54f..db31959558a3 100644 --- a/Others/TowerOfHanoi.java +++ b/Others/TowerOfHanoi.java @@ -12,7 +12,7 @@ public static void shift(int n, String startPole, String intermediatePole, Strin // 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 + 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); } diff --git a/Searches/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java index 8df51a7d789b..5a3a6d9e11cc 100644 --- a/Searches/IterativeBinarySearch.java +++ b/Searches/IterativeBinarySearch.java @@ -40,7 +40,7 @@ public > int find(T[] array, T key) { r = array.length - 1; while (l <= r) { - k = (l + r) / 2; + k = (l + r) >>> 1; cmp = key.compareTo(array[k]); if (cmp == 0) { diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index 47f79de0c35d..ef564ac722cb 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -64,7 +64,7 @@ private static > int randomPartition(T[] array, int left **/ private static > int partition(T[] array, int left, int right) { - int mid = (left + right) / 2; + int mid = (left + right) >>> 1; T pivot = array[mid]; while (left <= right) { diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java index cec0ddce0065..76893f45327e 100644 --- a/ciphers/Caesar.java +++ b/ciphers/Caesar.java @@ -125,6 +125,8 @@ public static void main(String[] args) { case 'D': case 'd': System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); + default: + System.out.println("default case"); } input.close(); } diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java index 26acc628e393..60af4ff5429c 100644 --- a/ciphers/ColumnarTranspositionCipher.java +++ b/ciphers/ColumnarTranspositionCipher.java @@ -117,7 +117,7 @@ private static Object[][] tableBuilder(String word) { * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { - if ((double) word.length() / keyword.length() > word.length() / keyword.length()) { + if (word.length() / keyword.length() > word.length() / keyword.length()) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java index 375d3e1a949c..67ebe89b8628 100644 --- a/divideconquer/ClosestPair.java +++ b/divideconquer/ClosestPair.java @@ -31,6 +31,15 @@ public final class ClosestPair { * Minimum point length. */ private static double minNum = Double.MAX_VALUE; + + public static void setMinNum(double minNum) { + ClosestPair.minNum = minNum; + } + + public static void setSecondCount(int secondCount) { + ClosestPair.secondCount = secondCount; + } + /** * secondCount */ @@ -213,7 +222,7 @@ public double closestPair(final Location[] a, final int indexNum) { for (int i = 0; i < totalNum; i++) { double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); if (xGap < minValue) { - secondCount++; // size of the array + ClosestPair.setSecondCount(secondCount + 1); // size of the array } else { if (divideArray[i].x > divideArray[divideX].x) { break; @@ -250,7 +259,7 @@ public double closestPair(final Location[] a, final int indexNum) { minValue = length; // Conditional for registering final coordinate if (length < minNum) { - minNum = length; + ClosestPair.setMinNum(length); point1 = firstWindow[i]; point2 = firstWindow[j]; } @@ -260,7 +269,7 @@ public double closestPair(final Location[] a, final int indexNum) { } } } - secondCount = 0; + ClosestPair.setSecondCount(0); return minValue; } @@ -288,7 +297,7 @@ public double bruteForce(final Location[] arrayParam) { length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // Conditional statement for registering final coordinate if (length < minNum) { - minNum = length; + ClosestPair.setMinNum(length); } point1 = arrayParam[0]; @@ -311,7 +320,7 @@ public double bruteForce(final Location[] arrayParam) { minValue = length; if (length < minNum) { // Registering final coordinate - minNum = length; + ClosestPair.setMinNum(length); point1 = arrayParam[i]; point2 = arrayParam[j]; } From f710f3aafac8be42219c1be4ed7dbfa03c878b4b Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:02:15 +0530 Subject: [PATCH 16/47] Update ListAddnFun --- DataStructures/Lists/ListAddnFun | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/DataStructures/Lists/ListAddnFun b/DataStructures/Lists/ListAddnFun index 47553e184358..afbd2ae431d8 100644 --- a/DataStructures/Lists/ListAddnFun +++ b/DataStructures/Lists/ListAddnFun @@ -1,3 +1,44 @@ +package DataStructures.Lists; + +/* + * This class implements a SinglyLinked List. + * A linked list is similar to an array, it hold values. + * However, links in a linked list do not have indexes. With + * a linked list you do not need to predetermine it's size as + * it grows and shrinks as it is edited. + *it has functions called mid that gives node at mid + * in addn to linked list there is algo that + * construct a linked list with alternate sums of linked list + * and added to new one and add mid value + * i.e sum of first and last value of inital list + + Test Case: + + + LinkedList LL1 = new LinkedList(); + Scanner scn=new Scanner(System.in); + int numNodes=scn.nextInt(); + for(int i=0;i<2*numNodes;i++) { + LL1.addLast(scn.nextInt()); + } + LL1.display(); + LinkedList LL2=new LinkedList(); + LL2.formLL2(LL1); + LL2.display(); + LinkedList LL3=new LinkedList(); + LL3.formLL3(LL1); + LL3.display(); + Node MID=LL1.midValue(); + System.out.println(MID.data); + LinkedList updLL1=new LinkedList(); + updLL1.formRes(LL1,LL2,LL3,MID); + updLL1.display(); + updLL1.Size(); + + */ + + + import java.util.*; import java.lang.*; import java.io.*; From 82e2132557bbf295f2f1d3b03bc41092bd736f78 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:06:36 +0530 Subject: [PATCH 17/47] Update AVLSimple --- DataStructures/Trees/AVLSimple | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/DataStructures/Trees/AVLSimple b/DataStructures/Trees/AVLSimple index 1f2c2bd6aba2..ace0c46b9374 100644 --- a/DataStructures/Trees/AVLSimple +++ b/DataStructures/Trees/AVLSimple @@ -1,3 +1,34 @@ + +package DataStructures.Trees; + +/* +* Avl is algo that balance itself while adding new alues to tree +* by rotating branches of binary tree and make itself Binary seaarch tree +* there are four cases which has to tackle +* rotating - left right ,left left,right right,right left + +Test Case: + +AVLTree tree=new AVLTree(); + tree.insert(20); + tree.insert(25); + tree.insert(30); + tree.insert(10); + tree.insert(5); + tree.insert(15); + tree.insert(27); + tree.insert(19); + tree.insert(16); + + tree.display(); + + + + +*/ + + + public class AVLTree { private class Node{ int data; From 920852aa0e41015a05fe72976675b4c439560bab Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:11:14 +0530 Subject: [PATCH 18/47] Update BoardPath --- DynamicProgramming/BoardPath | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath index 4b471a88ed64..91f1f011a6a0 100644 --- a/DynamicProgramming/BoardPath +++ b/DynamicProgramming/BoardPath @@ -1,4 +1,29 @@ +package DynamicProgramming.BoardPath; +/* +* this is an important Algo in which +* we have starting and ending of board and we have to reach +* we have to count no. of ways +* that help to reach end point i.e number by rolling dice +* which have 1 to 6 digits +Test Case: +here target is 10 + +int n=10; + startAlgo(); + System.out.println(bpR(0,n)); + System.out.println(endAlgo()+"ms"); + int[] strg=new int [n+1]; + startAlgo(); + System.out.println(bpRS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpIS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + + + +*/ public class BoardPath { public static long startTime; public static long endTime; From 94cfab0cfc060685c2f899d876b15be9cd279757 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:12:16 +0530 Subject: [PATCH 19/47] Update BoardPath --- DynamicProgramming/BoardPath | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath index 91f1f011a6a0..5ca14d1fab9b 100644 --- a/DynamicProgramming/BoardPath +++ b/DynamicProgramming/BoardPath @@ -1,4 +1,4 @@ -package DynamicProgramming.BoardPath; +package DynamicProgramming; /* * this is an important Algo in which * we have starting and ending of board and we have to reach From ec4f6a11102f9419eeaa36042fa265a95bf5e4e2 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:17:26 +0530 Subject: [PATCH 20/47] Update CountNumBinaryStrings --- DynamicProgramming/CountNumBinaryStrings | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/DynamicProgramming/CountNumBinaryStrings b/DynamicProgramming/CountNumBinaryStrings index c71fbd63c682..3dd0bf7ded9c 100644 --- a/DynamicProgramming/CountNumBinaryStrings +++ b/DynamicProgramming/CountNumBinaryStrings @@ -1,3 +1,31 @@ +package DynamicProgramming; +/* +* here is a important algo in this we have to count +* maximum no. of different binary strings which doesnot have +* consectuive 1s + + + +Test Case: + +int n=30; + + startAlgo(); + System.out.println(numStrIS(n)); + System.out.println(endAlgo()+"ms"); + + startAlgo(); + CountNumBinaryStr out=new CountNumBinaryStr(); + System.out.println(out.numStrR(n).ans); + System.out.println(endAlgo()+"ms"); + + startAlgo(); + System.out.println(countStrings(n,0)); + System.out.println(endAlgo()+"ms"); + + + +*/ public class CountNumBinaryStr { public static long startTime; public static long endTime; From a23a17ba6540818b266ad56a2fb181512dd4f1b5 Mon Sep 17 00:00:00 2001 From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com> Date: Mon, 25 May 2020 03:22:27 +0530 Subject: [PATCH 21/47] Update Intersection --- DataStructures/HashMap/Hashing/Intersection | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/DataStructures/HashMap/Hashing/Intersection b/DataStructures/HashMap/Hashing/Intersection index cfe1f74d73eb..8b54eeae1a95 100644 --- a/DataStructures/HashMap/Hashing/Intersection +++ b/DataStructures/HashMap/Hashing/Intersection @@ -1,3 +1,30 @@ +package DataStructures.HashMap.Hashing; +/* +* this is algo which implies common mathematical set theory concept +* called intersection in which result is common values of both the sets +* here metaphor of sets is HashMap + + +Test Case: + Scanner scn=new Scanner(System.in); + int len =scn.nextInt(); + int arr[]=new int[len]; + int arr2[]=new int[len]; + + for(int i=0;i<2*len;i++) { + + if(i=len) { + arr2[i-len]=scn.nextInt(); + } + } + System.out.println(Main(arr,arr2)); + + + +*/ + import java.util.ArrayList; import java.util.HashMap; import java.util.Map; From c76c4ddda7becf3c633323041f5128bcdb7d5e71 Mon Sep 17 00:00:00 2001 From: MohamedBechir <57349735+MohamedBechir@users.noreply.github.com> Date: Sun, 24 May 2020 23:00:46 +0100 Subject: [PATCH 22/47] Update CONTRIBUTING.md file I tried to update the CONTRIBUTING.md file in order to simplify as much as possible the process for the developers which will encourage them to join the project and hence enlarge our community. Thank you for putting it under review, if there are any changes feel free to ask me to do it. --- CONTRIBUTING.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d502de24281c..62f268c98f18 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,2 +1,25 @@ -## Contribution Guidelines -Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. +:+1::tada: Before guiding you through the contribution process TheAlgorithms/Java thank you for being one of us! :+1::tada: + +## How to contribute? + +#### **Did you find a bug?** + +* **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues). + +* If you are unable to find an open issue refering to the same problem, depending on the type of issue follow the appropriate steps: + +#### **Do you want to contribute to the documentation?** + +* Please read the documentation in here [Contributing to the Documentation]() ,[open a new one issue](https://github.com/TheAlgorithms/Java/issues/new), make changes and then create a pull request, it will be put under review and accepted if it is approprite. + +#### **Do you want to add a new feature?** +* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new). Be sure to include a **title and a clear description** and a **test case** demonstrating the new feature that you want to add to the project. + +#### **Do you want to fix a bug?** +* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new).Be sure to include a **title and a clear description** and a **test case** demonstrating the expected behaviour that is not occuring. + +#### **Do you have questions about the source code?** + +* Ask any question about how to use the repository in the [TheAlgorithms room in GITTER](https://gitter.im/TheAlgorithms/community?source=orgpage#) or [open a new one issue](https://github.com/TheAlgorithms/Java/issues/new) + +:+1::tada: That's all you need to know about the process now it's your turn to help us improve the repository, thank you again! :+1::tada: From 91b9ac759cff34e85e02ae17014bc55ab788cd4c Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 25 May 2020 11:36:04 +0000 Subject: [PATCH 23/47] updating DIRECTORY.md --- DIRECTORY.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index aee8eea6f2a2..d8a5165f015c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -45,9 +45,7 @@ * HashMap * Hashing * [HashMap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/HashMap.java) - * [LinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/LinkedList.java) * [Main](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Main.java) - * [Node](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Node.java) * Heaps * [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/EmptyHeapException.java) * [Heap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/Heap.java) From 8b6415f9b3c02ba3243061fd7637c581dcd4171e Mon Sep 17 00:00:00 2001 From: Sombit Bose Date: Mon, 25 May 2020 23:59:48 +0530 Subject: [PATCH 24/47] Update CONTRIBUTION.md Added some issue related to assignment of any particular algorithm --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 62f268c98f18..92a2dbf3e104 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,6 +6,8 @@ * **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues). +* Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request and it will be evaluated by project maintainers. + * If you are unable to find an open issue refering to the same problem, depending on the type of issue follow the appropriate steps: #### **Do you want to contribute to the documentation?** From 3b52109fc0d0ec43cbd21eecba0892353edac37a Mon Sep 17 00:00:00 2001 From: joshiujjawal22 Date: Fri, 29 May 2020 12:32:24 +0530 Subject: [PATCH 25/47] Added test cases --- Others/3 sum.java | 14 ++++++++++++- ...on of array without using extra space.java | 21 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Others/3 sum.java b/Others/3 sum.java index 3c008ff78360..577044aab1d2 100644 --- a/Others/3 sum.java +++ b/Others/3 sum.java @@ -11,6 +11,18 @@ * * @author Ujjawal Joshi * @date 2020.05.18 + * + * Test Cases: + Input: + * 6 //Length of array + 12 3 4 1 6 9 + target=24 + * Output:3 9 12 + * Explanation: There is a triplet (12, 3 and 9) present + in the array whose sum is 24. + * + * + */ @@ -26,7 +38,7 @@ public static void main(String args[]) { a[i]=sc.nextInt(); } - System.out.println("Number to be find"); + System.out.println("Target"); int n_find=sc.nextInt(); Arrays.sort(a); // Sort the array if array is not sorted diff --git a/Others/Rotation of array without using extra space.java b/Others/Rotation of array without using extra space.java index c25dbaefc8c9..76380be37300 100644 --- a/Others/Rotation of array without using extra space.java +++ b/Others/Rotation of array without using extra space.java @@ -8,6 +8,27 @@ * * @author Ujjawal Joshi * @date 2020.05.18 + * + * Test Cases: + + Input: + 2 //Size of matrix + 1 2 + 3 4 + Output: + 3 1 + 4 2 + ------------------------------ + Input: + 3 //Size of matrix + 1 2 3 + 4 5 6 + 7 8 9 + Output: + 7 4 1 + 8 5 2 + 9 6 3 + * */ class main{ From a6398d1d27c897009dbe55a057b6cfd81ee0da21 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 10:17:28 +0000 Subject: [PATCH 26/47] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d8a5165f015c..a4738bcc0b69 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -137,6 +137,7 @@ * [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/Misc/PalindromePrime.java) ## Others + * [3 sum](https://github.com/TheAlgorithms/Java/blob/master/Others/3%20sum.java) * [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java) * [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java) * [BestFit](https://github.com/TheAlgorithms/Java/blob/master/Others/BestFit.java) @@ -167,6 +168,7 @@ * [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java) * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseString.java) * [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/Others/RootPrecision.java) + * [Rotation of array without using extra space](https://github.com/TheAlgorithms/Java/blob/master/Others/Rotation%20of%20array%20without%20using%20extra%20space.java) * [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/Others/SieveOfEratosthenes.java) * [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java) * [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java) From e3a78a64000c1974a84287ac3129dd99857ecb19 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 1 Jun 2020 04:39:59 +0000 Subject: [PATCH 27/47] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index a4738bcc0b69..13651165369d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -193,6 +193,7 @@ * [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BitonicSort.java) * [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java) * [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java) + * [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BucketSort.java) * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java) * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java) * [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CountingSort.java) From b1caf8c6aea2bab16ce0117b8941b64b6834dde8 Mon Sep 17 00:00:00 2001 From: Swati Prajapati <42577922+swatiprajapati08@users.noreply.github.com> Date: Mon, 1 Jun 2020 23:41:32 +0530 Subject: [PATCH 28/47] Minimum sum partition Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. --- DynamicProgramming/Minimum sum partition | 64 ++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 DynamicProgramming/Minimum sum partition diff --git a/DynamicProgramming/Minimum sum partition b/DynamicProgramming/Minimum sum partition new file mode 100644 index 000000000000..2ab1d134cad2 --- /dev/null +++ b/DynamicProgramming/Minimum sum partition @@ -0,0 +1,64 @@ +// Partition a set into two subsets such that the difference of subset sums is minimum + +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG + { + public static void main (String[] args) + { + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(); + while(t-->0) + { + int n=sc.nextInt(); + int arr[]=new int[n]; + int sum=0; + for(int i=0;i Date: Wed, 3 Jun 2020 15:19:55 +0530 Subject: [PATCH 29/47] Update Minimum sum partition Added some test cases for better understanding. --- DynamicProgramming/Minimum sum partition | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/DynamicProgramming/Minimum sum partition b/DynamicProgramming/Minimum sum partition index 2ab1d134cad2..3763d5bd68a8 100644 --- a/DynamicProgramming/Minimum sum partition +++ b/DynamicProgramming/Minimum sum partition @@ -1,5 +1,19 @@ // Partition a set into two subsets such that the difference of subset sums is minimum +/* +Input: arr[] = {1, 6, 11, 5} +Output: 1 +Explanation: +Subset1 = {1, 5, 6}, sum of Subset1 = 12 +Subset2 = {11}, sum of Subset2 = 11 + +Input: arr[] = {36, 7, 46, 40} +Output: 23 +Explanation: +Subset1 = {7, 46} ; sum of Subset1 = 53 +Subset2 = {36, 40} ; sum of Subset2 = 76 + */ + import java.util.*; import java.lang.*; import java.io.*; From 7179718df290ccf0ecaaab044508aa309ffada8b Mon Sep 17 00:00:00 2001 From: lollerfirst <43107113+lollerfirst@users.noreply.github.com> Date: Tue, 9 Jun 2020 08:40:46 +0200 Subject: [PATCH 30/47] Update ParseInteger.java Fixed error for empty string. --- Maths/ParseInteger.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maths/ParseInteger.java b/Maths/ParseInteger.java index 91177bb49dd6..c9c11528c1dc 100644 --- a/Maths/ParseInteger.java +++ b/Maths/ParseInteger.java @@ -16,7 +16,7 @@ public static void main(String[] args) { * @throws NumberFormatException if the {@code string} does not contain a parsable integer. */ public static int parseInt(String s) { - if (s == null) { + if (s == null || s.length() == 0) { throw new NumberFormatException("null"); } boolean isNegative = s.charAt(0) == '-'; From 15536392f93d1c24d47c191ac1b67e0442666f23 Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Fri, 12 Jun 2020 13:16:52 +0200 Subject: [PATCH 31/47] marcosvillacanas-A-Star --- DataStructures/Graphs/A_Star.java | 158 ++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 DataStructures/Graphs/A_Star.java diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java new file mode 100644 index 000000000000..59ebd7aa5993 --- /dev/null +++ b/DataStructures/Graphs/A_Star.java @@ -0,0 +1,158 @@ +package A_Star; + +import java.util.*; + +public class A_Star { + + private static class Graph { + //Graph's structure can be changed only applying changes to this class. + private ArrayList [] graph; + + //Initialise ArrayLists in Constructor + public Graph(int size) { + this.graph = new ArrayList[size]; + for (int i = 0; i < size; i++) { + this.graph[i] = new ArrayList<>(); + } + } + + private ArrayList getNeighbours(int from) { return this.graph[from]; } + + //Graph is bidirectional, for just one direction remove second instruction of this method. + private void addEdge (Edge edge) { + this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); + this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); + } + + private void initializeGraph() { + this.addEdge(new Edge(0, 19, 75)); this.addEdge(new Edge(0, 15, 140)); + this.addEdge(new Edge(0, 16, 118)); this.addEdge(new Edge(19, 12, 71)); + this.addEdge(new Edge(12, 15, 151));this.addEdge(new Edge(16, 9, 111)); + this.addEdge(new Edge(9, 10, 70)); this.addEdge(new Edge(10, 3, 75)); + this.addEdge(new Edge(3, 2, 120)); this.addEdge(new Edge(2, 14, 146)); + this.addEdge(new Edge(2, 13, 138)); this.addEdge(new Edge(2, 6, 115)); + this.addEdge(new Edge(15, 14, 80)); this.addEdge(new Edge(15, 5, 99)); + this.addEdge(new Edge(14, 13, 97)); this.addEdge(new Edge(5, 1, 211)); + this.addEdge(new Edge(13, 1, 101)); this.addEdge(new Edge(6, 1, 160)); + this.addEdge(new Edge(1, 17, 85)); this.addEdge(new Edge(17, 7, 98)); + this.addEdge(new Edge(7, 4, 86)); this.addEdge(new Edge(17, 18, 142)); + this.addEdge(new Edge(18, 8, 92)); this.addEdge(new Edge(8, 11, 87)); + + /* + .x. node + (y) cost + - or | or / bidirectional connection + + ( 98)- .7. -(86)- .4. + | + ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. + | + . 1. -------------------- (160) + | \ | + (211) \ .6. + | \ | + . 5. (101)-.13. -(138) (115) + | | | / + ( 99) ( 97) | / + | | | / + .12. -(151)- .15. -(80)- .14. | / + | | | | / + ( 71) (140) (146)- .2. -(120) + | | | + .19. -( 75)- . 0. .10. -(75)- .3. + | | + (118) ( 70) + | | + .16. -(111)- .9. + */ + } + } + + private static class Edge { + private int from; + private int to; + private int weight; + + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } + + public int getFrom() { return from; } + + public int getTo() { return to; } + + public int getWeight() { return weight; } + } + + //class to iterate during the algorithm execution, and also used to return the solution. + private static class PathAndDistance { + private int distance; //distance advanced so far. + private ArrayList path; //list of visited nodes in this path. + private int estimated; //heuristic value associated to the last node od the path (current node). + + public PathAndDistance(int distance, ArrayList path, int estimated) { + this.distance = distance; + this.path = path; + this.estimated = estimated; + } + + public int getDistance() { return distance; } + + public ArrayList getPath() { return path; } + + public int getEstimated() { return estimated; } + + private void printSolution () { + if (this.path != null) + System.out.println("Optimal path: " + this.path.toString() + + ", distance: " + this.distance); + else + System.out.println("There is no path available to connect the points"); + } + } + + public static void main(String[] args) { + //heuristic function optimistic values + int[] heuristic = {366, 0, 160, 242, 161, 178, 77, 151, 226, + 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374}; + + Graph graph = new Graph(20); + graph.initializeGraph(); + + PathAndDistance solution = aStar(3, 1, graph, heuristic); + solution.printSolution(); + + } + + public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { + //nodes are prioritised by the less value of the current distance of their paths, and the estimated value + //given by the heuristic function to reach the destination point from the current point. + PriorityQueue queue = new PriorityQueue<> + (Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); + + //dummy data to start the algorithm from the beginning point + queue.add(new PathAndDistance(0, new ArrayList<>(Arrays.asList(from)), 0)); + + boolean solutionFound = false; + PathAndDistance currentData = new PathAndDistance(-1, null, -1); + while (!queue.isEmpty() && !solutionFound) { + currentData = queue.poll(); //first in the queue, best node so keep exploring. + int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); //current node. + if (currentPosition == to) + solutionFound = true; + else + for (Edge edge : graph.getNeighbours(currentPosition)) + if (!currentData.getPath().contains(edge.getTo())) { //Avoid Cycles + ArrayList updatedPath = new ArrayList<>(currentData.getPath()); + updatedPath.add(edge.getTo()); //Add the new node to the path, update the distance, + // and the heuristic function value associated to that path. + queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), + updatedPath, heuristic[edge.getTo()])); + } + } + return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); + //Out of while loop, if there is a solution, the current Data stores the optimal path, and its distance + } +} From ce945bc76b49bf7679f08d6f237fe5c7af7f5c21 Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Fri, 12 Jun 2020 13:23:15 +0200 Subject: [PATCH 32/47] Complexity Added --- DataStructures/Graphs/A_Star.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java index 59ebd7aa5993..c8c2db9c6263 100644 --- a/DataStructures/Graphs/A_Star.java +++ b/DataStructures/Graphs/A_Star.java @@ -1,3 +1,7 @@ +/* + Time Complexity = O(E), where E is equal to the number of edges +*/ + package A_Star; import java.util.*; From dd06589833e0117f3db2c196b82c0059c8107bba Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Wed, 17 Jun 2020 13:01:22 +0200 Subject: [PATCH 33/47] Kruskal Algorithm Implemented --- DataStructures/Graphs/Kruskal.java | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 DataStructures/Graphs/Kruskal.java diff --git a/DataStructures/Graphs/Kruskal.java b/DataStructures/Graphs/Kruskal.java new file mode 100644 index 000000000000..58b8d89eb5fa --- /dev/null +++ b/DataStructures/Graphs/Kruskal.java @@ -0,0 +1,94 @@ +package Kruskal; + +import java.util.Comparator; +import java.util.HashSet; +import java.util.PriorityQueue; + +public class Kruskal { + + //Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of vertices + + private static class Edge{ + private int from; + private int to; + private int weight; + + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } + } + + private static void addEdge (HashSet[] graph, int from, int to, int weight) { + graph[from].add(new Edge(from, to, weight)); + } + + public static void main(String[] args) { + HashSet[] graph = new HashSet[7]; + for (int i = 0; i < graph.length; i++) { + graph[i] = new HashSet<>(); + } + addEdge(graph,0, 1, 2); + addEdge(graph,0, 2, 3); + addEdge(graph,0, 3, 3); + addEdge(graph,1, 2, 4); + addEdge(graph,2, 3, 5); + addEdge(graph,1, 4, 3); + addEdge(graph,2, 4, 1); + addEdge(graph,3, 5, 7); + addEdge(graph,4, 5, 8); + addEdge(graph,5, 6, 9); + + System.out.println("Initial Graph: "); + for (int i = 0; i < graph.length; i++) { + for (Edge edge: graph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } + } + + Kruskal k = new Kruskal(); + HashSet[] solGraph = k.kruskal(graph); + + System.out.println("\nMinimal Graph: "); + for (int i = 0; i < solGraph.length; i++) { + for (Edge edge: solGraph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } + } + } + + public HashSet[] kruskal (HashSet[] graph) { + int nodes = graph.length; + int [] captain = new int [nodes]; + //captain of i, stores the set with all the connected nodes to i + HashSet[] connectedGroups = new HashSet[nodes]; + HashSet[] minGraph = new HashSet[nodes]; + PriorityQueue edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); + for (int i = 0; i < nodes; i++) { + minGraph[i] = new HashSet<>(); + connectedGroups[i] = new HashSet<>(); + connectedGroups[i].add(i); + captain[i] = i; + edges.addAll(graph[i]); + } + int connectedElements = 0; + //as soon as two sets merge all the elements, the algorithm must stop + while (connectedElements != nodes && !edges.isEmpty()) { + Edge edge = edges.poll(); + //This if avoids cycles + if (!connectedGroups[captain[edge.from]].contains(edge.to) + && !connectedGroups[captain[edge.to]].contains(edge.from)) { + //merge sets of the captains of each point connected by the edge + connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); + //update captains of the elements merged + connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); + //add Edge to minimal graph + addEdge(minGraph, edge.from, edge.to, edge.weight); + //count how many elements have been merged + connectedElements = connectedGroups[captain[edge.from]].size(); + } + } + return minGraph; + } +} From c21ae9acdb9807d5ed62bb97dc82df671e426bae Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Fri, 19 Jun 2020 18:10:49 +0200 Subject: [PATCH 34/47] Graph Initialization outside private classes --- DataStructures/Graphs/A_Star.java | 85 +++++++++++++++---------------- 1 file changed, 41 insertions(+), 44 deletions(-) diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java index c8c2db9c6263..9fa92ce32118 100644 --- a/DataStructures/Graphs/A_Star.java +++ b/DataStructures/Graphs/A_Star.java @@ -27,49 +27,6 @@ private void addEdge (Edge edge) { this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); } - - private void initializeGraph() { - this.addEdge(new Edge(0, 19, 75)); this.addEdge(new Edge(0, 15, 140)); - this.addEdge(new Edge(0, 16, 118)); this.addEdge(new Edge(19, 12, 71)); - this.addEdge(new Edge(12, 15, 151));this.addEdge(new Edge(16, 9, 111)); - this.addEdge(new Edge(9, 10, 70)); this.addEdge(new Edge(10, 3, 75)); - this.addEdge(new Edge(3, 2, 120)); this.addEdge(new Edge(2, 14, 146)); - this.addEdge(new Edge(2, 13, 138)); this.addEdge(new Edge(2, 6, 115)); - this.addEdge(new Edge(15, 14, 80)); this.addEdge(new Edge(15, 5, 99)); - this.addEdge(new Edge(14, 13, 97)); this.addEdge(new Edge(5, 1, 211)); - this.addEdge(new Edge(13, 1, 101)); this.addEdge(new Edge(6, 1, 160)); - this.addEdge(new Edge(1, 17, 85)); this.addEdge(new Edge(17, 7, 98)); - this.addEdge(new Edge(7, 4, 86)); this.addEdge(new Edge(17, 18, 142)); - this.addEdge(new Edge(18, 8, 92)); this.addEdge(new Edge(8, 11, 87)); - - /* - .x. node - (y) cost - - or | or / bidirectional connection - - ( 98)- .7. -(86)- .4. - | - ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. - | - . 1. -------------------- (160) - | \ | - (211) \ .6. - | \ | - . 5. (101)-.13. -(138) (115) - | | | / - ( 99) ( 97) | / - | | | / - .12. -(151)- .15. -(80)- .14. | / - | | | | / - ( 71) (140) (146)- .2. -(120) - | | | - .19. -( 75)- . 0. .10. -(75)- .3. - | | - (118) ( 70) - | | - .16. -(111)- .9. - */ - } } private static class Edge { @@ -117,13 +74,53 @@ private void printSolution () { } } + private static void initializeGraph(Graph graph, ArrayList data) { + for (int i = 0; i < data.size(); i+=4) { + graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); + } + /* + .x. node + (y) cost + - or | or / bidirectional connection + + ( 98)- .7. -(86)- .4. + | + ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. + | + . 1. -------------------- (160) + | \ | + (211) \ .6. + | \ | + . 5. (101)-.13. -(138) (115) + | | | / + ( 99) ( 97) | / + | | | / + .12. -(151)- .15. -(80)- .14. | / + | | | | / + ( 71) (140) (146)- .2. -(120) + | | | + .19. -( 75)- . 0. .10. -(75)- .3. + | | + (118) ( 70) + | | + .16. -(111)- .9. + */ + } + public static void main(String[] args) { //heuristic function optimistic values int[] heuristic = {366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374}; Graph graph = new Graph(20); - graph.initializeGraph(); + ArrayList graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, + 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, + 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, + 2, 14, 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, + 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, + 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, + 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); + initializeGraph(graph, graphData); PathAndDistance solution = aStar(3, 1, graph, heuristic); solution.printSolution(); From 5150a6bd875b24bf98ba693980e5d78a2be03a05 Mon Sep 17 00:00:00 2001 From: Hardik Kapadia Date: Tue, 30 Jun 2020 00:14:04 +0530 Subject: [PATCH 35/47] Closed Scanner in 3 sum, fixed syntax errors in BucketSort.java --- Others/3 sum.java | 2 +- Sorts/BucketSort.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Others/3 sum.java b/Others/3 sum.java index 577044aab1d2..5723ba49c34e 100644 --- a/Others/3 sum.java +++ b/Others/3 sum.java @@ -53,8 +53,8 @@ public static void main(String args[]) else r--; } } - + sc.close(); } } \ No newline at end of file diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java index 7556faf57406..1d2e94ff2d58 100644 --- a/Sorts/BucketSort.java +++ b/Sorts/BucketSort.java @@ -1,7 +1,8 @@ +package Sorts; import java.util.Random; -public class Bucket_Sort +public class BucketSort { static int[] sort(int[] sequence, int maxValue) { From d07e6680919d4bad06c7f687fa04895ec571face Mon Sep 17 00:00:00 2001 From: Hardik Kapadia Date: Tue, 30 Jun 2020 00:17:48 +0530 Subject: [PATCH 36/47] Fixed parameter error in SelectionSort --- Sorts/SelectionSort.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sorts/SelectionSort.java b/Sorts/SelectionSort.java index e6b7c8833f43..31b16c5bb171 100644 --- a/Sorts/SelectionSort.java +++ b/Sorts/SelectionSort.java @@ -10,10 +10,12 @@ public class SelectionSort implements SortAlgorithm { /** * This method swaps the two elements in the array + * @param * @param arr, i, j The array for the swap and the indexes of the to-swap elements */ - public void swap(T[] arr, int i, int j) { + + public void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; From 95389bf9c6252d184a5e3d13df8f80d2d4161413 Mon Sep 17 00:00:00 2001 From: Igor Kvashnin Date: Tue, 30 Jun 2020 22:44:38 +0300 Subject: [PATCH 37/47] Fixed wrong order in BubbleSort, corrected spelling mistakes --- Sorts/BubbleSort.java | 8 ++++---- Sorts/SortUtils.java | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java index 9d2f371786d8..7df1fae8a392 100644 --- a/Sorts/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -13,7 +13,7 @@ class BubbleSort implements SortAlgorithm { * This method implements the Generic Bubble Sort * * @param array The array to be sorted - * Sorts the array in increasing order + * Sorts the array in ascending order **/ @Override @@ -21,7 +21,7 @@ public > T[] sort(T[] array) { for (int i = 0, size = array.length; i < size - 1; ++i) { boolean swapped = false; for (int j = 0; j < size - 1 - i; ++j) { - if (less(array[j], array[j + 1])) { + if (greater(array[j], array[j + 1])) { swap(array, j, j + 1); swapped = true; } @@ -41,12 +41,12 @@ public static void main(String[] args) { BubbleSort bubbleSort = new BubbleSort(); bubbleSort.sort(integers); - // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1 + // Output => 1, 4, 6, 9, 12, 23, 54, 78, 231 print(integers); // String Input String[] strings = {"c", "a", "e", "b", "d"}; - //Output => e, d, c, b, a + //Output => a, b, c, d, e print(bubbleSort.sort(strings)); } diff --git a/Sorts/SortUtils.java b/Sorts/SortUtils.java index d5f592ad984d..334e3c1c1ad5 100644 --- a/Sorts/SortUtils.java +++ b/Sorts/SortUtils.java @@ -26,11 +26,11 @@ static boolean swap(T[] array, int idx, int idy) { /** - * This method checks if first element is less then the other element + * This method checks if first element is less than the other element * * @param v first element * @param w second element - * @return true if the first element is less then the second element + * @return true if the first element is less than the second element */ static > boolean less(T v, T w) { return v.compareTo(w) < 0; @@ -38,7 +38,19 @@ static > boolean less(T v, T w) { /** - * Just print list + * This method checks if first element is greater than the other element + * + * @param v first element + * @param w second element + * @return true if the first element is greater than the second element + */ + static > boolean greater(T v, T w) { + return v.compareTo(w) > 0; + } + + + /** + * Prints a list * * @param toPrint - a list which should be printed */ @@ -55,7 +67,7 @@ static void print(List toPrint) { /** * Prints an array * - * @param toPrint - the array which should be printed + * @param toPrint - an array which should be printed */ static void print(Object[] toPrint) { System.out.println(Arrays.toString(toPrint)); From bf0fdd735acd7d7c0ba5b090f930a0716fd44524 Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Mon, 6 Jul 2020 13:00:35 +0200 Subject: [PATCH 38/47] Context added --- DataStructures/Graphs/Kruskal.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/DataStructures/Graphs/Kruskal.java b/DataStructures/Graphs/Kruskal.java index 58b8d89eb5fa..82fdf3912842 100644 --- a/DataStructures/Graphs/Kruskal.java +++ b/DataStructures/Graphs/Kruskal.java @@ -1,4 +1,9 @@ -package Kruskal; +//Problem -> Connect all the edges with the minimum cost. +//Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the group of edges with the minimum sum of their weights that connect the whole graph. +//The graph needs to be connected, because if there are nodes impossible to reach, there are no edges that could connect every node in the graph. +//KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a Priority Queue is used, to take first those less weighted. +//This implementations below has some changes compared to conventional ones, but they are explained all along the code. +//In case you need to know anyhing else, I would be willing to answer all your doubts, you can contact me by https://www.linkedin.com/in/marcosvillacanas/ import java.util.Comparator; import java.util.HashSet; From 174b43caa58ea02c9823191a09575f9499d197a7 Mon Sep 17 00:00:00 2001 From: MarcosVillacanas Date: Mon, 6 Jul 2020 21:28:29 +0200 Subject: [PATCH 39/47] link-Removed --- DataStructures/Graphs/Kruskal.java | 1 - 1 file changed, 1 deletion(-) diff --git a/DataStructures/Graphs/Kruskal.java b/DataStructures/Graphs/Kruskal.java index 82fdf3912842..731b821be076 100644 --- a/DataStructures/Graphs/Kruskal.java +++ b/DataStructures/Graphs/Kruskal.java @@ -3,7 +3,6 @@ //The graph needs to be connected, because if there are nodes impossible to reach, there are no edges that could connect every node in the graph. //KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a Priority Queue is used, to take first those less weighted. //This implementations below has some changes compared to conventional ones, but they are explained all along the code. -//In case you need to know anyhing else, I would be willing to answer all your doubts, you can contact me by https://www.linkedin.com/in/marcosvillacanas/ import java.util.Comparator; import java.util.HashSet; From 6f0ea8d2272f66f381ca3417aba84c471df18738 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Tue, 7 Jul 2020 09:40:29 +0000 Subject: [PATCH 40/47] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 13651165369d..0d9d08a94d0e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -40,6 +40,7 @@ * [Cycles](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Cycles.java) * [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/FloydWarshall.java) * [Graphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Graphs.java) + * [Kruskal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Kruskal.java) * [MatrixGraphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/MatrixGraphs.java) * [PrimMST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/PrimMST.java) * HashMap From 4e058def8255f42d390f4179d2ed974086934fce Mon Sep 17 00:00:00 2001 From: Stepfen Shawn Date: Wed, 8 Jul 2020 17:00:56 +0800 Subject: [PATCH 41/47] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 80b5888a5165..d2a467239faa 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # The Algorithms - Java [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100) +[![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)  NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we're trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info. From 7a4d6b2544010d5a588fcb641cd900f10102654f Mon Sep 17 00:00:00 2001 From: vakhokoto Date: Sat, 11 Jul 2020 00:58:58 +0400 Subject: [PATCH 42/47] z function added --- Strings/ZFunction.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Strings/ZFunction.java diff --git a/Strings/ZFunction.java b/Strings/ZFunction.java new file mode 100644 index 000000000000..9872f26beff7 --- /dev/null +++ b/Strings/ZFunction.java @@ -0,0 +1,29 @@ +package Strings; + +public class ZFunction { + private String s; + + public ZFunction(String s){ + this.s = s; + } + + public int[] getArray(){ + int length = s.length(); + int[] z = new int[length]; + int l = 0, r = 0; + for (int i=0; i l && i <= r){ + z[i] = Math.min(z[i - l], r - i + 1); + } + while (i + z[i] < length && s.charAt(z[i]) == s.charAt(i + z[i])){ + z[i]++; + } + if (i + z[i] > r){ + l = i; + r = i + z[i] - 1; + } + } + + return z; + } +} From b8fa50480291911dabb3d3c0635f0aec5aec74a6 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 16 Jul 2020 11:54:01 +0000 Subject: [PATCH 43/47] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 0d9d08a94d0e..e50e18eaf647 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -35,6 +35,7 @@ * DynamicArray * [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/DynamicArray/DynamicArray.java) * Graphs + * [A Star](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/A_Star.java) * [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/BellmanFord.java) * [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/ConnectedComponent.java) * [Cycles](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Cycles.java) From a983a15b62c0f98b626c6ebc194ecbf950aa369a Mon Sep 17 00:00:00 2001 From: vakhokoto Date: Wed, 22 Jul 2020 12:52:54 +0400 Subject: [PATCH 44/47] description added and also link to the algorithm review --- Strings/ZFunction.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Strings/ZFunction.java b/Strings/ZFunction.java index 9872f26beff7..f9ca97d6b24d 100644 --- a/Strings/ZFunction.java +++ b/Strings/ZFunction.java @@ -1,21 +1,25 @@ +// Initialisation of strings algorithm Z function +// detailed review and proper examples can be seen on the link bewlow +// +// Link of algorithm review: https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/ package Strings; public class ZFunction { - private String s; + private String string; - public ZFunction(String s){ - this.s = s; + public ZFunction(String string){ + this.string = string; } public int[] getArray(){ - int length = s.length(); + int length = string.length(); int[] z = new int[length]; int l = 0, r = 0; for (int i=0; i l && i <= r){ z[i] = Math.min(z[i - l], r - i + 1); } - while (i + z[i] < length && s.charAt(z[i]) == s.charAt(i + z[i])){ + while (i + z[i] < length && string.charAt(z[i]) == string.charAt(i + z[i])){ z[i]++; } if (i + z[i] > r){ From 5e8c8c7476112a497087ccb5037eedd069ba5050 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 22 Jul 2020 17:53:38 +0000 Subject: [PATCH 45/47] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index e50e18eaf647..acbef75630d2 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -211,3 +211,6 @@ * [ShellSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/ShellSort.java) * [SortAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortAlgorithm.java) * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java) + +## Strings + * [ZFunction](https://github.com/TheAlgorithms/Java/blob/master/Strings/ZFunction.java) From 6e7a326f75e6d74b22ce14ceca5f9a137e6bde43 Mon Sep 17 00:00:00 2001 From: Sombit Bose Date: Wed, 22 Jul 2020 23:29:09 +0530 Subject: [PATCH 46/47] Revert "z function added" --- Strings/ZFunction.java | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 Strings/ZFunction.java diff --git a/Strings/ZFunction.java b/Strings/ZFunction.java deleted file mode 100644 index f9ca97d6b24d..000000000000 --- a/Strings/ZFunction.java +++ /dev/null @@ -1,33 +0,0 @@ -// Initialisation of strings algorithm Z function -// detailed review and proper examples can be seen on the link bewlow -// -// Link of algorithm review: https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/ -package Strings; - -public class ZFunction { - private String string; - - public ZFunction(String string){ - this.string = string; - } - - public int[] getArray(){ - int length = string.length(); - int[] z = new int[length]; - int l = 0, r = 0; - for (int i=0; i l && i <= r){ - z[i] = Math.min(z[i - l], r - i + 1); - } - while (i + z[i] < length && string.charAt(z[i]) == string.charAt(i + z[i])){ - z[i]++; - } - if (i + z[i] > r){ - l = i; - r = i + z[i] - 1; - } - } - - return z; - } -} From c4a8f71c122bbbe38e4502e8b87dedf432977541 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 22 Jul 2020 17:59:28 +0000 Subject: [PATCH 47/47] updating DIRECTORY.md --- DIRECTORY.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index acbef75630d2..e50e18eaf647 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -211,6 +211,3 @@ * [ShellSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/ShellSort.java) * [SortAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortAlgorithm.java) * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java) - -## Strings - * [ZFunction](https://github.com/TheAlgorithms/Java/blob/master/Strings/ZFunction.java)