├── CODE_OF_CONDUCT.md ├── NumberOfDigit.java ├── Programs ├── ADTFractionApp.java ├── Anagram.java ├── BFS.java ├── BellmanFord.java ├── BinarySearch.java ├── BinaryTreeInorder.java ├── BreathFirstSearch.java ├── BubbleSort.java ├── BucketSort.java ├── Calculator.java ├── CeaserCipher.java ├── CeilingFloor.java ├── Check_If_Sorted.java ├── Circular Integer LinkedList │ ├── Main.java │ ├── Node.java │ └── circularLinkedList.java ├── Circular_Queue.java ├── CombinationCoinChange.java ├── ComplexNosOps.java ├── CountingSort.java ├── DFS.java ├── Decimal_to_Binary.java ├── DepthFirstSearch.java ├── Dijkstra.java ├── ExponentialSearch.java ├── FactorialDemo.java ├── Factory Method │ ├── Car.java │ ├── CarFactory.java │ ├── HatchbackCar.java │ ├── HatchbackCarFactory.java │ ├── SUVCar.java │ ├── SUVCarFactory.java │ ├── SedanCar.java │ ├── SedanCarFactory.java │ └── TestFactoryPattern.java ├── Fibonacci.java ├── FindIndexValue.java ├── Floyd_Warshall_Algorithm.java ├── ForLoop.java ├── FordFulkerson.java ├── FunctionalInterfaces.java ├── Games │ ├── GuessTheNumber.java │ ├── HangMan.java │ ├── MaximumSubArraySum.java │ ├── Snake Game with Different Playing Features and GUI │ │ ├── GameFrame.java │ │ ├── GamePanel.java │ │ ├── README.md │ │ └── SnakeGamer.java │ └── peg-solitaire │ │ ├── 1.png │ │ ├── 2.png │ │ ├── 3.png │ │ ├── 4.png │ │ ├── 5.png │ │ ├── 6.png │ │ ├── Main.java │ │ ├── PegSolitaire.java │ │ └── PegSolitaireGame.java ├── GenClassMethod.java ├── Gssarray.java ├── HeapSort.java ├── HttpsRequest.java ├── HuffmanCoding.java ├── IncomeTaxCalculator.java ├── InsertionSort.java ├── IntegerToWord.java ├── InterpolationSearch.java ├── JavaClasses.java ├── JavaStreams.java ├── KMP.java ├── KnapSack.java ├── Kruskal.java ├── LinearSearch.java ├── LongestCommonSubsequence.java ├── LuckyNumber.java ├── MatrixAdd.java ├── Mcolor.java ├── MergeKsortedLists.java ├── MergeSort.java ├── MultipleInheritance.java ├── NoDupArray.java ├── NumberToRoman.java ├── Overriding.java ├── Palindrome.java ├── PrimsAlgorithm.java ├── PrintPattern.java ├── QuickSort.java ├── RabinKarp.java ├── RemoveloopinLinkedList.java ├── ReverseList.java ├── ReverseString.java ├── RockPaperScissor.java ├── RotateLinkedList.java ├── SelectionSort.java ├── ShellSort.java ├── Sieve_Of_Eratosthenes.java ├── SortNonBoundary.java ├── Soundex.java ├── SquareEveryDigit.java ├── Stack.java ├── StaticCount.java ├── StaticMemberFunctions.java ├── StrassensMultiplication.java ├── StudentInterface.java ├── SumOfArrayNos.java ├── Swing_Simple_Registration_Form.java ├── SwitchCase.java ├── SwitchingLetters.java ├── ThisPointerExplicit.java ├── ThisPointerImplicit.java ├── TicTacToe.java ├── ToDoList.java ├── Trie_Implementation.java ├── TwoDArrays.java ├── TwoElementsOccurOnceWhileOthersOccurTwice.java ├── Two_Sum.java ├── WashingMachine │ ├── Lavadora.java │ └── LavadoraImplementada.java ├── WiggleSorting.java ├── Xorpalindrome.java ├── abstractClass.java ├── areaRect.java ├── arithExceptions.java ├── arrayLists.java ├── arrayOutOfBounds.java ├── bankSystem.java ├── bookShop.java ├── constructors.java ├── derivedConstructor.java ├── eduEmpDb.java ├── eduInstitute.java ├── excHandling.java ├── excThrow.java ├── factoflargenum.java ├── fibo.java ├── genProg.java ├── helloWorld.java ├── input.java ├── integers.java ├── isValidPerfectSquare.java ├── kadane.java ├── largestNum.java ├── list_1.java ├── matrix │ └── Matrix_Multiply.java ├── nestedTry.java ├── overloading.java ├── patterns │ ├── Pattern1.java │ ├── Pattern2.java │ ├── Pattern3.java │ ├── Pattern4.java │ ├── Pattern5.java │ ├── Pattern6.java │ ├── Pattern7.java │ ├── Pattern8.java │ ├── Pattern9.java │ └── README.md ├── primeNumbers.java └── seive.java ├── README.md ├── mersenneprime.java └── palindrome.java /NumberOfDigit.java: -------------------------------------------------------------------------------- 1 | // This program demonstrates a new and most efficient way to calculate number of digits by using logarithmic functions 2 | /* the normal and most used algorithm to calculate number of digits is 3 | while(num>0){ 4 | numberOfDigits=num%10; 5 | numberOfDigits++; 6 | num=num%10; 7 | } 8 | this algorithm has a time complexity of O(n) 9 | we can simply calculate it by log(number)+1. 10 | here is the code for it :- */ 11 | import java.util.*; 12 | 13 | class NumberOfDigit 14 | { 15 | public static void main(String args[]) 16 | { 17 | int num=356, digits=0; 18 | digits = (int)Math.log10(num) + 1; 19 | System.out.println(digits); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Programs/ADTFractionApp.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | public class ADTFractionApp { 5 | 6 | /** 7 | * @param args the command line arguments 8 | */ 9 | public static void main(String[] args) { 10 | ADTFraction f1=new ADTFraction(3,5); 11 | f1.display(); 12 | ADTFraction f2=new ADTFraction(7,8); 13 | f2.display(); 14 | } 15 | 16 | } 17 | 18 | 19 | class ADTFraction { 20 | private int n; //numerator 21 | private int d; //denomenator 22 | //--------------------------------------------------- 23 | public ADTFraction() {//default constructor 24 | this.n=0; 25 | this.d=1; 26 | } 27 | //--------------------------------------------------- 28 | public ADTFraction(int a, int b) {//parameter constructor 29 | 30 | if(b!=0){ 31 | this.d=b; 32 | this.n=a; 33 | } 34 | else{ 35 | this.n=0; 36 | this.d=1; 37 | System.out.println("Denomenator cannot be Zero"); 38 | } 39 | 40 | 41 | } 42 | //--------------------------------------------------- 43 | public void set(int a, int b) {//set numerator and denomenator 44 | if(b!=0){ 45 | this.d=b; 46 | this.n=a; 47 | } 48 | else{ 49 | this.n=0; 50 | this.d=1; 51 | System.out.println("Denomenator cannot be Zero"); 52 | } 53 | } 54 | 55 | 56 | 57 | //--------------------------------------------------- 58 | public ADTFraction plus(ADTFraction x) {//add two fractions this=3/5 x=7/8 59 | int num, den; 60 | den=this.d * x.d; 61 | num=this.n * x.d + x.n * this.d; 62 | ADTFraction f1 = new ADTFraction(num,den); 63 | return f1; 64 | } 65 | 66 | 67 | //--------------------------------------------------- 68 | public ADTFraction times(int a) {//multiply fraction by a number 69 | int num, den; 70 | den=this.d; 71 | num=this.n * a; 72 | 73 | ADTFraction f1 = new ADTFraction(num,den); 74 | return f1; 75 | 76 | //return times(new ADTFraction(a,1)) 77 | 78 | } 79 | 80 | 81 | //--------------------------------------------------- 82 | public ADTFraction times(ADTFraction x) {//multiply two fractions 83 | int num, den; 84 | den=this.d * x.d; 85 | num=this.n * x.n; 86 | 87 | ADTFraction f1 = new ADTFraction(num,den); 88 | return f1; 89 | } 90 | 91 | 92 | //--------------------------------------------------- 93 | public ADTFraction reciprocal() {//reciprocal of a fraction 94 | ADTFraction f1=new ADTFraction(this.d,this.n); 95 | return f1; 96 | } 97 | 98 | 99 | //--------------------------------------------------- 100 | public float value() {//numerical value of a fraction 101 | return (float)this.n/this.d; 102 | } 103 | 104 | 105 | //--------------------------------------------------- 106 | public void display() {//display the fraction in the format n/d 107 | System.out.println(this.n + "/" + this.d); 108 | } 109 | //--------------------------------------------------- 110 | 111 | } -------------------------------------------------------------------------------- /Programs/Anagram.java: -------------------------------------------------------------------------------- 1 | // JAVA program to check if two strings 2 | // are anagrams of each other 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class Anagram { 7 | 8 | static int NO_OF_CHARS = 256; 9 | 10 | /* function to check whether two strings 11 | are anagram of each other */ 12 | static boolean areAnagram(char str1[], char str2[]) 13 | { 14 | // Create 2 count arrays and initialize 15 | // all values as 0 16 | int count1[] = new int[NO_OF_CHARS]; 17 | Arrays.fill(count1, 0); 18 | int count2[] = new int[NO_OF_CHARS]; 19 | Arrays.fill(count2, 0); 20 | int i; 21 | 22 | // For each character in input strings, 23 | // increment count in the corresponding 24 | // count array 25 | for (i = 0; i < str1.length && i < str2.length; 26 | i++) { 27 | count1[str1[i]]++; 28 | count2[str2[i]]++; 29 | } 30 | 31 | // If both strings are of different length. 32 | // Removing this condition will make the program 33 | // fail for strings like "aaca" and "aca" 34 | if (str1.length != str2.length) 35 | return false; 36 | 37 | // Compare count arrays 38 | for (i = 0; i < NO_OF_CHARS; i++) 39 | if (count1[i] != count2[i]) 40 | return false; 41 | 42 | return true; 43 | } 44 | 45 | /* Driver code*/ 46 | public static void main(String args[]) 47 | { 48 | char str1[] = ("gram").toCharArray(); 49 | char str2[] = ("arm").toCharArray(); 50 | 51 | // Function call 52 | if (areAnagram(str1, str2)) 53 | System.out.println("The two strings are" 54 | + " anagram of each other"); 55 | else 56 | System.out.println("The two strings are not" 57 | + " anagram of each other"); 58 | } 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /Programs/BFS.java: -------------------------------------------------------------------------------- 1 | // bfs - for unweighted connected graph 2 | 3 | package project0; 4 | 5 | import java.util.Arrays; 6 | import java.util.Iterator; 7 | import java.util.LinkedList; 8 | import java.util.Queue; 9 | 10 | class Graph { 11 | private int v; // total number of vertices 12 | private LinkedList adj[]; // adjacency list 13 | private boolean visited[]; 14 | 15 | Graph(int v) { 16 | this.v = v; 17 | this.adj = new LinkedList[v]; 18 | this.visited = new boolean[v]; 19 | for (int i = 0; i < this.v; i++) { 20 | adj[i] = new LinkedList(); 21 | } 22 | 23 | } 24 | 25 | public void addEdge(int u, int v) { // edge from u -> v 26 | this.adj[u].add(v); 27 | } 28 | 29 | public void BFS(int source) { 30 | Queue queue = new LinkedList(); 31 | 32 | queue.add(source); 33 | visited[source] = true; 34 | 35 | while (!queue.isEmpty()) { 36 | 37 | int currNode = queue.poll(); 38 | System.out.print(currNode + " "); 39 | 40 | for (int next : this.adj[currNode]) { 41 | if (!visited[next]) { 42 | visited[next] = true; 43 | queue.add(next); 44 | } 45 | } 46 | } 47 | } 48 | 49 | public void BFS_end() { 50 | 51 | } 52 | 53 | } 54 | 55 | public class Main { 56 | public static void main(String args[]) { 57 | 58 | Graph g = new Graph(4); 59 | 60 | g.addEdge(0, 1); 61 | g.addEdge(0, 2); 62 | g.addEdge(1, 2); 63 | g.addEdge(2, 0); 64 | g.addEdge(2, 3); 65 | g.addEdge(3, 3); 66 | 67 | g.BFS(0); 68 | 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Programs/BellmanFord.java: -------------------------------------------------------------------------------- 1 | // Bellman Ford Algorithm in Java 2 | 3 | class CreateGraph { 4 | 5 | // CreateGraph - it consists of edges 6 | class CreateEdge { 7 | int s, d, w; 8 | 9 | CreateEdge() { 10 | s = d = w = 0; 11 | } 12 | }; 13 | 14 | int V, E; 15 | CreateEdge edge[]; 16 | 17 | // Creates a graph with V vertices and E edges 18 | CreateGraph(int v, int e) { 19 | V = v; 20 | E = e; 21 | edge = new CreateEdge[e]; 22 | for (int i = 0; i < e; ++i) 23 | edge[i] = new CreateEdge(); 24 | } 25 | 26 | void BellmanFord(CreateGraph graph, int s) { 27 | int V = graph.V, E = graph.E; 28 | int dist[] = new int[V]; 29 | 30 | // Step 1: fill the distance array and predecessor array 31 | for (int i = 0; i < V; ++i) 32 | dist[i] = Integer.MAX_VALUE; 33 | 34 | // Mark the source vertex 35 | dist[s] = 0; 36 | 37 | // Step 2: relax edges |V| - 1 times 38 | for (int i = 1; i < V; ++i) { 39 | for (int j = 0; j < E; ++j) { 40 | // Get the edge data 41 | int u = graph.edge[j].s; 42 | int v = graph.edge[j].d; 43 | int w = graph.edge[j].w; 44 | if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) 45 | dist[v] = dist[u] + w; 46 | } 47 | } 48 | 49 | // Step 3: detect negative cycle 50 | // if value changes then we have a negative cycle in the graph 51 | // and we cannot find the shortest distances 52 | for (int j = 0; j < E; ++j) { 53 | int u = graph.edge[j].s; 54 | int v = graph.edge[j].d; 55 | int w = graph.edge[j].w; 56 | if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { 57 | System.out.println("CreateGraph contains negative w cycle"); 58 | return; 59 | } 60 | } 61 | 62 | // No negative w cycle found! 63 | // Print the distance and predecessor array 64 | printSolution(dist, V); 65 | } 66 | 67 | // Print the solution 68 | void printSolution(int dist[], int V) { 69 | System.out.println("Vertex Distance from Source"); 70 | for (int i = 0; i < V; ++i) 71 | System.out.println(i + "\t\t" + dist[i]); 72 | } 73 | 74 | public static void main(String[] args) { 75 | int V = 5; // Total vertices 76 | int E = 8; // Total Edges 77 | 78 | CreateGraph graph = new CreateGraph(V, E); 79 | 80 | // edge 0 --> 1 81 | graph.edge[0].s = 0; 82 | graph.edge[0].d = 1; 83 | graph.edge[0].w = 5; 84 | 85 | // edge 0 --> 2 86 | graph.edge[1].s = 0; 87 | graph.edge[1].d = 2; 88 | graph.edge[1].w = 4; 89 | 90 | // edge 1 --> 3 91 | graph.edge[2].s = 1; 92 | graph.edge[2].d = 3; 93 | graph.edge[2].w = 3; 94 | 95 | // edge 2 --> 1 96 | graph.edge[3].s = 2; 97 | graph.edge[3].d = 1; 98 | graph.edge[3].w = 6; 99 | 100 | // edge 3 --> 2 101 | graph.edge[4].s = 3; 102 | graph.edge[4].d = 2; 103 | graph.edge[4].w = 2; 104 | 105 | graph.BellmanFord(graph, 0); // 0 is the source vertex 106 | } 107 | } -------------------------------------------------------------------------------- /Programs/BinarySearch.java: -------------------------------------------------------------------------------- 1 | // Java implementation of recursive Binary Search 2 | import java.util.*; 3 | class BinarySearch { 4 | // Returns index of target if it is present in arr else return -1 5 | int binarySearch(int arr[], int first, int last, int target) 6 | { 7 | if (last >= first) { 8 | int mid = first + (last - first) / 2; 9 | 10 | // if element is present in the middle 11 | if (arr[mid] == target) 12 | return mid; 13 | 14 | // If element is smaller than mid, then it can only be present in first subarray 15 | if (target < arr[mid]) 16 | return binarySearch(arr, first, mid - 1, target); 17 | 18 | // Else the element can only be present in the second subarray 19 | return binarySearch(arr, mid + 1, last, target); 20 | } 21 | 22 | // We reach here when element is not present 23 | // in array 24 | return -1; 25 | } 26 | 27 | // Driver method to test above 28 | public static void main(String args[]) 29 | { 30 | BinarySearch ob = new BinarySearch(); 31 | Scanner kb = new Scanner(System.in); 32 | int n = kb.nextInt(); 33 | int arr[] = new int[n]; 34 | for(int i=0;i inOrder(Node root) { 6 | 7 | //New ArrayList to return 8 | ArrayList li = new ArrayList(); 9 | 10 | travel(root, li); 11 | 12 | return li; 13 | } 14 | 15 | public static void travel(Node root, ArrayList ans) 16 | { 17 | if(root==null) return; 18 | 19 | //if there is node on left, go there 20 | if(root.left!=null)travel(root.left,ans); 21 | //add the element to list 22 | ans.add(root.data); 23 | //if there is node on right, go there 24 | if(root.right!=null)travel(root.right,ans); 25 | } 26 | } 27 | //Time Complexity : o(n) 28 | //Space Complexity : o(n) 29 | 30 | //Driver Code to test the Above Class 31 | import java.util.LinkedList; 32 | import java.util.Queue; 33 | import java.io.*; 34 | import java.util.*; 35 | 36 | class Node { 37 | int data; 38 | Node left; 39 | Node right; 40 | Node(int data) { 41 | this.data = data; 42 | left = null; 43 | right = null; 44 | } 45 | } 46 | 47 | class GfG { 48 | 49 | static Node buildTree(String str) { 50 | 51 | if (str.length() == 0 || str.charAt(0) == 'N') { 52 | return null; 53 | } 54 | 55 | String ip[] = str.split(" "); 56 | // Create the root of the tree 57 | Node root = new Node(Integer.parseInt(ip[0])); 58 | // Push the root to the queue 59 | 60 | Queue queue = new LinkedList<>(); 61 | 62 | queue.add(root); 63 | // Starting from the second element 64 | 65 | int i = 1; 66 | while (queue.size() > 0 && i < ip.length) { 67 | 68 | // Get and remove the front of the queue 69 | Node currNode = queue.peek(); 70 | queue.remove(); 71 | 72 | // Get the current node's value from the string 73 | String currVal = ip[i]; 74 | 75 | // If the left child is not null 76 | if (!currVal.equals("N")) { 77 | 78 | // Create the left child for the current node 79 | currNode.left = new Node(Integer.parseInt(currVal)); 80 | // Push it to the queue 81 | queue.add(currNode.left); 82 | } 83 | 84 | // For the right child 85 | i++; 86 | if (i >= ip.length) break; 87 | 88 | currVal = ip[i]; 89 | 90 | // If the right child is not null 91 | if (!currVal.equals("N")) { 92 | 93 | // Create the right child for the current node 94 | currNode.right = new Node(Integer.parseInt(currVal)); 95 | 96 | // Push it to the queue 97 | queue.add(currNode.right); 98 | } 99 | i++; 100 | } 101 | 102 | return root; 103 | } 104 | 105 | public static void main(String[] args) throws IOException { 106 | BufferedReader br = 107 | new BufferedReader(new InputStreamReader(System.in)); 108 | 109 | int t = Integer.parseInt(br.readLine()); 110 | 111 | while (t > 0) { 112 | String s = br.readLine(); 113 | Node root = buildTree(s); 114 | Solution g = new Solution(); 115 | ArrayList res = g.inOrder(root); 116 | for (int i = 0; i < res.size(); i++) 117 | System.out.print(res.get(i) + " "); 118 | System.out.print("\n"); 119 | t--; 120 | } 121 | } 122 | } -------------------------------------------------------------------------------- /Programs/BreathFirstSearch.java: -------------------------------------------------------------------------------- 1 | // BFS algorithm in Java 2 | 3 | import java.util.*; 4 | 5 | public class Graph { 6 | private int V; 7 | private LinkedList adj[]; 8 | 9 | // Create a graph 10 | Graph(int v) { 11 | V = v; 12 | adj = new LinkedList[v]; 13 | for (int i = 0; i < v; ++i) 14 | adj[i] = new LinkedList(); 15 | } 16 | 17 | // Add edges to the graph 18 | void addEdge(int v, int w) { 19 | adj[v].add(w); 20 | } 21 | 22 | // BFS algorithm 23 | void BFS(int s) { 24 | 25 | boolean visited[] = new boolean[V]; 26 | 27 | LinkedList queue = new LinkedList(); 28 | 29 | visited[s] = true; 30 | queue.add(s); 31 | 32 | while (queue.size() != 0) { 33 | s = queue.poll(); 34 | System.out.print(s + " "); 35 | 36 | Iterator i = adj[s].listIterator(); 37 | while (i.hasNext()) { 38 | int n = i.next(); 39 | if (!visited[n]) { 40 | visited[n] = true; 41 | queue.add(n); 42 | } 43 | } 44 | } 45 | } 46 | 47 | public static void main(String args[]) { 48 | Graph g = new Graph(4); 49 | 50 | g.addEdge(0, 1); 51 | g.addEdge(0, 2); 52 | g.addEdge(1, 2); 53 | g.addEdge(2, 0); 54 | g.addEdge(2, 3); 55 | g.addEdge(3, 3); 56 | 57 | System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)"); 58 | 59 | g.BFS(2); 60 | } 61 | } -------------------------------------------------------------------------------- /Programs/BubbleSort.java: -------------------------------------------------------------------------------- 1 | // Program to sort an array in Java (using bubble sort) - 2 | public class BubbleSort { 3 | public static void main(String[] args) { 4 | int arr[] = {10, 45, 15, 13, 54}; // Initializing an array 5 | int temp; 6 | // Two for loops to traverse the array - 7 | for (int i = 0; i < arr.length - 1; i++) { 8 | for (int j = i + 1; j < arr.length; j++) { 9 | // check if element is greater - 10 | if (arr[i] > arr[j]) { 11 | temp = arr[i]; // assign arr[i] element to temp position 12 | arr[i] = arr[j]; // assign arr[j] element to arr[i] position 13 | arr[j] = temp; // assign temp value to arr[j] position 14 | } 15 | } 16 | } 17 | System.out.println("Sorted array: "); 18 | // For loop to print the sorted array - 19 | for (int i = 0; i < arr.length; i++) { 20 | System.out.println(arr[i]); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Programs/BucketSort.java: -------------------------------------------------------------------------------- 1 | // Bucket sort in Java 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | 5 | public class BucketSort { 6 | public void bucketSort(float[] arr, int n) { 7 | if (n <= 0) 8 | return; 9 | @SuppressWarnings("unchecked") 10 | ArrayList[] bucket = new ArrayList[n]; 11 | 12 | // Create empty buckets 13 | for (int i = 0; i < n; i++) 14 | bucket[i] = new ArrayList(); 15 | 16 | // Add elements into the buckets 17 | for (int i = 0; i < n; i++) { 18 | int bucketIndex = (int) arr[i] * n; 19 | bucket[bucketIndex].add(arr[i]); 20 | } 21 | 22 | // Sort the elements of each bucket 23 | for (int i = 0; i < n; i++) { 24 | Collections.sort((bucket[i])); 25 | } 26 | 27 | // Get the sorted array 28 | int index = 0; 29 | for (int i = 0; i < n; i++) { 30 | for (int j = 0, size = bucket[i].size(); j < size; j++) { 31 | arr[index++] = bucket[i].get(j); 32 | } 33 | } 34 | } 35 | 36 | // Driver code 37 | public static void main(String[] args) { 38 | BucketSort b = new BucketSort(); 39 | float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47, 40 | (float) 0.51 }; 41 | b.bucketSort(arr, 7); 42 | 43 | for (float i : arr) 44 | System.out.print(i + " "); 45 | } 46 | } -------------------------------------------------------------------------------- /Programs/Calculator.java: -------------------------------------------------------------------------------- 1 | /* 2 | Make a Calculator. 3 | Take 2 numbers(a&b)from the user and an operation as follows: 4 | 5 | 1:+(Addition)a+b. 6 | 2:-(Subtraction)a-b. 7 | 3:*(Multiplication)a*b. 8 | 4:/(Division)a/b. 9 | 5:%(Moduloorremainder)a%b. 10 | 11 | Calculate the result according to the operation given and display it to the user. 12 | */ 13 | 14 | package chapter3sol; 15 | 16 | import java.util.*; 17 | 18 | 19 | public class s1 { 20 | public static void main(String[] args) { 21 | Scanner sc = new Scanner(System.in); 22 | System.out.println("Enter First Number: "); 23 | double a = sc.nextDouble(); 24 | 25 | System.out.println("Enter Second Number: "); 26 | double b = sc.nextDouble(); 27 | 28 | System.out.print("choose one: \n 1. For Addition\n 2. For Substraction\n 3. For Multiplication\n 4. For Division\n 5. For Modulation \n : "); 29 | int n = sc.nextInt(); 30 | 31 | switch (n) { 32 | case 1: 33 | System.out.println("Addition: "+(a+b)); 34 | break; 35 | case 2: 36 | System.out.println("Substraction: "+(a-b)); 37 | break; 38 | case 3: 39 | System.out.println("Multiplication: "+(a*b)); 40 | break; 41 | case 4: 42 | System.out.println("Division: "+(a/b)); 43 | break; 44 | default: 45 | System.out.println("Plz Choose Right Option"); 46 | break; 47 | } 48 | } 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /Programs/CeaserCipher.java: -------------------------------------------------------------------------------- 1 | package Programs; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CeaserCipher { 6 | public static void main(String[] args) { 7 | System.out.println(""" 8 | -------------------------------- 9 | CEASER CIPHER ENCRYPT/ DECRYPT 10 | -------------------------------- 11 | """); 12 | Scanner sc = new Scanner(System.in); 13 | System.out.println("Encrypt or Decrypt:\n 1- Encryption\n 2- Decryption"); 14 | int type = sc.nextInt(); 15 | for (int j = 1; j > 0; j++) { 16 | if (type == 1) { 17 | ceaserCipherEncryption(); 18 | break; 19 | } else if (type == 2) { 20 | ceaserCipherDecryption(); 21 | break; 22 | } else { 23 | System.out.print("Please enter a valid number (1 or 2): "); 24 | type = sc.nextInt(); 25 | } 26 | } 27 | } 28 | public static void ceaserCipherEncryption() { 29 | Scanner textInput = new Scanner(System.in); 30 | System.out.print("PlainText: "); 31 | String textToEncrypt = textInput.nextLine(); 32 | System.out.print("shifting key: "); 33 | int keyToUse = textInput.nextInt(); 34 | String cipher = ""; 35 | for (int i = 0; true; i++) { 36 | if (keyToUse > 50 && keyToUse <= 0) { 37 | System.out.print("Please Enter key value <= 50: "); 38 | keyToUse = textInput.nextInt(); 39 | } else { 40 | for (int j = 0; j < textToEncrypt.length(); j++) { 41 | char temp = textToEncrypt.charAt(j); 42 | if (temp >= 'A' && temp <= 'Z') { 43 | temp = (char) (temp + keyToUse); 44 | if (temp > 'Z') { // go back to A in Ascii 45 | temp = (char) (temp + 'A' - 'Z' - 1); 46 | 47 | } 48 | cipher += temp; 49 | } else if (temp >= 'a' && temp <= 'z') { 50 | temp = (char) (temp + keyToUse); 51 | if (temp > 'z') { // go back to a in Ascii 52 | temp = (char) (temp + 'a' - 'z' - 1); 53 | 54 | } 55 | cipher += temp; 56 | } else 57 | cipher += temp; 58 | 59 | } 60 | } 61 | System.out.println("Enrypted text is: " + cipher); 62 | break; 63 | 64 | } 65 | } 66 | 67 | 68 | public static void ceaserCipherDecryption() { 69 | Scanner textInput = new Scanner(System.in); 70 | System.out.print("Encrypted Text: "); 71 | String textToEncrypt = textInput.nextLine(); 72 | System.out.print("shifting key: "); 73 | int keyToUse = textInput.nextInt(); 74 | String cipher = ""; 75 | for (int i = 0; true; i++) { 76 | if (keyToUse > 50 && keyToUse <= 0) { 77 | System.out.print("Please Enter key value <= 50: "); 78 | keyToUse = textInput.nextInt(); 79 | } else { 80 | for (int j = 0; j < textToEncrypt.length(); j++) { 81 | char temp = textToEncrypt.charAt(j); 82 | if (temp >= 'A' && temp <= 'Z') { 83 | temp = (char) (temp - keyToUse); 84 | if (temp < 'A') { // go back to A in Ascii 85 | temp = (char) (temp - 'A' + 'Z' + 1); 86 | 87 | } 88 | cipher += temp; 89 | } else if (temp >= 'a' && temp <= 'z') { 90 | temp = (char) (temp - keyToUse); 91 | if (temp < 'a') { // go back to a in Ascii 92 | temp = (char) (temp - 'a' + 'z' + 1); 93 | } 94 | cipher += temp; 95 | } else 96 | cipher += temp; 97 | } 98 | } 99 | System.out.println("Decrypted text is: " + cipher); 100 | break; 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /Programs/CeilingFloor.java: -------------------------------------------------------------------------------- 1 | package com.datastructures; 2 | 3 | public class CeilingFloor { 4 | 5 | static int findCeiling(int[] arr, int target) { 6 | int start = 0, end = arr.length - 1; 7 | while (start <= end) { 8 | int mid = start + (end - start) / 2; 9 | if (target < arr[mid]) { 10 | end = mid - 1; 11 | } else if (target > arr[mid]) { 12 | start = mid + 1; 13 | } else { 14 | return arr[mid]; 15 | } 16 | } 17 | return arr[start]; 18 | } 19 | 20 | static int findFloor(int arr[], int target) { 21 | int start = 0, end = arr.length - 1; 22 | while (start <= end) { 23 | int mid = start + (end - start) / 2; 24 | if (target < arr[mid]) { 25 | end = mid - 1; 26 | } else if (target > arr[mid]) { 27 | start = mid + 1; 28 | } else { 29 | return arr[mid]; 30 | } 31 | } 32 | return end; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int[] arr = {12, 18, 24, 30, 36, 42}; 37 | System.out.println(findCeiling(arr, 18)); 38 | System.out.println(findFloor(arr, 1)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Programs/Check_If_Sorted.java: -------------------------------------------------------------------------------- 1 | package Programs; 2 | 3 | public class Check_If_Sorted { 4 | public static void main(String[] args) { 5 | int[] toCheck = {1, 2, 3, 5, 16, 8}; 6 | int pointer = 0; 7 | System.out.println(checkIfSorted(toCheck, pointer)); 8 | } 9 | 10 | private static boolean checkIfSorted(int[] toCheck, int pointer) { 11 | if (pointer == toCheck.length - 1) { 12 | return true; 13 | } 14 | return toCheck[pointer] < toCheck[pointer + 1] && checkIfSorted(toCheck, pointer + 1); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Programs/Circular Integer LinkedList/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | circularLinkedList list = new circularLinkedList(); 5 | 6 | /**adds 10 random number in linkedlist */ 7 | for(int i=0;i<10;i++){ 8 | int number = (int)(Math.random()*10); 9 | list.add(number); 10 | } 11 | System.out.println("linkedlist:"); 12 | list.print(); 13 | System.out.println("size of linkedlist: "+list.size()); 14 | System.out.println("\n"); 15 | 16 | list.delete(1); 17 | list.delete(0); 18 | 19 | System.out.println("1. element is : "+list.getElement(1)); 20 | System.out.println("head of linkedlist is: "+list.getElement(0)); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Programs/Circular Integer LinkedList/Node.java: -------------------------------------------------------------------------------- 1 | public class Node { 2 | int data; 3 | Node next; 4 | 5 | public Node(int a) { 6 | data=a; 7 | next=null; 8 | 9 | } 10 | 11 | public Node() { 12 | data=-1; 13 | next=null; 14 | } 15 | 16 | public int getNodeElement(){ 17 | return data; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Programs/Circular Integer LinkedList/circularLinkedList.java: -------------------------------------------------------------------------------- 1 | public class circularLinkedList { 2 | Node head; 3 | int size; 4 | 5 | public circularLinkedList() { 6 | head=new Node(); 7 | head.next=head; 8 | size=0; 9 | head.data=-1; 10 | } 11 | /** 12 | * adds a new element end of the linkedlist 13 | * @param num 14 | */ 15 | public void add(int num) { 16 | 17 | Node newNode=new Node(num); 18 | Node currNode=head; 19 | 20 | if(size==0) 21 | { 22 | head.data=num; 23 | } 24 | else { 25 | while(!currNode.next.equals(head)) 26 | { 27 | currNode=currNode.next; 28 | 29 | } 30 | newNode.next=currNode.next; 31 | currNode.next=newNode; 32 | } 33 | size++; 34 | 35 | } 36 | 37 | /** 38 | * deletes index 39 | * index 0 is equal to head of linkedlist 40 | * @param index 41 | */ 42 | public void delete(int index) { 43 | 44 | Node currNode=head; 45 | Node currNodePrev=head; 46 | 47 | if(size==0) 48 | System.out.println("Linkedlist is empty"); 49 | if(index>=size) 50 | System.out.println("index of deletion is larger then size of linkedlist"); 51 | else{ 52 | if(index==0){ 53 | while(!currNode.next.equals(head)){ 54 | currNode=currNode.next; 55 | } 56 | currNode.next=head.next; 57 | head=head.next; 58 | }else{ 59 | for(int i=0;i coins; 8 | private static int count=0; 9 | 10 | private static void init() { 11 | coins = new ArrayList(); 12 | coins.add(1); 13 | coins.add(3); 14 | coins.add(5); 15 | coins.add(9); 16 | coins.add(10); 17 | coins.add(14); 18 | coins.add(18); 19 | coins.add(23); 20 | } 21 | 22 | /*Prints all comninations of the coin change*/ 23 | public static void coinCombinations(int amount,int index,LinkedList list) 24 | { 25 | if(amount==0) 26 | { 27 | count++; 28 | System.out.println(list); 29 | return ; 30 | } 31 | 32 | if(amount < 0) 33 | return ; 34 | 35 | for(int i=index ; i < coins.size();i++) 36 | { 37 | int coin = coins.get(i); 38 | if(amount >= coin) 39 | { 40 | list.add(coin); 41 | coinCombinations(amount - coin ,i,list ); 42 | list.removeLast(); 43 | 44 | } 45 | } 46 | } 47 | 48 | public static void main(String[] args) { 49 | int amount = 175; 50 | init(); 51 | coinCombinations(amount,0,new LinkedList()); 52 | //System.out.println("Number of Combinations :" + count); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Programs/ComplexNosOps.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate operations on complex numbers in Java - 2 | package ComplexNumsOps; 3 | import java.util.Scanner; // For user-input 4 | class Complex { 5 | double real1, real2, imag1, imag2; 6 | // Function to input data from user 7 | public void get_data() { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter real part of first complex number: "); 10 | real1 = sc.nextDouble(); 11 | System.out.println("Enter imaginary part first of complex number: "); 12 | imag1 = sc.nextDouble(); 13 | System.out.println("Enter real part of second complex number: "); 14 | real2 = sc.nextDouble(); 15 | System.out.println("Enter imaginary part second of complex number: "); 16 | imag2 = sc.nextDouble(); 17 | } 18 | // Function to display data that has been taken as input from user 19 | public void display() { 20 | System.out.println("Entered first complex number is: " + real1 + " + " + imag1 + "i"); 21 | System.out.println("Entered second complex number is: " + real2 + " + " + imag2 + "i"); 22 | } 23 | // Function to add two complex numbers 24 | public void add() { 25 | double addr = real1 + real2; 26 | double addi = imag1 + imag2; 27 | System.out.println("Addition is: " + addr + " + " + addi + "i"); 28 | } 29 | // Function to subtract two complex numbers 30 | public void sub() { 31 | double subr = real1 - real2; 32 | double subi = imag1 - imag2; 33 | System.out.println("Subtraction is: " + subr + " + " + subi + "i"); 34 | } 35 | // Function to multiply two complex numbers 36 | public void mult() { 37 | double s1, s2, s3, rs2; 38 | s1 = real1 * real2; 39 | s2 = (real1 * imag2) + (real2 * imag1); 40 | rs2 = Math.round((s2 * 100)/100); 41 | if (imag1 == 0 || imag2 == 0) { 42 | s3 = 0; 43 | } 44 | else { 45 | s3 = (-1) * (imag1 * imag2); 46 | } 47 | s1 = s1 + s3; 48 | System.out.println("Multiplication is: " + s1 + " + " + rs2 + "i"); 49 | 50 | } 51 | // Function to divide two complex numbers 52 | public void div() { 53 | double d1, d2, d3, d4, d5, d6; 54 | if (real2 == 0 && imag2 == 0) { 55 | System.out.println("Division cannot be performed."); 56 | } 57 | else { 58 | d1 = real1 * real2; // For numerator 59 | d2 = (real1 * imag2) + (real2 * imag1); // For numerator 60 | d4 = (real2 * real2); // For denominator 61 | d5 = (real2 * (-1) * imag2) + (real2 * (-1) * imag2); // For denominator 62 | d6 = d4 + d5; // For denominator 63 | if (imag1 == 0 || imag2 == 0) { 64 | d3 = 0; 65 | } 66 | else { 67 | d3 = (-1) * (imag1 * imag2); 68 | } 69 | d1 = d1 + d3; 70 | System.out.println("Division is: " + d1/d6 + " + " + d2/d6 + "i"); 71 | } 72 | } 73 | 74 | }; 75 | 76 | public class CmplxNumOps { 77 | public static void main(String[] args) { 78 | Scanner sc = new Scanner(System.in); 79 | int choice = 0; 80 | Complex c1 = new Complex(); // Creation of object of class Complex 81 | c1.get_data(); 82 | c1.display(); 83 | System.out.println("Enter 1 for addition, 2 for subtraction, 3 for multiplication, 4 for division: "); 84 | choice = sc.nextInt(); 85 | switch (choice) { 86 | case 1: 87 | c1.add(); 88 | break; 89 | case 2: 90 | c1.sub(); 91 | break; 92 | case 3: 93 | c1.mult(); 94 | break; 95 | case 4: 96 | c1.div(); 97 | break; 98 | default: 99 | System.out.println("Wrong input. Please enter correct choice."); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Programs/CountingSort.java: -------------------------------------------------------------------------------- 1 | // Program to implement counting sort 2 | import java.util.Arrays; 3 | 4 | public class CountingSortMain { 5 | 6 | public static void main(String[] args) { 7 | System.out.println("Before Sorting : "); 8 | int arr[]={1,4,7,3,4,5,6,3,4,8,6,4,4}; 9 | System.out.println(Arrays.toString(arr)); 10 | arr=countingSort(arr); 11 | System.out.println("======================="); 12 | System.out.println("After Sorting : "); 13 | System.out.println(Arrays.toString(arr)); 14 | } 15 | 16 | static int[] countingSort(int arr[]) 17 | { 18 | int n = arr.length; 19 | 20 | int result[] = new int[n]; 21 | 22 | int count[] = new int[9]; 23 | for (int i=0; i<9; ++i) 24 | count[i] = 0; 25 | 26 | for (int i=0; i adj[]; //adjacency list 12 | private boolean visited[]; //to keep track of the node which are visited. 13 | 14 | Graph(int v){ 15 | this.v = v; 16 | this.adj = new LinkedList[v]; 17 | this.visited = new boolean[v]; 18 | for(int i=0;i(); 20 | this.visited[i] = false; 21 | } 22 | 23 | } 24 | 25 | 26 | public void addEdge(int u,int v) { // edge from u -> v 27 | this.adj[u].add(v); 28 | } 29 | 30 | 31 | public void DFS(int source) { 32 | //if the node is already visited, then backtrack. 33 | if(this.visited[source] == true) { 34 | return; 35 | } 36 | //mark the source vertex as visited 37 | System.out.print(source+" "); 38 | this.visited[source] = true; 39 | 40 | //traverse through all the neighbours and backtrack if already visited. 41 | LinkedList neighbours = this.adj[source]; 42 | 43 | for(int next : neighbours) { 44 | DFS(next); 45 | } 46 | 47 | } 48 | 49 | } 50 | 51 | public class Main { 52 | public static void main(String args[]){ 53 | 54 | Graph g = new Graph(4); 55 | 56 | g.addEdge(0, 1); 57 | g.addEdge(0, 2); 58 | g.addEdge(1, 2); 59 | g.addEdge(2, 0); 60 | g.addEdge(2, 3); 61 | g.addEdge(3, 3); 62 | g.DFS(2); 63 | 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Programs/Decimal_to_Binary.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class BnaryCal { 5 | public static void main(String[] args) { 6 | Scanner scn = new Scanner(System.in); 7 | int number = scn.nextInt(); 8 | 9 | calculateBinary(number, calculateLength(number)); 10 | 11 | } 12 | 13 | static int calculateLength(int n){ 14 | int count =0; 15 | while(n>0){ 16 | n = n/2; 17 | count++; 18 | } 19 | return count; 20 | } 21 | 22 | static void calculateBinary(int n,int positions){ 23 | // int count = 0; 24 | // while(n>0){ 25 | // n = n/2; 26 | // count ++; 27 | // } 28 | int length = positions; 29 | 30 | int[] Binary = new int[length]; 31 | int i =0; 32 | while (n>0){ 33 | Binary[i] = n%2; 34 | n = n/2; 35 | i++; 36 | 37 | } 38 | for(int j= Binary.length-1; j>=0; j--){ 39 | System.out.print(Binary[j]); 40 | } 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Programs/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | // DFS algorithm in Java 2 | 3 | import java.util.*; 4 | 5 | class Graph { 6 | private LinkedList adjLists[]; 7 | private boolean visited[]; 8 | 9 | // Graph creation 10 | Graph(int vertices) { 11 | adjLists = new LinkedList[vertices]; 12 | visited = new boolean[vertices]; 13 | 14 | for (int i = 0; i < vertices; i++) 15 | adjLists[i] = new LinkedList(); 16 | } 17 | 18 | // Add edges 19 | void addEdge(int src, int dest) { 20 | adjLists[src].add(dest); 21 | } 22 | 23 | // DFS algorithm 24 | void DFS(int vertex) { 25 | visited[vertex] = true; 26 | System.out.print(vertex + " "); 27 | 28 | Iterator ite = adjLists[vertex].listIterator(); 29 | while (ite.hasNext()) { 30 | int adj = ite.next(); 31 | if (!visited[adj]) 32 | DFS(adj); 33 | } 34 | } 35 | 36 | public static void main(String args[]) { 37 | Graph g = new Graph(4); 38 | 39 | g.addEdge(0, 1); 40 | g.addEdge(0, 2); 41 | g.addEdge(1, 2); 42 | g.addEdge(2, 3); 43 | 44 | System.out.println("Following is Depth First Traversal"); 45 | 46 | g.DFS(2); 47 | } 48 | } -------------------------------------------------------------------------------- /Programs/Dijkstra.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Dijkstra{ 4 | public static void main(String ...args){ 5 | int v = 9; 6 | Graph g = new Graph(v); 7 | g.addEdge(0, 1, 4); 8 | g.addEdge(0, 7, 8); 9 | g.addEdge(1, 2, 8); 10 | g.addEdge(1, 7, 11); 11 | g.addEdge(2, 3, 7); 12 | g.addEdge(2, 8, 2); 13 | g.addEdge(2, 5, 4); 14 | g.addEdge(3, 4, 9); 15 | g.addEdge(3, 5, 14); 16 | g.addEdge(4, 5, 10); 17 | g.addEdge(5, 6, 2); 18 | g.addEdge(6, 7, 1); 19 | g.addEdge(6, 8, 6); 20 | g.addEdge(7, 8, 7); 21 | // g.printGraph(); 22 | 23 | dijkstra(g,0); 24 | } 25 | 26 | private static void dijkstra(Graph g, int src){ 27 | int V = g.v; 28 | int dist[] = new int[V]; 29 | Arrays.fill(dist, Integer.MAX_VALUE); 30 | dist[src] = 0; 31 | boolean visited[] = new boolean[V]; 32 | 33 | 34 | for(int i = 0 ; i < V; i ++){ 35 | int u = minDist(dist,visited); 36 | visited[u] = true; 37 | 38 | List list = g.adjList.get(u); 39 | for(AdjNode v : list){ 40 | if(!visited[v.dest] && dist[u] + v.cost < dist[v.dest]){ 41 | dist[v.dest] = dist[u] + v.cost; 42 | } 43 | } 44 | } 45 | 46 | System.out.println("Vertex Distance from Source"); 47 | for(int i = 0; i < dist.length; i++) 48 | System.out.println(i + " " + dist[i]); 49 | } 50 | 51 | private static int minDist(int dist[], boolean[] visited){ 52 | int min = Integer.MAX_VALUE, min_index = -1; 53 | 54 | for(int i = 0 ; i < dist.length; i++){ 55 | if(!visited[i] && dist[i] <= min){ 56 | min = dist[i]; 57 | min_index = i; 58 | } 59 | } 60 | return min_index; 61 | } 62 | } 63 | 64 | 65 | class Graph{ 66 | int v; 67 | List> adjList; 68 | Graph(int v){ 69 | this.v = v; 70 | adjList = new ArrayList<>(); 71 | for(int i = 0; i < this.v; i++){ 72 | adjList.add(new ArrayList<>()); 73 | } 74 | } 75 | 76 | public void addEdge(int u, int v, int cost){ 77 | this.adjList.get(u).add(new AdjNode(u, v, cost)); 78 | this.adjList.get(v).add(new AdjNode(v, u, cost)); 79 | } 80 | public void printGraph(){ 81 | for(int i = 0 ; i < this.v ; i++){ 82 | System. out.print(i + " -> "); 83 | for(int j = 0 ; j < adjList.get(i).size(); j++){ 84 | System.out.print(adjList.get(i).get(j).dest + " "); 85 | } 86 | System. out.println(); 87 | } 88 | } 89 | } 90 | 91 | class AdjNode{ 92 | int source, dest, cost; 93 | AdjNode(int source, int dest, int cost){ 94 | this.source = source; 95 | this.dest = dest; 96 | this.cost = cost; 97 | } 98 | } -------------------------------------------------------------------------------- /Programs/ExponentialSearch.java: -------------------------------------------------------------------------------- 1 | // Java program to implement Exponential search. 2 | import java.util.Arrays; 3 | 4 | class ExponentialSearch 5 | { 6 | 7 | static int exponentialSearch(int arr[], 8 | int n, int x) 9 | { 10 | if (arr[0] == x) 11 | return 0; 12 | 13 | int i = 1; 14 | while (i < n && arr[i] <= x) 15 | i = i*2; 16 | 17 | return Arrays.binarySearch(arr, i/2, 18 | Math.min(i, n-1), x); 19 | } 20 | 21 | public static void main(String args[]) 22 | { 23 | int arr[] = {2, 3, 4, 10, 40}; 24 | int x = 10; 25 | int result = exponentialSearch(arr, 26 | arr.length, x); 27 | 28 | System.out.println((result < 0) ? 29 | "Element is not present in array" : 30 | "Element is present at index " + 31 | result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Programs/FactorialDemo.java: -------------------------------------------------------------------------------- 1 | class FactorialDemo { 2 | public static void main(String args[]){ 3 | int fact = 0; 4 | for (int i=0; i<=10; i++) { 5 | fact = factorial(i); 6 | System.out.println("factorial of "+i+" is: "+fact); 7 | } 8 | 9 | } 10 | static int factorial(int n){ 11 | if (n == 0) 12 | return 1; 13 | else 14 | return(n * factorial(n-1)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Programs/Factory Method/Car.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public interface Car { 4 | public String getModel(); 5 | public void setWheel(String wheel); 6 | public String getWheel(); 7 | public void setEngine(String engine); 8 | public String getEngine(); 9 | } 10 | -------------------------------------------------------------------------------- /Programs/Factory Method/CarFactory.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public interface CarFactory { 4 | public abstract Car buildCar(String model, String wheel, String engine); 5 | } 6 | -------------------------------------------------------------------------------- /Programs/Factory Method/HatchbackCar.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class HatchbackCar implements Car { 4 | String model; 5 | String wheel; 6 | String engine; 7 | HatchbackCar(String model, String wheel, String engine) { 8 | this.model = model; 9 | this.wheel = wheel; 10 | this.engine = engine; 11 | } 12 | 13 | public String getModel() { 14 | return model; 15 | } 16 | 17 | public void setWheel(String wheel) { 18 | this.wheel = wheel; 19 | } 20 | 21 | public String getWheel() { 22 | return wheel; 23 | } 24 | 25 | public void setEngine(String engine) { 26 | this.engine = engine; 27 | } 28 | 29 | public String getEngine() { 30 | return engine; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Programs/Factory Method/HatchbackCarFactory.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class HatchbackCarFactory implements CarFactory { 4 | @Override 5 | public Car buildCar(String model, String wheel, String engine) { 6 | Car car = new HatchbackCar(model, wheel, engine); 7 | return car; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Programs/Factory Method/SUVCar.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class SUVCar implements Car { 4 | String model; 5 | String wheel; 6 | String engine; 7 | 8 | SUVCar(String model, String wheel, String engine) { 9 | this.model = model; 10 | this.wheel = wheel; 11 | this.engine = engine; 12 | } 13 | 14 | public String getModel() { 15 | return model; 16 | } 17 | 18 | public void setWheel(String wheel) { 19 | this.wheel = wheel; 20 | } 21 | 22 | public String getWheel() { 23 | return wheel; 24 | } 25 | 26 | public void setEngine(String engine) { 27 | this.engine = engine; 28 | } 29 | 30 | public String getEngine() { 31 | return engine; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Programs/Factory Method/SUVCarFactory.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class SUVCarFactory implements CarFactory { 4 | @Override 5 | public Car buildCar(String model, String wheel, String engine) { 6 | Car car = new SUVCar(model, wheel, engine); 7 | return car; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Programs/Factory Method/SedanCar.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class SedanCar implements Car { 4 | String model; 5 | String wheel; 6 | String engine; 7 | 8 | SedanCar(String model, String wheel, String engine) { 9 | this.model = model; 10 | this.wheel = wheel; 11 | this.engine = engine; 12 | } 13 | 14 | public String getModel() { 15 | return model; 16 | } 17 | 18 | public void setWheel(String wheel) { 19 | this.wheel = wheel; 20 | } 21 | 22 | public String getWheel() { 23 | return wheel; 24 | } 25 | 26 | public void setEngine(String engine) { 27 | this.engine = engine; 28 | } 29 | 30 | public String getEngine() { 31 | return engine; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Programs/Factory Method/SedanCarFactory.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class SedanCarFactory implements CarFactory { 4 | @Override 5 | public Car buildCar(String model, String wheel, String engine) { 6 | Car car = new SedanCar(model, wheel, engine); 7 | return car; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Programs/Factory Method/TestFactoryPattern.java: -------------------------------------------------------------------------------- 1 | package factoryMethod; 2 | 3 | public class TestFactoryPattern { 4 | CarFactory carBuilder; 5 | Car car; 6 | public static void main(String[] args) { 7 | TestFactoryPattern client = new TestFactoryPattern(); 8 | client.buildCarMethod(); 9 | } 10 | 11 | public void buildCarMethod() { 12 | System.out.println("Building Hatchback car..."); 13 | carBuilder = new HatchbackCarFactory(); 14 | car = carBuilder.buildCar("Polo", "Michelin", "VW"); 15 | System.out.println("Car is assembled!"); 16 | System.out.println("Specifications of car are: "); 17 | System.out.println("Model: " + car.getModel()); 18 | System.out.println("Engine: " + car.getEngine()); 19 | System.out.println("Wheel: " + car.getWheel()); 20 | 21 | System.out.println(); 22 | 23 | System.out.println("Building Sedan car..."); 24 | carBuilder = new SedanCarFactory(); 25 | car = carBuilder.buildCar("Dzire", "MRF", "Suzuki"); 26 | System.out.println("Car is assembled!"); 27 | System.out.println("Specifications of car are: "); 28 | System.out.println("Model: " + car.getModel()); 29 | System.out.println("Engine: " + car.getEngine()); 30 | System.out.println("Wheel: " + car.getWheel()); 31 | 32 | System.out.println(); 33 | 34 | System.out.println("Building SUV car..."); 35 | carBuilder = new SUVCarFactory(); 36 | car = carBuilder.buildCar("Innova", "Bridgestone", "Fiat"); 37 | System.out.println("Car is assembled!"); 38 | System.out.println("Specifications of car are: "); 39 | System.out.println("Model: " + car.getModel()); 40 | System.out.println("Engine: " + car.getEngine()); 41 | System.out.println("Wheel: " + car.getWheel()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Programs/Fibonacci.java: -------------------------------------------------------------------------------- 1 | // Java program for Fibonacci Search 2 | import java.util.*; 3 | 4 | class Fibonacci { 5 | public static int min(int x, int y) 6 | { 7 | return (x <= y) ? x : y; 8 | } 9 | 10 | /* Returns index of x if present, else returns -1 */ 11 | public static int fibMonaccianSearch(int arr[], int x, 12 | int n) 13 | { 14 | /* Initialize fibonacci numbers */ 15 | int fibMMm2 = 0; 16 | int fibMMm1 = 1; 17 | int fibM = fibMMm2 + fibMMm1; 18 | 19 | while (fibM < n) { 20 | fibMMm2 = fibMMm1; 21 | fibMMm1 = fibM; 22 | fibM = fibMMm2 + fibMMm1; 23 | } 24 | 25 | int offset = -1; 26 | 27 | while (fibM > 1) { 28 | int i = min(offset + fibMMm2, n - 1); 29 | 30 | if (arr[i] < x) { 31 | fibM = fibMMm1; 32 | fibMMm1 = fibMMm2; 33 | fibMMm2 = fibM - fibMMm1; 34 | offset = i; 35 | } 36 | 37 | else if (arr[i] > x) { 38 | fibM = fibMMm2; 39 | fibMMm1 = fibMMm1 - fibMMm2; 40 | fibMMm2 = fibM - fibMMm1; 41 | } 42 | 43 | else 44 | return i; 45 | } 46 | 47 | if (fibMMm1 == 1 && arr[n-1] == x) 48 | return n-1; 49 | 50 | return -1; 51 | } 52 | 53 | public static void main(String[] args) 54 | { 55 | int arr[] = { 10, 22, 35, 40, 45, 50, 56 | 80, 82, 85, 90, 100,235}; 57 | int n = 12; 58 | int x = 235; 59 | int ind = fibMonaccianSearch(arr, x, n); 60 | if(ind>=0) 61 | System.out.print("Found at index: "+ ind); 62 | else 63 | System.out.print(x+" isn't present in the array"); 64 | } 65 | } -------------------------------------------------------------------------------- /Programs/FindIndexValue.java: -------------------------------------------------------------------------------- 1 | import java.util.function.BiFunction; 2 | public class MyClass { 3 | public static final BiFunction fun = (i, val) -> { 4 | if(val >= i.length){ 5 | return -999; 6 | } 7 | return i[val]; 8 | }; 9 | public static void main(String args[]) { 10 | int a1[] = {1,2,4,51,3,4,5,6,7,2,3,4}; 11 | int a2[] = {3,2,52,12,4,43,54,5,6,56,56,56,5,11}; 12 | System.out.println(fun.apply(a1,2)); 13 | System.out.println(fun.apply(a1,12)); 14 | System.out.println(fun.apply(a1,7)); 15 | System.out.println(fun.apply(a1,21)); 16 | System.out.println(fun.apply(a2,1)); 17 | System.out.println(fun.apply(a2,11)); 18 | System.out.println(fun.apply(a2,9)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Programs/Floyd_Warshall_Algorithm.java: -------------------------------------------------------------------------------- 1 | // Java program for Floyd Warshall All Pairs Shortest Path algorithm. 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | 7 | class AllPairShortestPath 8 | { 9 | final static int INF = 99999, V = 4; 10 | 11 | void floydWarshall(int graph[][]) 12 | { 13 | int dist[][] = new int[V][V]; 14 | int i, j, k; 15 | 16 | for (i = 0; i < V; i++) 17 | for (j = 0; j < V; j++) 18 | dist[i][j] = graph[i][j]; 19 | 20 | for (k = 0; k < V; k++) 21 | { 22 | for (i = 0; i < V; i++) 23 | { 24 | for (j = 0; j < V; j++) 25 | { 26 | if (dist[i][k] + dist[k][j] < dist[i][j]) 27 | dist[i][j] = dist[i][k] + dist[k][j]; 28 | } 29 | } 30 | } 31 | 32 | printSolution(dist); 33 | } 34 | 35 | void printSolution(int dist[][]) 36 | { 37 | System.out.println("The following matrix shows the shortest "+ 38 | "distances between every pair of vertices"); 39 | for (int i=0; i queue = new LinkedList(); 15 | queue.add(s); 16 | visited[s] = true; 17 | p[s] = -1; 18 | 19 | while (queue.size() != 0) { 20 | int u = queue.poll(); 21 | 22 | for (int v = 0; v < V; v++) { 23 | if (visited[v] == false && Graph[u][v] > 0) { 24 | queue.add(v); 25 | p[v] = u; 26 | visited[v] = true; 27 | } 28 | } 29 | } 30 | 31 | return (visited[t] == true); 32 | } 33 | 34 | // Applying fordfulkerson algorithm 35 | int fordFulkerson(int graph[][], int s, int t) { 36 | int u, v; 37 | int Graph[][] = new int[V][V]; 38 | 39 | for (u = 0; u < V; u++) 40 | for (v = 0; v < V; v++) 41 | Graph[u][v] = graph[u][v]; 42 | 43 | int p[] = new int[V]; 44 | 45 | int max_flow = 0; 46 | 47 | // Updating the residual calues of edges 48 | while (bfs(Graph, s, t, p)) { 49 | int path_flow = Integer.MAX_VALUE; 50 | for (v = t; v != s; v = p[v]) { 51 | u = p[v]; 52 | path_flow = Math.min(path_flow, Graph[u][v]); 53 | } 54 | 55 | for (v = t; v != s; v = p[v]) { 56 | u = p[v]; 57 | Graph[u][v] -= path_flow; 58 | Graph[v][u] += path_flow; 59 | } 60 | 61 | // Adding the path flows 62 | max_flow += path_flow; 63 | } 64 | 65 | return max_flow; 66 | } 67 | 68 | public static void main(String[] args) throws java.lang.Exception { 69 | int graph[][] = new int[][] { { 0, 8, 0, 0, 3, 0 }, { 0, 0, 9, 0, 0, 0 }, { 0, 0, 0, 0, 7, 2 }, 70 | { 0, 0, 0, 0, 0, 5 }, { 0, 0, 7, 4, 0, 0 }, { 0, 0, 0, 0, 0, 0 } }; 71 | FordFulkerson m = new FordFulkerson(); 72 | 73 | System.out.println("Max Flow: " + m.fordFulkerson(graph, 0, 5)); 74 | 75 | } 76 | } -------------------------------------------------------------------------------- /Programs/FunctionalInterfaces.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate how to use the Function and BiFunction functional interfaces 2 | 3 | import java.util.function.Function; 4 | import java.util.function.BiFunction; 5 | 6 | public class FunctionalInterfaces { 7 | 8 | /** 9 | * A functional interface such as Function class takes two generic types, the 10 | * type of the input and the type of the output. They can be written as 11 | * anonymous classes that implement the Function interface, but they are more 12 | * commonly written as lambda functions. 13 | * 14 | */ 15 | static Function sayHello = name -> "Hello, " + name; 16 | 17 | /** 18 | * A BiFunction works the same way as a Function,except for taking two input 19 | * types 20 | */ 21 | static BiFunction sumValues = (x, y) -> x + y; 22 | 23 | public static void main(String[] args) { 24 | // Function types are invoked using the .apply() method on the interface 25 | System.out.println(sayHello.apply("Dan")); 26 | System.out.println(sumValues.apply(3, 2)); 27 | } 28 | } -------------------------------------------------------------------------------- /Programs/Games/GuessTheNumber.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | import java.util.Random; 3 | import java.util.Scanner; 4 | 5 | public class GuessTheNumber { 6 | private int guesses = 10; 7 | private int warning = 4; 8 | private int guessedNo; 9 | private int[] alreadyTold = new int[10]; 10 | private int specialWarning = 1; 11 | int index = 0; 12 | int rng = 20; 13 | 14 | public Scanner inputInt(){ 15 | System.out.print("\nEnter Your Guess: "); 16 | return new Scanner(System.in); 17 | } 18 | 19 | public boolean isValid(Scanner inp){ 20 | return inp.hasNextInt(); 21 | } 22 | 23 | public int generateRand(int range){ 24 | Random rand = new Random(); 25 | return rand.nextInt(range); 26 | } 27 | public void setAlreadyTold(int guess){ 28 | this.alreadyTold[this.index] = guess; 29 | this.index++; 30 | } 31 | 32 | public boolean isAlreadyTold(int guess){ 33 | for(int i = 0; i < 10; i++){ 34 | if(guess == this.alreadyTold[i]){ 35 | return true; 36 | } 37 | } 38 | return false; 39 | } 40 | public void printGuessed(){ 41 | for(int i = 0; i < 10; i ++){ 42 | if(alreadyTold[i] != -1) 43 | System.out.print(alreadyTold[i] + " "); 44 | } 45 | } 46 | 47 | public void setGuessedToNull(){ 48 | for(int i = 0; i < 10; i ++){ 49 | alreadyTold[i] = -1; 50 | } 51 | } 52 | 53 | public void play(){ 54 | setGuessedToNull(); 55 | int secretNum = generateRand(rng); 56 | System.out.println("I am Thinking of a word between 0-"+ rng + "."); 57 | Scanner scanGuess; 58 | int guess; 59 | boolean flag = true; 60 | do{ 61 | System.out.print("Remaining guesses: "+this.guesses+"\nRemaining warnings: "+this.warning + "\nGuessed Numbers: "); printGuessed(); 62 | scanGuess = inputInt(); 63 | if(isValid(scanGuess)){ 64 | guess = scanGuess.nextInt(); 65 | if(guess == secretNum) 66 | { 67 | System.out.println("Congratulations! You have guessed the secret number!!"); 68 | flag = false; 69 | } 70 | else if ((this.warning) > 0 && (this.guesses > 0)) { 71 | 72 | if(isAlreadyTold(guess)){ 73 | this.warning--; 74 | this.guesses--; 75 | System.out.println("You have already guessed this number"); 76 | }else 77 | if(guess < secretNum){ 78 | this.guesses--; 79 | System.out.println("Guessed number is less than secret number."); 80 | setAlreadyTold(guess); 81 | }else { 82 | this.guesses--; 83 | System.out.println("Guessed number is greater than secret number."); 84 | setAlreadyTold(guess); 85 | } 86 | 87 | } else { 88 | System.out.println("Game Over!"); 89 | flag = false; 90 | } 91 | } else if (this.specialWarning>0){ 92 | System.out.println("Invalid Input!!!"); 93 | this.specialWarning--; 94 | }else{ 95 | System.out.println("Invalid Input!!!"); 96 | this.guesses--; 97 | } 98 | 99 | }while(flag); 100 | } 101 | 102 | public static void main(String[] args){ 103 | GuessTheNumber n = new GuessTheNumber(); 104 | System.out.println(n.generateRand(20)); 105 | n.play(); 106 | 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Programs/Games/MaximumSubArraySum.java: -------------------------------------------------------------------------------- 1 | public class MaximumSubArraySum { 2 | //Maximum Subarray Sum using Divide and Conquer algorithm 3 | 4 | 5 | public static int MaximumSum(int[] Arr, int firstindex, int lastindex) { 6 | 7 | if (lastindex == firstindex) {//if the first index and the last index of array are same 8 | return Arr[ firstindex ];//it means array contains only one element 9 | //and this element equals maximum subarray sum. 10 | } 11 | 12 | // Finding middle element's index of the array 13 | int middle = ( firstindex + lastindex ) / 2; 14 | 15 | // Finding maximum subarray sum for the left subarray 16 | 17 | int leftMax = -1000000000; 18 | int sum = 0; 19 | for (int i = middle; i >= firstindex; i--) { 20 | sum += Arr[ i ];//addition for sum 21 | if (sum > leftMax) { 22 | leftMax = sum; 23 | } 24 | } 25 | 26 | // Find maximum subarray sum for the right subarray 27 | int rightMax = -1000000000;//should be minimum value 28 | sum = 0; 29 | for (int i = middle + 1; i <= lastindex; i++) { 30 | sum += Arr[ i ];//addition for sum 31 | if (sum > rightMax) { 32 | rightMax = sum; 33 | } 34 | } 35 | 36 | // Recursive part 37 | int maxLeftRight = Math.max (MaximumSum (Arr, firstindex, middle),//left part of the array 38 | MaximumSum (Arr, middle + 1, lastindex));//right part of the array 39 | 40 | // return maximum of the three 41 | return Math.max (maxLeftRight, leftMax + rightMax); 42 | } 43 | 44 | C:\Users\Ayse\Desktop\Java\Programs\Games\ MaximumSubArraySum 45 | } 46 | -------------------------------------------------------------------------------- /Programs/Games/Snake Game with Different Playing Features and GUI/GameFrame.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | 3 | //GAME FRAME CLASS EXTENDING JFRAME CLASS 4 | public class GameFrame extends JFrame { 5 | 6 | //CONSTRUCTOR 7 | GameFrame(){ 8 | 9 | this.add(new GamePanel()); 10 | this.setTitle("Snake"); 11 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 | this.setResizable(false); 13 | this.pack(); 14 | this.setVisible(true); 15 | this.setLocationRelativeTo(null); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Programs/Games/Snake Game with Different Playing Features and GUI/README.md: -------------------------------------------------------------------------------- 1 | # Snake-Game 2 | 3 | A simple Snake Game using JAVA . WIth three classes GameFrame GamePanel and SnakeGamer . Main class is in SnakeGamer . Features are Score Pause Resume Difficulty increases . 4 | -------------------------------------------------------------------------------- /Programs/Games/Snake Game with Different Playing Features and GUI/SnakeGamer.java: -------------------------------------------------------------------------------- 1 | public class SnakeGamer { 2 | //MAIN 3 | public static void main(String[] args) { 4 | new GameFrame(); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/1.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/2.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/3.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/4.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/5.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/1ff670b1d5b88b5514de9501323d6c386b123238/Programs/Games/peg-solitaire/6.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/Main.java: -------------------------------------------------------------------------------- 1 | import javax.swing.JFrame; 2 | /* 3 | 4 | STARTER "Main" CLASS FOR PEG SOLITAIRE GAME 5 | THIS IS A PROGRAM FOR PEG SOLITAIRE GAME, TRY TO WIPE OFF AS MANY PEG AS POSSIBLE 6 | 7 | */ 8 | public class Main{ 9 | public static void main(String args[]){ 10 | //Creating game object 11 | PegSolitaire game = new PegSolitaire(); 12 | 13 | //exit when frame is closed 14 | game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15 | 16 | //setting beginning size 17 | game.setSize(1000, 300); 18 | 19 | //make frame visible 20 | game.setVisible(true); 21 | } 22 | } -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/PegSolitaireGame.java: -------------------------------------------------------------------------------- 1 | public interface PegSolitaireGame{ 2 | /** 3 | * Method to create first board from scratch. 4 | * @param is_loaded True if the board is loaded from a file. 5 | */ 6 | void Board1(boolean is_loaded); 7 | 8 | /** 9 | * Method to create second board from scratch. 10 | * @param is_loaded True if the board is loaded from a file. 11 | */ 12 | void Board2(boolean is_loaded); 13 | 14 | /** 15 | * Method to create third board from scratch. 16 | * @param is_loaded True if the board is loaded from a file. 17 | */ 18 | void Board3(boolean is_loaded); 19 | 20 | /** 21 | * Method to create fourth board from scratch. 22 | * @param is_loaded True if the board is loaded from a file. 23 | */ 24 | void Board4(boolean is_loaded); 25 | 26 | /** 27 | * Method to create fifth board from scratch. 28 | * @param is_loaded True if the board is loaded from a file. 29 | */ 30 | void Board5(boolean is_loaded); 31 | 32 | /** 33 | * Method to create sixth board from scratch. 34 | * @param is_loaded True if the board is loaded from a file. 35 | */ 36 | void Board6(boolean is_loaded); 37 | 38 | /** 39 | * Method to add cell buttons to the frame for first 5 types. 40 | */ 41 | void addBoard(); 42 | 43 | /** 44 | * Method to add cell buttons to the frame for last type. 45 | */ 46 | void addBoardTriangle(); 47 | 48 | /** 49 | * Method to add listeners for the cell buttons. 50 | */ 51 | void addingListenersType(); 52 | 53 | /** 54 | * Method to determine if move is valid for the up. 55 | * @param yRow Row value of the selected cell. 56 | * @param yCol Column value of the selected cell. 57 | * @param row Row value of the slot that user wants to go. 58 | * @param col Column value of the slot that user wants to go. 59 | * @return boolean to specify if the move is valid. 60 | */ 61 | boolean is_valid_up(int yRow, int yCol, int row, int col); 62 | 63 | /** 64 | * Method to determine if move is valid for the down. 65 | * @param yRow Row value of the selected cell. 66 | * @param yCol Column value of the selected cell. 67 | * @param row Row value of the slot that user wants to go. 68 | * @param col Column value of the slot that user wants to go. 69 | * @return boolean to specify if the move is valid. 70 | */ 71 | boolean is_valid_down(int yRow, int yCol, int row, int col); 72 | 73 | /** 74 | * Method to determine if move is valid for the right. 75 | * @param yRow Row value of the selected cell. 76 | * @param yCol Column value of the selected cell. 77 | * @param row Row value of the slot that user wants to go. 78 | * @param col Column value of the slot that user wants to go. 79 | * @return boolean to specify if the move is valid. 80 | */ 81 | boolean is_valid_right(int yRow, int yCol, int row, int col); 82 | 83 | /** 84 | * Method to determine if move is valid for the left. 85 | * @param yRow Row value of the selected cell. 86 | * @param yCol Column value of the selected cell. 87 | * @param row Row value of the slot that user wants to go. 88 | * @param col Column value of the slot that user wants to go. 89 | * @return boolean to specify if the move is valid. 90 | */ 91 | boolean is_valid_left(int yRow, int yCol, int row, int col); 92 | 93 | /** 94 | * Method to determine if the game is finished. 95 | * @return boolean to specify if the game is finished. 96 | */ 97 | boolean is_finished(); 98 | 99 | /** 100 | * Method to refresh the current screen. 101 | */ 102 | void reset_screen(); 103 | 104 | /** 105 | * Method to make the computer play 1 move. 106 | * @return boolean to specify if the game is finished. 107 | */ 108 | boolean autoOne(); 109 | } -------------------------------------------------------------------------------- /Programs/GenClassMethod.java: -------------------------------------------------------------------------------- 1 | package genclass; 2 | 3 | public class GenClassMethod { 4 | public static void printItems(T[] arr) { 5 | for (int i = 0; i < arr.length; i++) { 6 | System.out.print(arr[i] + " "); 7 | } 8 | } 9 | 10 | public static void main(String[] args) { 11 | // TODO Auto-generated method stub 12 | String arr1[] = {"Cat", "Mouse", "Dog"}; 13 | Integer arr2[] = {1, 2, 3}; 14 | Double arr3[] = {10.5, 3.33, 7.33}; 15 | 16 | GenClassMethod.printItems(arr1); 17 | GenClassMethod.printItems(arr2); 18 | GenClassMethod.printItems(arr3); 19 | 20 | } 21 | } 22 | 23 | // Using generic program, implement a stack -------------------------------------------------------------------------------- /Programs/Gssarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Name - Jayneel Shah 3 | Date - 23/10/21 4 | Topic - Application of classes in Java 5 | Program to implement growable self sorting array(GSSArray) 6 | */ 7 | 8 | import java.util.*; 9 | 10 | class GSSArray 11 | { 12 | private int [] arr; 13 | private int size; 14 | private int lastIndex = -1; 15 | 16 | //default constructor 17 | GSSArray(int n) 18 | { 19 | arr = new int[n]; 20 | size = n; 21 | } 22 | 23 | int i = 0; 24 | 25 | //insert function 26 | public void insert(int value) 27 | { 28 | //if size is less than defined size regular addition 29 | if (size > i) 30 | { 31 | lastIndex++; 32 | arr[lastIndex] = value; 33 | i++; 34 | display(); 35 | } 36 | 37 | //if the size is more then it first increases the size and then performs addition in the array 38 | else 39 | { 40 | increaseSize(); 41 | lastIndex++; 42 | arr[lastIndex] = value; 43 | i++; 44 | display(); 45 | } 46 | } 47 | 48 | //incrase size function - it doubles the size and copie the elements of old array in the new array 49 | private void increaseSize() 50 | { 51 | int[] arr1 = new int[arr.length*2]; 52 | for(int i=0;iarr[j]) 110 | { 111 | temp = arr[i]; 112 | arr[i] = arr[j]; 113 | arr[j] = temp; 114 | } 115 | } 116 | } 117 | } 118 | } 119 | 120 | class Gssarray 121 | { 122 | public static void main(String[] args) { 123 | Scanner sc = new Scanner(System.in); 124 | GSSArray gs = new GSSArray(5); 125 | 126 | int choice, val; 127 | boolean ans; 128 | 129 | while (true) { 130 | System.out.println("Enter 1 to insert"); 131 | System.out.println("Enter 2 to delete"); 132 | System.out.println("Enter 3 to exit"); 133 | choice = sc.nextInt(); 134 | if (choice == 1) { 135 | System.out.print("Enter the value to enter in array: "); 136 | val = sc.nextInt(); 137 | gs.insert(val); 138 | } else if (choice == 2) { 139 | System.out.print("Enter the value to delete: "); 140 | val = sc.nextInt(); 141 | ans = gs.delete(val); 142 | System.out.println(ans); 143 | gs.display(); 144 | } else if (choice == 3) { 145 | System.out.println("Thank You!"); 146 | break; 147 | } 148 | } 149 | sc.close(); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /Programs/HeapSort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | public void sort(int arr[]) { 3 | int n = arr.length; 4 | 5 | // Build heap (rearrange array) 6 | for (int i = n / 2 - 1; i >= 0; i--) 7 | heapify(arr, n, i); 8 | 9 | // One by one extract an element from heap 10 | for (int i = n - 1; i > 0; i--) { 11 | // Move current root to end 12 | int temp = arr[0]; 13 | arr[0] = arr[i]; 14 | arr[i] = temp; 15 | 16 | // call max heapify on the reduced heap 17 | heapify(arr, i, 0); 18 | } 19 | } 20 | 21 | // To heapify a subtree rooted with node i which is 22 | // an index in arr[]. n is size of heap 23 | void heapify(int arr[], int n, int i) { 24 | int largest = i; // Initialize largest as root 25 | int l = 2 * i + 1; // left = 2*i + 1 26 | int r = 2 * i + 2; // right = 2*i + 2 27 | 28 | // If left child is larger than root 29 | if (l < n && arr[l] > arr[largest]) 30 | largest = l; 31 | 32 | // If right child is larger than largest so far 33 | if (r < n && arr[r] > arr[largest]) 34 | largest = r; 35 | 36 | // If largest is not root 37 | if (largest != i) { 38 | int swap = arr[i]; 39 | arr[i] = arr[largest]; 40 | arr[largest] = swap; 41 | 42 | // Recursively heapify the affected sub-tree 43 | heapify(arr, n, largest); 44 | } 45 | } 46 | 47 | /* A utility function to print array of size n */ 48 | static void printArr(int arr[]) { 49 | int n = arr.length; 50 | for (int i = 0; i < n; ++i){ 51 | System.out.print(arr[i] + " "); 52 | } 53 | System.out.println(); 54 | } 55 | 56 | public static void main(String[] args) { 57 | int arr[] = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; 58 | int n = arr.length; 59 | System.out.println("The original Heap sort is: "); 60 | printArr(arr); 61 | 62 | HeapSort heapSort = new HeapSort(); 63 | heapSort.sort(arr); 64 | 65 | System.out.println("The sorted array is"); 66 | printArr(arr); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Programs/HttpsRequest.java: -------------------------------------------------------------------------------- 1 | import java.net.URI; 2 | import java.net.http.HttpClient; 3 | import java.net.http.HttpRequest; 4 | import java.net.http.HttpResponse; 5 | import java.nio.charset.Charset; 6 | 7 | public class HttpsRequest { 8 | public static void main(String[] args) { 9 | var request = HttpRequest.newBuilder(URI.create("https://github.com/")) 10 | .GET() 11 | .build(); 12 | //Prints the status Code of the HTTP-Request 13 | HttpClient.newHttpClient() 14 | .sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset())) 15 | .thenApply(HttpResponse::statusCode) 16 | .thenAccept(System.out::println) 17 | .join(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Programs/HuffmanCoding.java: -------------------------------------------------------------------------------- 1 | // Huffman Coding in Java 2 | 3 | import java.util.PriorityQueue; 4 | import java.util.Comparator; 5 | 6 | class HuffmanNode { 7 | int item; 8 | char c; 9 | HuffmanNode left; 10 | HuffmanNode right; 11 | } 12 | 13 | // For comparing the nodes 14 | class ImplementComparator implements Comparator { 15 | public int compare(HuffmanNode x, HuffmanNode y) { 16 | return x.item - y.item; 17 | } 18 | } 19 | 20 | // Implementing the huffman algorithm 21 | public class Huffman { 22 | public static void printCode(HuffmanNode root, String s) { 23 | if (root.left == null && root.right == null && Character.isLetter(root.c)) { 24 | 25 | System.out.println(root.c + " | " + s); 26 | 27 | return; 28 | } 29 | printCode(root.left, s + "0"); 30 | printCode(root.right, s + "1"); 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | int n = 4; 36 | char[] charArray = { 'A', 'B', 'C', 'D' }; 37 | int[] charfreq = { 5, 1, 6, 3 }; 38 | 39 | PriorityQueue q = new PriorityQueue(n, new ImplementComparator()); 40 | 41 | for (int i = 0; i < n; i++) { 42 | HuffmanNode hn = new HuffmanNode(); 43 | 44 | hn.c = charArray[i]; 45 | hn.item = charfreq[i]; 46 | 47 | hn.left = null; 48 | hn.right = null; 49 | 50 | q.add(hn); 51 | } 52 | 53 | HuffmanNode root = null; 54 | 55 | while (q.size() > 1) { 56 | 57 | HuffmanNode x = q.peek(); 58 | q.poll(); 59 | 60 | HuffmanNode y = q.peek(); 61 | q.poll(); 62 | 63 | HuffmanNode f = new HuffmanNode(); 64 | 65 | f.item = x.item + y.item; 66 | f.c = '-'; 67 | f.left = x; 68 | f.right = y; 69 | root = f; 70 | 71 | q.add(f); 72 | } 73 | System.out.println(" Char | Huffman code "); 74 | System.out.println("--------------------"); 75 | printCode(root, ""); 76 | } 77 | } -------------------------------------------------------------------------------- /Programs/IncomeTaxCalculator.java: -------------------------------------------------------------------------------- 1 | /* My code is to create an income tax calculator. 2 | The first step is to ask whether the user is single or married, then based on that information it takes their secondary input (income) and calculates how much tax they must pay. 3 | */ 4 | import java.util.Scanner; 5 | public class IncomeTax_Calculate{ 6 | public static void main(String[] args) { 7 | 8 | Scanner sc=new Scanner(System.in); 9 | System.out.println("Enter your income in lakhs par annum: "); 10 | float tax=0; 11 | float income=sc.nextFloat(); 12 | if (income<=2.5) { 13 | tax = tax + 0; 14 | } 15 | else if (income>5f && income<=10.0f) { 16 | tax=tax+0.05f*(5.0f-2.5f); 17 | tax=tax+0.2f*(income-5f); 18 | }else if (income>10.0f) { 19 | tax=tax+0.05f*(5.0f-2.5f); 20 | tax=tax+0.2f*(10.0f-5f); 21 | tax=tax+0.3f*(income-10.0f); 22 | } 23 | System.out.println("The total tax paid by the employee is : "+tax); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Programs/InsertionSort.java: -------------------------------------------------------------------------------- 1 | //program that demonstrate insertion sort algorithm 2 | import java.util.Arrays; 3 | 4 | public class Main { 5 | //Driver Function 6 | public static void main(String[] args) { 7 | int[] arr = {7, 9, 2, 4, 10}; 8 | insertionSort(arr); 9 | System.out.println(Arrays.toString(arr)); 10 | } 11 | //Insertion Sort Algorithm 12 | static void insertionSort(int[] arr) { 13 | for (int i = 0; i < arr.length - 1; i++) { 14 | for (int j = i+1; j > 0; j--) { 15 | if (arr[j] < arr[j-1]) { 16 | swap(arr, j, j-1); 17 | } 18 | else { 19 | break; 20 | } 21 | } 22 | } 23 | } 24 | //Swapping Algorithm 25 | static void swap(int[] arr, int first, int second) { 26 | int temp = arr[first]; 27 | arr[first] = arr[second]; 28 | arr[second] = temp; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Programs/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | // Java program to implement interpolation 2 | public class InterpolationSearch { 3 | 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int[] arr = {12, 23, 10, 34, 55, 4, 68, 3, 73}; 7 | Arrays.sort(arr); 8 | System.out.println("sorted array- " + Arrays.toString(arr)); 9 | System.out.println("Enter value to search: "); 10 | int searchElement = sc.nextInt(); 11 | int index = interpolationSearch(arr, searchElement); 12 | if(index != -1){ 13 | System.out.println("Searched item " + arr[index] + " found at index "+index); 14 | }else{ 15 | System.out.println("Searched item " + searchElement + " not found in the array"); 16 | } 17 | sc.close(); 18 | } 19 | 20 | private static int interpolationSearch(int[] arr, int searchElement){ 21 | int start = 0; 22 | int end = arr.length - 1; 23 | int position; 24 | while ((arr[end] != arr[start]) && (searchElement >= arr[start]) && (searchElement <= arr[end])) { 25 | position = start + ((searchElement - arr[start]) * (end - start) / (arr[end] - arr[start])); 26 | 27 | if (arr[position] < searchElement) 28 | start = position + 1; 29 | else if (searchElement < arr[position]) 30 | end = position - 1; 31 | else 32 | return position; 33 | } 34 | if (searchElement == arr[start]) 35 | return start ; 36 | else 37 | return -1; 38 | } 39 | } -------------------------------------------------------------------------------- /Programs/JavaClasses.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of classes and objects (basic) - 2 | package classes; 3 | class MyClass { 4 | private int x, y; 5 | // Function to set the values of x and y - 6 | public void set(int m, int n) { 7 | x = m; 8 | y = n; 9 | } 10 | // Function to display the product along with the values of x and y - 11 | public void display() { 12 | System.out.println("The value of x = " + x); 13 | System.out.println("The value of y = " + y); 14 | System.out.println("The product of x and y = " + x * y); 15 | } 16 | } 17 | public class JavaClasses { 18 | public static void main(String[] args) { 19 | // TODO Auto-generated method stub 20 | // Object instantiation - 21 | MyClass obj = new MyClass(); 22 | obj.set(15, 50); 23 | obj.display(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Programs/JavaStreams.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.stream.Collectors; 3 | 4 | /* 5 | A demo for the Java Streams API 6 | Includes examples with lists of numbers and words 7 | */ 8 | public class JavaStreams { 9 | 10 | private static final List numbers = 11 | List.of(10, 2, 21, 23, 22, 14, 16, 18, 19, 9, 4, 6, 7); 12 | 13 | private static final List words = 14 | List.of("apple", "bread", "tree", "computer", "name", "brain", "arm"); 15 | 16 | //Use stream to find all numbers that are greater than 10 17 | public static List findAllNumbersGreaterThanTen(List numbers){ 18 | return numbers.stream() 19 | .filter(number -> number > 10) 20 | .sorted() 21 | .collect(Collectors.toList()); 22 | } 23 | 24 | //Use stream to find all numbers that contain the letter a 25 | public static List findAllWordsThatContainLetterA(List words){ 26 | return words.stream() 27 | .filter(word -> word.contains("a")) 28 | .collect(Collectors.toList()); 29 | } 30 | 31 | //print out the origin lists, and then the changed lists 32 | public static void main(String[] args) { 33 | System.out.println("The unsorted array is: " 34 | + numbers); 35 | 36 | System.out.println("The sorted array is: " 37 | + numbers.stream().sorted().toList()); 38 | 39 | System.out.println("All numbers in the list greater than 10: " 40 | + findAllNumbersGreaterThanTen(numbers)); 41 | 42 | System.out.println(); 43 | 44 | System.out.println("A list of words: " + words); 45 | System.out.println("All words in the list that contain the letter A: " 46 | + findAllWordsThatContainLetterA(words)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Programs/KMP.java: -------------------------------------------------------------------------------- 1 | class KMP{ 2 | String string; 3 | String pattern; 4 | int[] lps; 5 | 6 | KMP(String string,String pattern){ 7 | this.string = string; 8 | this.pattern = pattern; 9 | this.lps = new int[pattern.length()]; 10 | } 11 | 12 | 13 | public int kmp() { 14 | this.createLPS(); 15 | int i = 0,j= 0; 16 | 17 | while(i b)?a:b; 8 | } 9 | 10 | public int knapSack(int W, int wt[], int val[], int n) 11 | { 12 | int i, w; 13 | int[][] K = new int[n+1][W+1]; 14 | for(i=0; i<=n; i++) 15 | { 16 | for(w=0; w<=W; w++) 17 | { 18 | if(i == 0 || w == 0) 19 | { 20 | K[i][w] = 0; 21 | } 22 | else if(wt[i-1] <= w) 23 | { 24 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); 25 | } 26 | else 27 | { 28 | K[i][w] = K[i-1][w]; 29 | } 30 | } 31 | } 32 | return K[n][W]; 33 | } 34 | 35 | public static void main(String[] args) 36 | { 37 | int i, n, W; 38 | Scanner sc = new Scanner(System.in); 39 | System.out.println("Enter the number of items : "); 40 | n = sc.nextInt(); 41 | System.out.println("Enter the maximum weight/capacity : "); 42 | W = sc.nextInt(); 43 | int wt[] = new int[n]; 44 | int val[] = new int[n]; 45 | System.out.println("Enter the weights of the items : "); 46 | for(i=0; i { 7 | int src, dest, weight; 8 | 9 | public int compareTo(Edge compareEdge) { 10 | return this.weight - compareEdge.weight; 11 | } 12 | }; 13 | 14 | // Union 15 | class subset { 16 | int parent, rank; 17 | }; 18 | 19 | int vertices, edges; 20 | Edge edge[]; 21 | 22 | // Graph creation 23 | Graph(int v, int e) { 24 | vertices = v; 25 | edges = e; 26 | edge = new Edge[edges]; 27 | for (int i = 0; i < e; ++i) 28 | edge[i] = new Edge(); 29 | } 30 | 31 | int find(subset subsets[], int i) { 32 | if (subsets[i].parent != i) 33 | subsets[i].parent = find(subsets, subsets[i].parent); 34 | return subsets[i].parent; 35 | } 36 | 37 | void Union(subset subsets[], int x, int y) { 38 | int xroot = find(subsets, x); 39 | int yroot = find(subsets, y); 40 | 41 | if (subsets[xroot].rank < subsets[yroot].rank) 42 | subsets[xroot].parent = yroot; 43 | else if (subsets[xroot].rank > subsets[yroot].rank) 44 | subsets[yroot].parent = xroot; 45 | else { 46 | subsets[yroot].parent = xroot; 47 | subsets[xroot].rank++; 48 | } 49 | } 50 | 51 | // Applying Krushkal Algorithm 52 | void KruskalAlgo() { 53 | Edge result[] = new Edge[vertices]; 54 | int e = 0; 55 | int i = 0; 56 | for (i = 0; i < vertices; ++i) 57 | result[i] = new Edge(); 58 | 59 | // Sorting the edges 60 | Arrays.sort(edge); 61 | subset subsets[] = new subset[vertices]; 62 | for (i = 0; i < vertices; ++i) 63 | subsets[i] = new subset(); 64 | 65 | for (int v = 0; v < vertices; ++v) { 66 | subsets[v].parent = v; 67 | subsets[v].rank = 0; 68 | } 69 | i = 0; 70 | while (e < vertices - 1) { 71 | Edge next_edge = new Edge(); 72 | next_edge = edge[i++]; 73 | int x = find(subsets, next_edge.src); 74 | int y = find(subsets, next_edge.dest); 75 | if (x != y) { 76 | result[e++] = next_edge; 77 | Union(subsets, x, y); 78 | } 79 | } 80 | for (i = 0; i < e; ++i) 81 | System.out.println(result[i].src + " - " + result[i].dest + ": " + result[i].weight); 82 | } 83 | 84 | public static void main(String[] args) { 85 | int vertices = 6; // Number of vertices 86 | int edges = 8; // Number of edges 87 | Graph G = new Graph(vertices, edges); 88 | 89 | G.edge[0].src = 0; 90 | G.edge[0].dest = 1; 91 | G.edge[0].weight = 4; 92 | 93 | G.edge[1].src = 0; 94 | G.edge[1].dest = 2; 95 | G.edge[1].weight = 4; 96 | 97 | G.edge[2].src = 1; 98 | G.edge[2].dest = 2; 99 | G.edge[2].weight = 2; 100 | 101 | G.edge[3].src = 2; 102 | G.edge[3].dest = 3; 103 | G.edge[3].weight = 3; 104 | 105 | G.edge[4].src = 2; 106 | G.edge[4].dest = 5; 107 | G.edge[4].weight = 2; 108 | 109 | G.edge[5].src = 2; 110 | G.edge[5].dest = 4; 111 | G.edge[5].weight = 4; 112 | 113 | G.edge[6].src = 3; 114 | G.edge[6].dest = 4; 115 | G.edge[6].weight = 3; 116 | 117 | G.edge[7].src = 5; 118 | G.edge[7].dest = 4; 119 | G.edge[7].weight = 3; 120 | G.KruskalAlgo(); 121 | } 122 | } -------------------------------------------------------------------------------- /Programs/LinearSearch.java: -------------------------------------------------------------------------------- 1 | class LinearSearch{ 2 | 3 | public static int search(int arr[], int x) 4 | { 5 | int n = arr.length; 6 | for (int i = 0; i < n; i++) 7 | { 8 | if (arr[i] == x) 9 | return i; 10 | } 11 | return -1; 12 | } 13 | 14 | public static void main(String args[]) 15 | { 16 | int arr[] = { 45, 56, 37, 79, 46, 18, 90, 81, 51 }; 17 | int x = 79; 18 | 19 | int result = search(arr, x); 20 | if (result == -1) 21 | System.out.print("\n\nElement is not present in array\n"); 22 | else 23 | System.out.print("\n\nElement is present at index " + result + "\n"); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Programs/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. 3 | A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. 4 | For example, "ace" is a subsequence of "abcde". 5 | A common subsequence of two strings is a subsequence that is common to both strings. 6 | 7 | Example 1: 8 | Input: text1 = "abcde", text2 = "ace" 9 | Output: 3 10 | Explanation: The longest common subsequence is "ace" and its length is 3. 11 | **/ 12 | 13 | class Solution { 14 | public int longestCommonSubsequence(String text1, String text2) { 15 | int m = text1.length(), n = text2.length(); 16 | int mat[][] = new int[m+1][n+1]; 17 | for(int i = 0 ; i<=m;i++) 18 | mat[i][0] = 0; 19 | for(int i = 0 ; i<=n;i++) 20 | mat[0][i] = 0; 21 | for(int i = 1 ; i<=m;i++) { 22 | for(int j = 1 ; j<=n;j++) { 23 | if(text1.charAt(i-1) == text2.charAt(j-1)) 24 | mat[i][j] = mat[i-1][j-1] + 1; 25 | else { 26 | mat[i][j] = Math.max(mat[i-1][j],mat[i][j-1]); 27 | } 28 | } 29 | } 30 | return mat[m][n]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Programs/LuckyNumber.java: -------------------------------------------------------------------------------- 1 | //Program to check if the given number is a lucky number or not 2 | 3 | import java.util.*; 4 | public class LuckyNumber 5 | { 6 | int c = 2; 7 | 8 | //Method to check if the number is a Lucky Number 9 | public boolean checkLucky(int n) 10 | { 11 | if(c > n) 12 | return true; 13 | if(n % c == 0) 14 | return false; 15 | 16 | //Position of the element 17 | n = n - (n/c); 18 | 19 | //Incrementing the counter variable 20 | c++; 21 | return checkLucky(n); 22 | } 23 | 24 | //Main method 25 | public static void main(String[] args) 26 | { 27 | Scanner sc = new Scanner(System.in); 28 | System.out.println("Enter the number to be checked : "); 29 | int a = sc.nextInt(); 30 | LuckyNumber ob = new LuckyNumber(); 31 | boolean res = ob.checkLucky(a); 32 | if(res == true) 33 | { 34 | System.out.println(a+" is a Lucky Number"); 35 | } 36 | else 37 | { 38 | System.out.println(a+" is NOT a Lucky Number"); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Programs/MatrixAdd.java: -------------------------------------------------------------------------------- 1 | // Program to add two matrices in Java - 2 | package matrix; 3 | import java.util.Scanner; 4 | public class MatrixAdd { 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | int arr1[][] = new int[10][10]; // New 2D array for first matrix 9 | int arr2[][] = new int[10][10]; // New 2D array for second matrix 10 | int sum[][] = new int[10][10]; // New 2D array for sum of the two matrices 11 | int i, j; 12 | // Taking details of first matrix - 13 | System.out.println("Enter details for first matrix: "); 14 | for (i = 0; i < 2; i++) { 15 | for (j = 0; j < 2; j++) { 16 | System.out.println("Enter number: "); 17 | arr1[i][j] = sc.nextInt(); 18 | } 19 | } 20 | // Taking details of second matrix - 21 | System.out.println("Enter details for second matrix: "); 22 | for (i = 0; i < 2; i++) { 23 | for (j = 0; j < 2; j++) { 24 | System.out.println("Enter number: "); 25 | arr2[i][j] = sc.nextInt(); 26 | } 27 | } 28 | System.out.println("Displaying addition of two matrices: "); 29 | // Performing addition of two matrices - 30 | for (i = 0; i < 2; i++) { 31 | for (j = 0; j < 2; j++) { 32 | sum[i][j] = arr1[i][j] + arr2[i][j]; 33 | } 34 | } 35 | // Displaying addition of two matrices - 36 | for (i = 0; i < 2; i++) { 37 | for (j = 0; j < 2; j++) { 38 | System.out.print(sum[i][j] + " "); 39 | } 40 | System.out.println(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Programs/Mcolor.java: -------------------------------------------------------------------------------- 1 | // Java program for m coloring problem 2 | 3 | public class Mcolor { 4 | 5 | // Number of vertices in the graph 6 | static int V = 4; 7 | 8 | /* A utility function to print solution */ 9 | static void printSolution(int[] color) 10 | { 11 | System.out.println( 12 | "Solution Exists:" 13 | + " Following are the assigned colors "); 14 | for (int i = 0; i < V; i++) 15 | System.out.print(" " + color[i]); 16 | System.out.println(); 17 | } 18 | 19 | // check if the colored 20 | // graph is safe or not 21 | static boolean isSafe(boolean[][] graph, int[] color) 22 | { 23 | // check for every edge 24 | for (int i = 0; i < V; i++) 25 | for (int j = i + 1; j < V; j++) 26 | if (graph[i][j] && color[j] == color[i]) 27 | return false; 28 | return true; 29 | } 30 | 31 | /* This function solves the m Coloring 32 | problem using recursion. It returns 33 | false if the m colours cannot be assigned, 34 | otherwise, return true and prints 35 | assignments of colours to all vertices. 36 | Please note that there may be more than 37 | one solutions, this function prints one 38 | of the feasible solutions.*/ 39 | static boolean graphColoring(boolean[][] graph, int m, 40 | int i, int[] color) 41 | { 42 | // if current index reached end 43 | if (i == V) { 44 | 45 | // if coloring is safe 46 | if (isSafe(graph, color)) { 47 | 48 | // Print the solution 49 | printSolution(color); 50 | return true; 51 | } 52 | return false; 53 | } 54 | 55 | // Assign each color from 1 to m 56 | for (int j = 1; j <= m; j++) { 57 | color[i] = j; 58 | 59 | // Recur of the rest vertices 60 | if (graphColoring(graph, m, i + 1, color)) 61 | return true; 62 | color[i] = 0; 63 | } 64 | return false; 65 | } 66 | 67 | // Driver code 68 | public static void main(String[] args) 69 | { 70 | 71 | /* Create following graph and 72 | test whether it is 3 colorable 73 | (3)---(2) 74 | | / | 75 | | / | 76 | | / | 77 | (0)---(1) 78 | */ 79 | boolean[][] graph = { 80 | { false, true, true, true }, 81 | { true, false, true, false }, 82 | { true, true, false, true }, 83 | { true, false, true, false }, 84 | }; 85 | int m = 3; // Number of colors 86 | 87 | // Initialize all color values as 0. 88 | // This initialization is needed 89 | // correct functioning of isSafe() 90 | int[] color = new int[V]; 91 | for (int i = 0; i < V; i++) 92 | color[i] = 0; 93 | 94 | // Function call 95 | if (!graphColoring(graph, m, 0, color)) 96 | System.out.println("Solution does not exist"); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Programs/MergeKsortedLists.java: -------------------------------------------------------------------------------- 1 | //Contributed by Dev jr - https://github.com/Dev-jr-8 2 | 3 | class Solution 4 | { 5 | //Function to merge K sorted linked list. 6 | //Logic for merging two sorted linked list 7 | Node mergetwolist(Node head1, Node head2) 8 | { 9 | Node a = head1; 10 | Node b = head2; 11 | Node head = null; 12 | Node tail = null; 13 | 14 | if(a==null)return b; 15 | if(b==null)return a; 16 | 17 | if(a.data 0) 101 | { 102 | int N = sc.nextInt(); 103 | 104 | Node []a = new Node[N]; 105 | 106 | for(int i = 0; i < N; i++) 107 | { 108 | int n = sc.nextInt(); 109 | 110 | Node head = new Node(sc.nextInt()); 111 | Node tail = head; 112 | 113 | for(int j=0; j `III`, 11 | * num = 58 --> `LVIII` 12 | * 13 | * @param num 14 | * @return String 15 | */ 16 | 17 | public static String intToRoman(int num) { 18 | Map map = new HashMap(); 19 | map.put(1, "I"); 20 | map.put(4, "IV"); 21 | map.put(5, "V"); 22 | map.put(9, "IX"); 23 | map.put(10, "X"); 24 | map.put(40, "XL"); 25 | map.put(50, "L"); 26 | map.put(90, "XC"); 27 | map.put(100, "C"); 28 | map.put(400, "CD"); 29 | map.put(500, "D"); 30 | map.put(900, "CM"); 31 | map.put(1000, "M"); 32 | 33 | List mapKeys = Arrays.asList(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); 34 | int remainder = num; 35 | StringBuilder result = new StringBuilder(""); 36 | int mapKeysIndex = 0; 37 | 38 | while (remainder != 0) { 39 | int currentComparison = mapKeys.get(mapKeysIndex); 40 | if (remainder < currentComparison) { 41 | mapKeysIndex++; 42 | continue; 43 | } 44 | 45 | result.append(map.get(currentComparison)); 46 | remainder = remainder - currentComparison; 47 | } 48 | 49 | return result.toString(); 50 | } 51 | 52 | public static void main(String[] args) { 53 | Scanner sc = new Scanner(System.in); 54 | while (true) { 55 | try { 56 | System.out.println("Please enter an Integer value"); 57 | int num = Integer.parseInt(sc.next()); 58 | System.out.println(intToRoman(num)); 59 | } catch (Exception e) { 60 | System.out.println("Something went wrong, please make sure to enter integer only"); 61 | } 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Programs/Overriding.java: -------------------------------------------------------------------------------- 1 | class Human{ 2 | //Overridden method 3 | public void eat() 4 | { 5 | System.out.println("Human is eating"); 6 | } 7 | } 8 | class Boy extends Human{ 9 | //Overriding method 10 | public void eat(){ 11 | System.out.println("Boy is eating"); 12 | } 13 | public static void main( String args[]) { 14 | Boy obj = new Boy(); 15 | //This will call the child class version of eat() 16 | obj.eat(); 17 | } 18 | } -------------------------------------------------------------------------------- /Programs/Palindrome.java: -------------------------------------------------------------------------------- 1 | /* A Palindrome number is a number that remains unchanged when reversed. 2 | EXAMPLE: 3 | 121 is a palindrome because its reverse ie '121' is same as the original number. 4 | 123 is NOT a palindrome because its reverse i.e. '321' is not same as the original number '123'. 5 | */ 6 | 7 | import java.util.*; 8 | 9 | public class Palindrome { 10 | 11 | public static void main(String[] args) 12 | { 13 | Scanner sc=new Scanner(System.in); 14 | int n=sc.nextInt(); 15 | int copy=n; 16 | int r=0,d=0; 17 | while(n>0) 18 | { 19 | d=n%10; 20 | r=10*r+d; 21 | n=n/10; 22 | } 23 | if(r==copy) 24 | { 25 | System.out.println(copy+" is a palindrome number"); 26 | } 27 | else{ 28 | System.out.println(copy+" is not a palindrome number"); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Programs/PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | // A Java program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | // The program is for adjacency matrix representation of the graph 3 | 4 | import java.util.*; 5 | import java.lang.*; 6 | import java.io.*; 7 | 8 | class MST { 9 | // Number of vertices in the graph 10 | private static final int V = 5; 11 | 12 | // A utility function to find the vertex with minimum key 13 | // value, from the set of vertices not yet included in MST 14 | int minKey(int key[], Boolean mstSet[]) 15 | { 16 | // Initialize min value 17 | int min = Integer.MAX_VALUE, min_index = -1; 18 | 19 | for (int v = 0; v < V; v++) 20 | if (mstSet[v] == false && key[v] < min) { 21 | min = key[v]; 22 | min_index = v; 23 | } 24 | 25 | return min_index; 26 | } 27 | 28 | // A utility function to print the constructed MST stored in 29 | // parent[] 30 | void printMST(int parent[], int graph[][]) 31 | { 32 | System.out.println("Edge \tWeight"); 33 | for (int i = 1; i < V; i++) 34 | System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); 35 | } 36 | 37 | // Function to construct and print MST for a graph represented 38 | // using adjacency matrix representation 39 | void primMST(int graph[][]) 40 | { 41 | // Array to store constructed MST 42 | int parent[] = new int[V]; 43 | 44 | // Key values used to pick minimum weight edge in cut 45 | int key[] = new int[V]; 46 | 47 | // To represent set of vertices included in MST 48 | Boolean mstSet[] = new Boolean[V]; 49 | 50 | // Initialize all keys as INFINITE 51 | for (int i = 0; i < V; i++) { 52 | key[i] = Integer.MAX_VALUE; 53 | mstSet[i] = false; 54 | } 55 | 56 | // Always include first 1st vertex in MST. 57 | key[0] = 0; // Make key 0 so that this vertex is 58 | // picked as first vertex 59 | parent[0] = -1; // First node is always root of MST 60 | 61 | // The MST will have V vertices 62 | for (int count = 0; count < V - 1; count++) { 63 | // Pick thd minimum key vertex from the set of vertices 64 | // not yet included in MST 65 | int u = minKey(key, mstSet); 66 | 67 | // Add the picked vertex to the MST Set 68 | mstSet[u] = true; 69 | 70 | // Update key value and parent index of the adjacent 71 | // vertices of the picked vertex. Consider only those 72 | // vertices which are not yet included in MST 73 | for (int v = 0; v < V; v++) 74 | 75 | // graph[u][v] is non zero only for adjacent vertices of m 76 | // mstSet[v] is false for vertices not yet included in MST 77 | // Update the key only if graph[u][v] is smaller than key[v] 78 | if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { 79 | parent[v] = u; 80 | key[v] = graph[u][v]; 81 | } 82 | } 83 | 84 | // print the constructed MST 85 | printMST(parent, graph); 86 | } 87 | 88 | public static void main(String[] args) 89 | { 90 | MST t = new MST(); 91 | int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, 92 | { 2, 0, 3, 8, 5 }, 93 | { 0, 3, 0, 0, 7 }, 94 | { 6, 8, 0, 0, 9 }, 95 | { 0, 5, 7, 9, 0 } }; 96 | 97 | // Print the solution 98 | t.primMST(graph); 99 | } 100 | } 101 | // This code is contributed by Samrat Mitra 102 | -------------------------------------------------------------------------------- /Programs/PrintPattern.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Program to print a pattern using nested for loops 3 | * eg:- * 4 | * * * 5 | * * * * 6 | * * * * * 7 | * * * * * * 8 | * @author arshcoder13 - https://github.com/arshcoder13/ 9 | **/ 10 | 11 | public class PrintPattern { 12 | 13 | public static void main(String args[]){ 14 | 15 | for(int i=1;i<=5;i++){ 16 | for(int j=1;j<=i;j++){ 17 | System.out.print("* "); 18 | } 19 | System.out.println(); 20 | } 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Programs/QuickSort.java: -------------------------------------------------------------------------------- 1 | //Quick Sort 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | 7 | 8 | public class QuickSort{ 9 | public static void main(String args[]){ 10 | int arr[]= {-1,-2,42,1,24,44,32,0,12,100}; 11 | quickSort(arr,0,arr.length-1); 12 | System.out.println(Arrays.toString(arr)); 13 | } 14 | 15 | 16 | public static void quickSort(int arr[],int i, int j){ 17 | int pivot = i; 18 | if(i=arr.length){ 27 | return arr; 28 | } 29 | while(arr[i] < arr[pivot]){ 30 | i++; 31 | } 32 | while(arr[j]> arr[pivot]){ 33 | j--; 34 | } 35 | if(i 3 || user < 1) { 11 | System.out.println("Plz type valid input"); 12 | return; 13 | } 14 | 15 | Random random = new Random(); 16 | int computer = random.nextInt(1, 4); 17 | System.out.println("YOU CHOOSE: "+user); 18 | System.out.println("Computer Choose: "+computer); 19 | 20 | if (user == 1 && computer == 1 || user == 2 && computer == 2 || user == 3 && computer == 3) { 21 | System.out.println("Match Tie"); 22 | } else if (user == 1 && computer == 3 || user == 2 && computer == 1 || user == 3 && computer == 2) { 23 | System.out.println("Hurray! YOU WIN"); 24 | } else { 25 | System.out.println("Better luck next Time: Computer WIN"); 26 | } 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Programs/RotateLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | **/ 6 | class SinglyLinkedNode { 7 | int val; 8 | SinglyLinkedNode next; 9 | 10 | public SinglyLinkedNode(int val) { 11 | this.val = val; 12 | } 13 | } 14 | 15 | /** 16 | * This is a program to demo rotating a singly linked list. 17 | * @see LeetCode 19 | * description 20 | * Time complexity O(n), Space O(1) 21 | */ 22 | public class RotateLinkedList { 23 | public static void main(String[] args) { 24 | try (Scanner sc = new Scanner(System.in)) { 25 | System.out.println("Enter the LinkedList in the form of [1,2,3,4,5]"); 26 | String input = sc.nextLine(); 27 | System.out.println("Enter the number of rotations"); 28 | int k = sc.nextInt(); 29 | String str = input.replaceAll(" ", "") .substring(1, input.length() - 1); 30 | String[] nodesStr = str.split(","); 31 | if (nodesStr.length == 0) { 32 | System.out.println("[]"); 33 | return; 34 | } 35 | 36 | SinglyLinkedNode head = buildLinkedList(nodesStr); 37 | RotateLinkedList solution = new RotateLinkedList(); 38 | SinglyLinkedNode newHead = solution.rotateRight(head, k); 39 | printOutput(newHead); 40 | } catch (Exception e) { 41 | System.out.println( 42 | "Something went wrong. Check the linkedlist format is in the form of [1,2,3,4,5] and rotation is an integer"); 43 | } 44 | } 45 | 46 | private static SinglyLinkedNode buildLinkedList(String[] nodesStr) { 47 | SinglyLinkedNode head = null; 48 | SinglyLinkedNode node = null; 49 | for (int i = 0; i < nodesStr.length; i++) { 50 | SinglyLinkedNode newNode = new SinglyLinkedNode(Integer.valueOf(nodesStr[i])); 51 | if (i == 0) { 52 | head = newNode; 53 | } 54 | 55 | if (node == null) { 56 | node = newNode; 57 | } else { 58 | node.next = newNode; 59 | node = newNode; 60 | } 61 | } 62 | 63 | return head; 64 | } 65 | 66 | private static void printOutput(SinglyLinkedNode newHead) { 67 | System.out.print("["); 68 | do { 69 | System.out.print(newHead.val); 70 | newHead = newHead.next; 71 | if (newHead != null) { 72 | System.out.print(","); 73 | } 74 | } while(newHead != null); 75 | System.out.println("]"); 76 | } 77 | 78 | /** 79 | * Given the head of a linked list, rotate the list to the right by k places. 80 | * @param head 81 | * @param k 82 | * @return head of linked list 83 | */ 84 | public SinglyLinkedNode rotateRight(SinglyLinkedNode head, int k) { 85 | if (k == 0 || head == null || head.next == null) { 86 | return head; 87 | } 88 | 89 | // Finding the size of the list 90 | int size = 1; // start with 1 because we're starting with head 91 | SinglyLinkedNode currentEnd = head; 92 | while (currentEnd.next != null) { 93 | currentEnd = currentEnd.next; 94 | size++; 95 | } 96 | 97 | // linking the end to the head 98 | currentEnd.next = head; 99 | 100 | // determine the rotation based on k 101 | int rotate = 0; 102 | if (k < size) { 103 | rotate = k; 104 | } else { 105 | rotate = k % size; 106 | } 107 | 108 | // Find the index of the end node 109 | int endNode = size - rotate; 110 | 111 | // set the newEnd to head and loop until you get to the new end node 112 | SinglyLinkedNode newEnd = head; 113 | for (int i = 1; i < endNode; i++) { 114 | newEnd = newEnd.next; 115 | } 116 | 117 | // set the new head node and terminate the new end node 118 | SinglyLinkedNode newHead = newEnd.next; 119 | newEnd.next = null; 120 | return newHead; 121 | } 122 | } -------------------------------------------------------------------------------- /Programs/SelectionSort.java: -------------------------------------------------------------------------------- 1 | // Java program that implements selection sort 2 | // Best case : O(N^2) 3 | // Average case : O(N^2) 4 | // Worst case : O(N^2) 5 | 6 | import java.util.Arrays; 7 | public class SelectionSortMain { 8 | 9 | public static int[] selectionSort(int[] arr){ 10 | 11 | for (int i = 0; i < arr.length - 1; i++) 12 | { 13 | int index = i; 14 | for (int j = i + 1; j < arr.length; j++) 15 | if (arr[j] < arr[index]) 16 | index = j; 17 | 18 | int smallerNumber = arr[index]; 19 | arr[index] = arr[i]; 20 | arr[i] = smallerNumber; 21 | } 22 | return arr; 23 | } 24 | 25 | public static void main(String a[]){ 26 | int[] arr = {40,10,-30,45,39,32}; 27 | System.out.println("Before Sorting : "); 28 | System.out.println(Arrays.toString(arr)); 29 | arr = selectionSort(arr); 30 | System.out.println("==================="); 31 | System.out.println("After Sorting : "); 32 | System.out.println(Arrays.toString(arr)); 33 | } 34 | } -------------------------------------------------------------------------------- /Programs/ShellSort.java: -------------------------------------------------------------------------------- 1 | // Program that implements Shell Sort (Invented by Donald Shell) 2 | import java.util.Arrays; 3 | 4 | public class ShellSortMain { 5 | public static void main(String[] args) { 6 | int[] array = { 22, 53, 33, 12, 75, 65, 887, 125, 37, 977 }; 7 | System.out.println("Before Sorting : "); 8 | System.out.println(Arrays.toString(array)); 9 | System.out.println("==================="); 10 | System.out.println("After Sorting : "); 11 | array = shellsort(array); 12 | System.out.println(Arrays.toString(array)); 13 | } 14 | 15 | private static int[] shellsort(int[] array) { 16 | 17 | // first part uses the Knuth's interval sequence 18 | int h = 1; 19 | while (h <= array.length / 3) { 20 | h = 3 * h + 1; 21 | } 22 | 23 | while (h > 0) { 24 | 25 | for (int i = 0; i < array.length; i++) { 26 | 27 | int temp = array[i]; 28 | int j; 29 | 30 | for (j = i; j > h - 1 && array[j - h] >= temp; j = j - h) { 31 | array[j] = array[j - h]; 32 | } 33 | array[j] = temp; 34 | } 35 | h = (h - 1) / 3; 36 | } 37 | return array; 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /Programs/Sieve_Of_Eratosthenes.java: -------------------------------------------------------------------------------- 1 | // Program to find all the primes upto N using Sieve Of Eratosthenes technique. 2 | // A number is called prime if it has only two factors (1 and the number itself) 3 | import java.util.*; 4 | public class Sieve_Of_Eratosthenes 5 | { 6 | public static void main(String args[]) 7 | { 8 | Scanner sc=new Scanner(System.in); 9 | Sieve_Of_Eratosthenes nm=new Sieve_Of_Eratosthenes(); 10 | int n=sc.nextInt(); 11 | // input taken upto which primes which will be displayed 12 | boolean k[]=nm.sieve_Of_Eratosthenes(n); 13 | // method calling where an integer value is sent and a boolean array is stored as a return value 14 | for(int i=0;i<=20000000;i++) 15 | { 16 | if(k[i]) 17 | { 18 | System.out.print(i+" "); 19 | } 20 | } 21 | System.out.println(); 22 | } 23 | boolean[] sieve_Of_Eratosthenes(int n) 24 | { 25 | boolean b[]=new boolean[n+1]; 26 | // boolean array is created 27 | Arrays.fill(b,true); 28 | b[0]=false; 29 | b[1]=false; 30 | // 0 & 1 are marked as false because they are neither prime nor composite 31 | for(int i=2;i<=Math.sqrt(n);i++) 32 | { 33 | // loop is started from 2 34 | if(b[i]) 35 | { 36 | for(int j=i*i;j<=n;j+=i) 37 | { 38 | // every multiple of the ith value is marked as false because they have a factor i 39 | b[j]=false; 40 | } 41 | } 42 | } 43 | return b; 44 | // boolean array is returned 45 | } 46 | } -------------------------------------------------------------------------------- /Programs/SortNonBoundary.java: -------------------------------------------------------------------------------- 1 | //Program to sort non-boundary elements in square matrix with print diagonal elements of matrix and sum of diagonal elements. 2 | 3 | import java.util.Scanner; 4 | class SortNonBoundary 5 | { 6 | Scanner sc=new Scanner(System.in); 7 | int A[][],B[],m,n; 8 | void input() 9 | { 10 | Scanner sc = new Scanner(System.in); 11 | System.out.print("Enter the size of the square matrix : "); 12 | m=sc.nextInt(); 13 | if(m<4 || m>10) 14 | { 15 | System.out.println("Invalid Range"); 16 | System.exit(0); 17 | } 18 | else 19 | { 20 | A = new int[m][m]; 21 | n = (m-2)*(m-2); 22 | B = new int[n]; 23 | System.out.println("Enter the elements of the Matrix : "); 24 | for(int i=0;iB[j]) 60 | { 61 | c = B[i]; 62 | B[i] = B[j]; 63 | B[j] = c; 64 | } 65 | } 66 | } 67 | } 68 | void printArray() 69 | { 70 | for(int i=0;i "); 19 | int desiredFunction = sc.nextInt(); 20 | choose(desiredFunction, tasks, sc); 21 | } 22 | 23 | public static void choose(int desiredFunction, ArrayList tasks, Scanner sc) { 24 | if (desiredFunction == 1) { 25 | viewTask(tasks); 26 | } else if (desiredFunction == 2) { 27 | addTask(tasks); 28 | } else if (desiredFunction == 3) { 29 | deleteTasks(tasks); 30 | } else { 31 | System.out.println("Please choose in the range of 1 till 3 only!"); 32 | list(tasks); 33 | } 34 | } 35 | 36 | static void addTask(ArrayList tasks) { 37 | Scanner sc = new Scanner(System.in); 38 | System.out.print("Task to save\n> "); 39 | tasks.add(sc.nextLine()); 40 | System.out.print("Add more?\n 1- Yes\n 2- No\n> "); 41 | int yn = sc.nextInt(); 42 | if (yn == 1) { 43 | addTask(tasks); 44 | } else if (yn == 2){ 45 | list(tasks); 46 | } else { 47 | System.out.println("Invalid number!"); 48 | addTask(tasks); 49 | } 50 | } 51 | 52 | static void viewTask(ArrayList tasks) { 53 | if (tasks.isEmpty()) { 54 | System.out.println(""" 55 | -------------------- 56 | No current tasks! 57 | --------------------"""); 58 | } else { 59 | System.out.println(""" 60 | -------------------- 61 | Tasks 62 | --------------------"""); 63 | int counter = 1; 64 | for (int i = 0; i < tasks.size(); i++) { 65 | System.out.println(counter + "- " + tasks.get(i)); 66 | counter++; 67 | } 68 | } 69 | System.out.println("\nSelect from the following commands:"); 70 | list(tasks); 71 | } 72 | 73 | static void deleteTasks(ArrayList tasks) { 74 | tasks.clear(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Programs/Trie_Implementation.java: -------------------------------------------------------------------------------- 1 | //This Java program demonstrates the implemntation of Trie Data structure in Java 2 | //This Implementation only supports lowercase letters 3 | 4 | class TrieNode{ 5 | TrieNode [] children= new TrieNode[26]; //Children a array of TrieNode pointers 6 | boolean isEnd; //a boolean variable used to indicate the end of the current word 7 | } 8 | 9 | 10 | class Trie{ 11 | TrieNode root; //Root of our Trie 12 | 13 | public Trie(){ 14 | root= new TrieNode(); //Intializing the root of our Trie 15 | } 16 | 17 | //This function insert the given word into our Trie 18 | public void insert(String word){ 19 | TrieNode curr= root;//get the root and create curr node to perform the operation 20 | 21 | for(int i=0; i "+isPresent); //Prints true as the word is exists 89 | 90 | boolean isStartsWith= t.startsWith("hack"); //Checks if any word starts with hack 91 | System.out.println("is there any word in our Trie that starts with hack => "+ isStartsWith); //Prints true 92 | 93 | boolean isPresent2= t.search("hecktoberFest"); 94 | System.out.println("is hecktoberfest present in our Trie => "+ isPresent2); //Printts false since there is no word with hecktoberfest 95 | 96 | t.delete("hacktoberfest"); //Delete the word from our Trie 97 | boolean isPresentAfterDeleting= t.search("hacktoberfest"); 98 | System.out.println("is hacktoberfest present in our Trie => "+ isPresentAfterDeleting); //Prints false as the word has been deleted 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Programs/TwoDArrays.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate 2D arrays (Hard-coded) - 2 | // package TwoDArrays; 3 | class TwoD { 4 | private int i, j; 5 | // Initializing new array of the order 2 X 2 6 | private int arr[][] = new int[10][10]; 7 | public void assign() { 8 | 9 | System.out.println("Assigning numbers to array: "); 10 | // Assigning numbers to array 11 | int n = 5; 12 | for (i = 0; i <= 3; i++) { 13 | for (j = 0; j <= 3; j++) { 14 | arr[i][j] = n * 2; 15 | n += 5; 16 | } 17 | } 18 | } 19 | public void display() { 20 | // Displaying array 21 | System.out.println("Displaying array: "); 22 | for (i = 1; i <= 3; i++) { 23 | for (j = 1; j <= 3; j++) { 24 | System.out.println("2D Array: " + "["+i+"]" + "["+j+"] : " + arr[i][j]); 25 | } 26 | } 27 | } 28 | } 29 | 30 | public class TwoDArrays { 31 | public static void main(String[] args) { 32 | // TODO Auto-generated method stub 33 | TwoD obj = new TwoD(); 34 | obj.assign(); 35 | obj.display(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Programs/TwoElementsOccurOnceWhileOthersOccurTwice.java: -------------------------------------------------------------------------------- 1 | // Fin the two non-repeating elements in an array where elements occur two times. 2 | package BitManipulation; 3 | import java.util.*; 4 | import java.lang.*; 5 | 6 | public class TwoElementsOccurOnceWhileOthersOccurTwice { 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of elements in the array:"); 10 | int n = sc.nextInt(); 11 | System.out.println("Enter the elements:"); 12 | int[] a = new int[n]; 13 | for(int i=0 ; i nm=new HashMap<>(); 30 | // hashmap is created to store the array elements 31 | int array[]=new int[2]; 32 | int k=n.length; 33 | for(int i=0;i= arr[1] <= arr[2] >= arr[3] <= arr[4].... 15 | void sortInWave(int[] arr, int n) { 16 | // Traverse all even elements 17 | for (int i = 0; i < n; i += 2) { 18 | // If current even element is smaller 19 | // than previous 20 | if (i > 0 && arr[i - 1] > arr[i]) 21 | swap(arr, i - 1, i); 22 | 23 | // If current even element is smaller 24 | // than next 25 | if (i < n - 1 && arr[i] < arr[i + 1]) 26 | swap(arr, i, i + 1); 27 | } 28 | } 29 | } 30 | public class WiggleSorting { 31 | public static void main(String[] args) { 32 | // What is wiggle sort? 33 | // 1.To sort an array in waveform. 34 | // 2.The array’s elements shall be ordered such that, 35 | // arr[0]arr[2]0) 18 | { 19 | int n=Integer.parseInt(br.readLine()); 20 | String s=br.readLine(); 21 | int count1=0,count2=0; 22 | for(int i=0;i cars = new ArrayList(); 7 | cars.add("Mercedes"); // adds elements to the ArrayList 8 | cars.add("Audi"); 9 | cars.add("Ferrari"); 10 | cars.add("Jaguar"); 11 | System.out.println(cars.isEmpty()); // prints true if list is empty or false if elements are present 12 | System.out.println(cars.size()); // prints the size / number of elements present in the list 13 | System.out.println(cars); // prints the entire list 14 | System.out.println(cars.get(0)); // prints element at 0th index of ArrayList 15 | cars.set(1, "Bugatti"); // changes value of the element at the specified index 16 | System.out.println(cars); 17 | // loop through the ArrayList 18 | for (int i = 0; i < cars.size(); i++) { 19 | System.out.println(cars.get(i)); 20 | } 21 | Collections.sort(cars); // sort method from collections class is used to sort the elements in the list alphabetically/numerically 22 | System.out.println(cars); 23 | cars.clear(); // clears the list 24 | System.out.println(cars); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Programs/arrayOutOfBounds.java: -------------------------------------------------------------------------------- 1 | // Program to show ArrayOutOfBoundsException Error handling - 2 | package arrayOutOfBounds; 3 | public class ArrayOutOfBounds { 4 | 5 | public static void main(String[] args) { 6 | int arr[] = new int[20]; 7 | try { 8 | arr[22] = 60; 9 | } 10 | catch(ArrayIndexOutOfBoundsException e) { 11 | System.out.println("Enception occured"); 12 | } 13 | System.out.println("Quit"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Programs/bookShop.java: -------------------------------------------------------------------------------- 1 | package bookShop; 2 | import java.util.Scanner; 3 | 4 | // class for book shop inventory management- 5 | public class bookShop { 6 | Scanner sc = new Scanner(System.in); 7 | String genre; // genre of book 8 | int engg; // engineering genre 9 | int nonfiction; // non-fiction genre 10 | int fiction; // fiction genre 11 | int childrens; // children's genre 12 | int comics; // comics genre 13 | int classics; // classics genre 14 | int ch; 15 | 16 | // constructor for initializing genres to 0 - 17 | bookShop() { 18 | engg = 0; 19 | nonfiction = 0; 20 | fiction = 0; 21 | childrens = 0; 22 | } 23 | 24 | // function to add books to stock - 25 | public void addToStock() { 26 | System.out.println("Menu: "); 27 | System.out.println("1. Engineering"); 28 | System.out.println("2. Non-fiction"); 29 | System.out.println("3. Fiction"); 30 | System.out.println("4. Children's "); 31 | System.out.println("5. Comics"); 32 | System.out.println("6. Classics"); 33 | System.out.println("7. Exit"); 34 | do { 35 | System.out.println("Enter genre of book: "); 36 | ch = sc.nextInt(); 37 | switch (ch) { 38 | case 1: 39 | engg++; 40 | break; 41 | case 2: 42 | nonfiction++; 43 | break; 44 | case 3: 45 | fiction++; 46 | break; 47 | case 4: 48 | childrens++; 49 | break; 50 | case 5: 51 | comics++; 52 | break; 53 | case 6: 54 | classics++; 55 | break; 56 | default: 57 | if (ch != 7) { 58 | System.out.println("Invalid input! Please enter correct choice!"); 59 | } 60 | } 61 | } while (ch != 7); 62 | } 63 | 64 | // function to update inventory - 65 | public void updateInventory() { 66 | System.out.println("Menu: "); 67 | System.out.println("1. Engineering"); 68 | System.out.println("2. Non-fiction"); 69 | System.out.println("3. Fiction"); 70 | System.out.println("4. Children's "); 71 | System.out.println("5. Comics"); 72 | System.out.println("6. Classics"); 73 | System.out.println("7. Exit"); 74 | do { 75 | System.out.println("Enter genre of book that was purchased by customer: "); 76 | ch = sc.nextInt(); 77 | switch (ch) { 78 | case 1: 79 | engg--; 80 | break; 81 | case 2: 82 | nonfiction--; 83 | break; 84 | case 3: 85 | fiction--; 86 | break; 87 | case 4: 88 | childrens--; 89 | break; 90 | case 5: 91 | comics--; 92 | break; 93 | case 6: 94 | classics--; 95 | break; 96 | default: 97 | if (ch != 7) { 98 | System.out.println("Invalid input! Please enter correct choice!"); 99 | } 100 | } 101 | } while (ch != 7); 102 | } 103 | 104 | // function to display details of book inventory - 105 | public void displayInventory() { 106 | System.out.println("Displaying inventory details: "); 107 | System.out.println("Number of books available in inventory - "); 108 | System.out.println("Genre \t No. of books"); 109 | System.out.println("Engineering: \t" + engg); 110 | System.out.println("Non-Fiction: \t" + nonfiction); 111 | System.out.println("Fiction: \t" + fiction); 112 | System.out.println("Children's: \t" + childrens); 113 | System.out.println("Comics: \t" + comics); 114 | System.out.println("Classics: \t" + classics); 115 | } 116 | 117 | public static void main(String[] args) { 118 | Scanner sc = new Scanner(System.in); 119 | System.out.println("Welcome to book shop inventory management portal!"); 120 | bookShop book = new bookShop(); 121 | int choice; 122 | do { 123 | System.out.println("What do you want to do?"); 124 | System.out.println("1. Add to stock"); 125 | System.out.println("2. Update inventory"); 126 | System.out.println("3. Display inventory details"); 127 | System.out.println("4. Exit portal"); 128 | System.out.print("Enter your choice: "); 129 | choice = sc.nextInt(); 130 | switch (choice) { 131 | case 1: 132 | book.addToStock(); 133 | break; 134 | case 2: 135 | book.updateInventory(); 136 | break; 137 | case 3: 138 | book.displayInventory(); 139 | break; 140 | default: 141 | if (choice != 4) { 142 | System.out.println("Invalid Input!"); 143 | } 144 | } 145 | } while (choice != 4); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Programs/constructors.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of constructors in Java - 2 | class Area { 3 | int length, breadth; 4 | // Parameterized constructor 5 | Area(int m, int n) { 6 | length = m; 7 | breadth = n; 8 | } 9 | // Function to calculate area of rectangle 10 | void rectArea(Area a) { 11 | System.out.println("Length = " + a.length); // Printing length 12 | System.out.println("Breadth = " + a.breadth); // Printing breadth 13 | int area = a.length * a.breadth; // Calculating area 14 | System.out.println("Area of rectangle is: " + area); // Printing area 15 | } 16 | } 17 | 18 | public class constructors { 19 | public static void main(String[] args) { 20 | // TODO Auto-generated method stub 21 | Area rect1 = new Area(50, 25); // Object 1 instantiation 22 | Area rect2 = new Area(30, 60); // Object 2 instantiation 23 | rect1.rectArea(rect1); // Function call to calculate and print area of first object 24 | rect2.rectArea(rect2); // Function call to calculate and print area of second object 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Programs/derivedConstructor.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the order of constructor call - 2 | package derivedConstructor; 3 | 4 | class Base { 5 | public Base() { 6 | System.out.println("Base class constructor called!"); // Will be called first 7 | } 8 | public Base(int x) { 9 | System.out.println(x); 10 | } 11 | } 12 | class Derived extends Base { 13 | public Derived() { 14 | System.out.println("Derived class constructor called!"); // Will be called after base class constructor 15 | } 16 | } 17 | class Derived1 extends Derived { 18 | public Derived1() { 19 | System.out.println("Derived1 class constructor called!"); // Will be called after the first derived class 20 | } 21 | } 22 | public class DerivedConstructors { 23 | public static void main(String[] args) { 24 | // TODO Auto-generated method stub 25 | Derived1 obj = new Derived1(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Programs/eduInstitute.java: -------------------------------------------------------------------------------- 1 | package realWorldScenario; 2 | import java.util.Scanner; 3 | 4 | class Person { 5 | Scanner sc = new Scanner(System.in); 6 | public String name; 7 | public int id; 8 | } 9 | 10 | class Student extends Person { 11 | public int year; 12 | public String course; 13 | void getDetails() { 14 | System.out.println("Enter name: "); 15 | name = sc.nextLine(); 16 | System.out.println("Enter id: "); 17 | id = sc.nextInt(); 18 | System.out.println("Enter year: "); 19 | year = sc.nextInt(); 20 | System.out.println("Enter course: "); 21 | course = sc.next(); 22 | System.out.println(); 23 | } 24 | void display() { 25 | System.out.println("Displaying student details: "); 26 | System.out.println("Name: " + name); 27 | System.out.println("ID: " + id); 28 | System.out.println("Year: " + year); 29 | System.out.println("Course: " + course); 30 | } 31 | } 32 | 33 | class Teacher extends Person { 34 | public int expYears; 35 | public String subject; 36 | void getDetails() { 37 | System.out.println("Enter name: "); 38 | name = sc.nextLine(); 39 | System.out.println("Enter id: "); 40 | id = sc.nextInt(); 41 | System.out.println("Enter years of experience: "); 42 | expYears = sc.nextInt(); 43 | System.out.println("Enter subject: "); 44 | subject = sc.next(); 45 | } 46 | void display() { 47 | System.out.println("Displaying teacher details: "); 48 | System.out.println("Name: " + name); 49 | System.out.println("ID: " + id); 50 | System.out.println("Years of experience: " + expYears); 51 | System.out.println("Subject taught: " + subject); 52 | } 53 | } 54 | 55 | public class EduInstitute { 56 | public static void main(String[] args) { 57 | // TODO Auto-generated method stub 58 | Student s1 = new Student(); 59 | s1.getDetails(); 60 | s1.display(); 61 | System.out.println(); 62 | Teacher t1 = new Teacher(); 63 | t1.getDetails(); 64 | t1.display(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Programs/excHandling.java: -------------------------------------------------------------------------------- 1 | package excHandling; 2 | import java.util.*; 3 | import java.io.*; 4 | 5 | public class ArrayListProg { 6 | public static void main(String[] args) throws IOException { 7 | System.out.println("Program for implementing ArrayList: "); 8 | ArrayList obj = new ArrayList(); 9 | 10 | Scanner sc = new Scanner(System.in); 11 | char ans; 12 | do { 13 | System.out.println("Main Menu"); 14 | System.out.println("1. Create \n2. Display \n3. Insert \n4. Delete \n5. Modify"); 15 | System.out.println("Enter your choice: "); 16 | int choice = sc.nextInt(); 17 | switch (choice) { 18 | case 1: 19 | System.out.println("Inserting some elements in the array..."); 20 | System.out.println("How many characters do you want to add to the list? "); 21 | int n = sc.nextInt(); 22 | for (int i = 0; i < n; i++) { 23 | System.out.println("Enter character: "); 24 | char ch = sc.next().charAt(0); 25 | if (Character.isDigit(ch)) 26 | throw new IOException("Invalid data type!"); 27 | else 28 | obj.add(ch); 29 | } 30 | break; 31 | case 2: 32 | System.out.println("The size of the array is: " + obj.size()); 33 | System.out.println("The array elements are: " + obj); 34 | break; 35 | case 3: 36 | System.out.println("Inserting some elements in the array in between: "); 37 | System.out.println("Enter the index at which you want to insert new character: "); 38 | int i = sc.nextInt(); 39 | System.out.println("Enter character: "); 40 | char ch = sc.next().charAt(0); 41 | if (Character.isDigit(ch)) 42 | throw new IOException("Invalid data type!"); 43 | else 44 | obj.add(i, ch); 45 | break; 46 | case 4: 47 | System.out.println("Enter the index of the number that you want to delete: "); 48 | int index = sc.nextInt(); 49 | System.out.println("Removing " + index + "th element from the array!"); 50 | obj.remove(index); 51 | break; 52 | case 5: 53 | System.out.println("Updating the elements from the array: "); 54 | System.out.println("Enter the index at which you want to modify the character: "); 55 | i = sc.nextInt(); 56 | System.out.println("Enter character: "); 57 | ch = sc.next().charAt(0); 58 | if (Character.isDigit(ch)) 59 | throw new IOException("Invalid data type!"); 60 | else 61 | obj.set(i, ch); 62 | break; 63 | } 64 | System.out.println("Do you want to go back to main menu?(y/n)"); 65 | ans = sc.next().charAt(0); 66 | } while (ans == 'y' || ans == 'Y'); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Programs/excThrow.java: -------------------------------------------------------------------------------- 1 | package exceptThr; 2 | 3 | class t { 4 | public t() { 5 | try { 6 | throw new NullPointerException("Null pointer exception"); 7 | } 8 | catch(NullPointerException e) { 9 | System.out.println("Caught!"); 10 | throw e; // Rethrow an exception 11 | } 12 | } 13 | } 14 | 15 | public class ExceptThrow { 16 | public static void main(String[] args) { 17 | try { 18 | // throw new ArithmeticException("Hello"); // "Hello" is a parameter 19 | t obj = new t(); 20 | } 21 | // catch(ArithmeticException e) { 22 | // System.out.println(e.getMessage()); 23 | // } 24 | catch(NullPointerException e) { 25 | System.out.println(e.getMessage()); 26 | // e.getLocalizedMessage() and e.getMessage() prints out the same output currently 27 | System.out.println("Recaught!"); 28 | } 29 | finally { 30 | System.out.println("Finally block will always be executed!"); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Programs/factoflargenum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Factorial of Large numbers in Java using BigInteger. 3 | * Input - Enter Test cases,Enter Number. 4 | */ 5 | 6 | import java.util.*; 7 | import java.lang.*; 8 | import java.io.*; 9 | import java.math.BigInteger; 10 | 11 | class factoflargenum { 12 | public static void main (String[] args) { 13 | Scanner sc = new Scanner(System.in); 14 | int t = sc.nextInt(); 15 | while(t-->0) 16 | { 17 | int n = sc.nextInt(); 18 | BigInteger bg = BigInteger.ONE; 19 | for(int i=n;i>0;i--) 20 | bg = bg.multiply(BigInteger.valueOf(i)); 21 | System.out.println(bg); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Programs/fibo.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class fibo{ 4 | 5 | public static void main(String[] args) { 6 | // write your code here 7 | 8 | int a = 0; 9 | int b=1; 10 | 11 | Scanner sc = new Scanner(System.in); 12 | 13 | int n= sc.nextInt(); 14 | sc.close(); 15 | 16 | for(int i=0; i { 3 | private T item; 4 | public void setItem(T item) { 5 | this.item = item; 6 | } 7 | 8 | public T getItem() { 9 | return this.item; 10 | } 11 | 12 | public static void main(String[] args) { 13 | // TODO Auto-generated method stub 14 | genProg gc1 = new genProg<>(); 15 | gc1.setItem("Hello"); 16 | String item1 = gc1.getItem(); 17 | System.out.println(item1); 18 | 19 | genProg gc2 = new genProg<>(); 20 | gc2.setItem(new Integer(1)); 21 | Integer item2 = gc2.getItem(); 22 | System.out.println(item2); 23 | 24 | genProg gc3 = new genProg<>(); 25 | gc3.setItem(new Double(3.33)); 26 | Double item3 = gc3.getItem(); 27 | System.out.println(item3); 28 | 29 | genProg gc4 = new genProg<>(); 30 | gc4.setItem(new Boolean(false)); 31 | Boolean item4 = gc4.getItem(); 32 | System.out.println(item4); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Programs/helloWorld.java: -------------------------------------------------------------------------------- 1 | public class helloWorld { 2 | public static void main(String args[]) { 3 | System.out.println("Hello World!!"); 4 | } 5 | } -------------------------------------------------------------------------------- /Programs/input.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; // import required files for input 2 | 3 | public class MyInput { 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | Scanner sc = new Scanner(System.in); // create new object of the scanner class 7 | int x; 8 | System.out.println("Enter a number: "); // displaying a message (prompt) for the user input 9 | x = sc.nextInt(); // save the user input as variable x 10 | System.out.println("Number is: " + x); 11 | } 12 | } -------------------------------------------------------------------------------- /Programs/integers.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | public static void main(String[] args) { 3 | int one = 1; 4 | int two = 2; 5 | if (one == two) { 6 | System.out.println("they are equal!"); 7 | } else { 8 | if (one > two) { 9 | System.out.println("one is greater than two"); 10 | } else { 11 | System.out.println("two is greater than one"); 12 | } 13 | } 14 | int int1 = 3*3+1; 15 | int int2 = 4*2; 16 | if (int1 == int2) { 17 | System.out.println("These integers are the same"); 18 | } 19 | else { 20 | System.out.println("These integers aren't the same"); 21 | } 22 | while (int2 < int1) { 23 | System.out.println("Int2 is still less than int1"); 24 | int2++; //Adds one to int2 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Programs/isValidPerfectSquare.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ValidPerfectSquare { 4 | public boolean isPerfectSquare(int num) { 5 | long high = (long) num+1; 6 | long low = -1; 7 | while(low!=high-1){ 8 | long mid = (low+high)/2; 9 | if(mid*mid==num) return true; 10 | else if(mid*mid>num) high = mid; 11 | else low = mid; 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Programs/kadane.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class Kadane 6 | { 7 | public static void main (String[] args) 8 | { 9 | int [] a = {10,13,11,22,34,50,20,80}; 10 | System.out.println("Sub array with maximum sum is " +maxSubArray(a)); 11 | 12 | } 13 | 14 | static int maxSubArray(int a[]) 15 | { 16 | int l = a.length; 17 | int max = Integer.MIN_VALUE, max_ending = 0; 18 | for (int i = 0; i < l; i++) 19 | { 20 | max_ending = max_ending + a[i]; 21 | if (max < max_ending) 22 | max = max_ending; 23 | if (max_ending < 0) 24 | max_ending = 0; 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /Programs/largestNum.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of if-else if-else statements - 2 | package largestNum; 3 | import java.util.Scanner; 4 | public class LargestNum { 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | double x; 8 | double y; 9 | Scanner sc = new Scanner(System.in); 10 | System.out.println("Enter first number: "); 11 | x = sc.nextDouble(); 12 | System.out.println("Enter second number: "); 13 | y = sc.nextDouble(); 14 | if (x > y) { 15 | System.out.println("X is greater than Y."); 16 | } 17 | else if (y > x) { 18 | System.out.println("Y is greater than X"); 19 | } 20 | else { 21 | System.out.println("X and Y are equal."); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Programs/list_1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | // HW - 7 | // WAP a Java program which will create a list of int, string and decimal numbers using arraylist and linkedlists 8 | 9 | public class list_1 { 10 | 11 | public static void main(String[] args) { 12 | // TODO Auto-generated method stub 13 | // Array list for strings - 14 | List listStrings = new ArrayList(); 15 | listStrings.add("One"); 16 | listStrings.add("Two"); 17 | listStrings.add("Three"); 18 | listStrings.add("Four"); 19 | System.out.println(listStrings); 20 | System.out.println(listStrings.get(1)); 21 | listStrings.set(3, "Using set method!"); 22 | System.out.println(listStrings); 23 | 24 | // Array list for integers - 25 | List listIntegers = new ArrayList(); 26 | listIntegers.add(1); 27 | listIntegers.add(2); 28 | listIntegers.add(3); 29 | listIntegers.add(4); 30 | System.out.println(listIntegers); 31 | // Iterating over a list - 32 | Iterator iter = listIntegers.iterator(); 33 | while (iter.hasNext()) { 34 | System.out.println(iter.next()); 35 | } 36 | 37 | // Linked List for numbers - 38 | LinkedList numbers = new LinkedList(); 39 | numbers.add(10); 40 | numbers.add(10.32); 41 | numbers.add(45.3333333); 42 | System.out.println(numbers); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Programs/matrix/Matrix_Multiply.java: -------------------------------------------------------------------------------- 1 | // Program to multply two matrices in Java 2 | package matrix; 3 | import java.util.Scanner; 4 | public class Matrix_Multiply { 5 | public static void main(String[] args) { 6 | try (Scanner sc = new Scanner(System.in)) { 7 | System.out.println("Enter the row and column number for 1st matrix"); 8 | int n=sc.nextInt(); 9 | int m=sc.nextInt(); 10 | // Input for the row and column number 11 | int a1[][] = new int[n][m]; 12 | // New 2D array for first matrix 13 | System.out.println("Enter "+(n*m)+ " numbers"); 14 | // Taking input of the first matrix 15 | for (int i = 0; i < n; i++) { 16 | for (int j = 0; j < m; j++) { 17 | a1[i][j] = sc.nextInt(); 18 | } 19 | } 20 | int n1=sc.nextInt(); 21 | int m1=sc.nextInt(); 22 | // Input for the row and column number 23 | int a2[][] = new int[n1][m1]; 24 | // New 2D array for second matrix 25 | System.out.println("Enter "+(n1*m1)+ " numbers"); 26 | // Taking input of the second matrix 27 | for (int i = 0; i < n1; i++) { 28 | for (int j = 0; j < m1; j++) { 29 | a2[i][j] = sc.nextInt(); 30 | } 31 | } 32 | if(m!=n1) 33 | { 34 | System.out.println("Invalid coordinates of the matrix"); 35 | return; 36 | } 37 | int multiply[][] = new int[n][m1]; 38 | // New 2D array for multiplication of the two matrices - 39 | System.out.println("The multiplication of two matrices are - "); 40 | // Performing multiplication of two matrices - 41 | for(int i=0;i n ? 2 * n - row: row; 17 | for (int col = 0; col < totalColsInRow; col++) { 18 | System.out.print("* "); 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern6.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern6 { 4 | public static void main(String[] args) { 5 | pattern6(4); 6 | } 7 | // * 8 | // * * 9 | // * * * 10 | // * * * * 11 | // * * * 12 | // * * 13 | // * 14 | private static void pattern6(int n) { 15 | for (int row = 0; row < 2 * n; row++) { 16 | int totalColsInRow = row > n ? 2 * n - row: row; 17 | 18 | int noOfSpaces = n - totalColsInRow; 19 | for (int s = 0; s < noOfSpaces; s++) { 20 | System.out.print(" "); 21 | } 22 | 23 | for (int col = 0; col < totalColsInRow; col++) { 24 | System.out.print("* "); 25 | } 26 | System.out.println(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern7.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern7 { 4 | public static void main(String[] args) { 5 | pattern7(4); 6 | } 7 | // 1 8 | // 2 1 2 9 | // 3 2 1 2 3 10 | //4 3 2 1 2 3 4 11 | // 3 2 1 2 3 12 | // 2 1 2 13 | // 1 14 | static void pattern7(int n) { 15 | for (int row = 1; row <= 2 * n; row++) { 16 | 17 | int c = row > n ? 2 * n - row: row; 18 | 19 | for (int space = 0; space < n-c; space++) { 20 | System.out.print(" "); 21 | } 22 | 23 | for (int col = c; col >= 1; col--) { 24 | System.out.print(col + " "); 25 | } 26 | for (int col = 2; col <= c; col++) { 27 | System.out.print(col + " "); 28 | } 29 | 30 | System.out.println(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern8.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern8 { 4 | public static void main(String[] args) { 5 | pattern8(4); 6 | } 7 | 8 | // 1 9 | // 2 1 2 10 | // 3 2 1 2 3 11 | //4 3 2 1 2 3 4 12 | static void pattern8(int n) { 13 | for (int row = 1; row <= n; row++) { 14 | 15 | for (int space = 0; space < n-row; space++) { 16 | System.out.print(" "); 17 | } 18 | 19 | for (int col = row; col >= 1; col--) { 20 | System.out.print(col + " "); 21 | } 22 | for (int col = 2; col <= row; col++) { 23 | System.out.print(col + " "); 24 | } 25 | 26 | System.out.println(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern9.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern9 { 4 | public static void main(String[] args) { 5 | pattern9(4); 6 | } 7 | // 4 4 4 4 4 4 4 4 4 8 | // 4 3 3 3 3 3 3 3 4 9 | // 4 3 2 2 2 2 2 3 4 10 | // 4 3 2 1 1 1 2 3 4 11 | // 4 3 2 1 0 1 2 3 4 12 | // 4 3 2 1 1 1 2 3 4 13 | // 4 3 2 2 2 2 2 3 4 14 | // 4 3 3 3 3 3 3 3 4 15 | // 4 4 4 4 4 4 4 4 4 16 | static void pattern9(int n) { 17 | int originalN = n; 18 | n = 2 * n; 19 | for (int row = 0; row <= n; row++) { 20 | for (int col = 0; col <= n; col++) { 21 | int atEveryIndex = originalN - Math.min(Math.min(row, col), Math.min(n - row, n - col)); 22 | System.out.print(atEveryIndex + " "); 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Programs/patterns/README.md: -------------------------------------------------------------------------------- 1 | ### Steps? 2 | 3 | - Number of lines = number of rows = number of times outer loop will run 4 | - Identify for every row number: 5 | - how many columns are there 6 | - or Types of elements in columns 7 | - What do you need to print? -------------------------------------------------------------------------------- /Programs/primeNumbers.java: -------------------------------------------------------------------------------- 1 | // Program to find out the prime numbers in a given range in Java - 2 | package primeNo; 3 | import java.util.Scanner; // To take input from user 4 | public class PrimeNo { 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | int a, b; 9 | System.out.println("Enter first value: "); 10 | a = sc.nextInt(); 11 | System.out.println("Enter last value: "); 12 | b = sc.nextInt(); 13 | int i, j, num = 0, c = 0; 14 | System.out.println("List of prime numbers from " + a + " to " + b + ": "); 15 | for (i = a; i <= b; i++) { 16 | num = i; 17 | c = 0; 18 | j = 2; // Start checking from 2 19 | while (j < num) { 20 | if ((num % j) == 0) { 21 | c = 1; 22 | break; 23 | } 24 | j++; 25 | } 26 | if (c == 0) { 27 | System.out.println(num); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Programs/seive.java: -------------------------------------------------------------------------------- 1 | 2 | class SieveOfEratosthenes 3 | { 4 | void sieveOfEratosthenes(int n) 5 | { 6 | boolean prime[] = new boolean[n+1]; 7 | for(int i=0;i<=n;i++) 8 | prime[i] = true; 9 | 10 | for(int p = 2; p*p <=n; p++) 11 | { 12 | 13 | if(prime[p] == true) 14 | { 15 | 16 | for(int i = p*p; i <= n; i += p) 17 | prime[i] = false; 18 | } 19 | } 20 | 21 | 22 | for(int i = 2; i <= n; i++) 23 | { 24 | if(prime[i] == true) 25 | System.out.print(i + " "); 26 | } 27 | } 28 | 29 | public static void main(String args[]) 30 | { 31 | int n = 30; 32 | System.out.print("Following are the prime numbers "); 33 | System.out.println("smaller than or equal to " + n); 34 | SieveOfEratosthenes g = new SieveOfEratosthenes(); 35 | g.sieveOfEratosthenes(n); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /mersenneprime.java: -------------------------------------------------------------------------------- 1 | //To find mersenne's prime upto 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | 6 | public class mersenneprime { 7 | 8 | public static boolean isPrime(long n){ 9 | boolean isPrime =true; 10 | 11 | for(int j=2;jtwoindexlist=new ArrayList(); 27 | long two=2; 28 | 29 | for(int k=1;k<100;k++){ 30 | two*=2; 31 | twoindexlist.add(two); 32 | if(two>=p){ 33 | break; 34 | } 35 | } 36 | for (Long long1 : twoindexlist) { 37 | System.out.println(long1); 38 | } 39 | /* 40 | for(long i=0; i