├── Programs ├── Games │ ├── peg-solitaire │ │ ├── 1.png │ │ ├── 2.png │ │ ├── 3.png │ │ ├── 4.png │ │ ├── 5.png │ │ ├── 6.png │ │ ├── Main.java │ │ └── PegSolitaireGame.java │ ├── Snake Game with Different Playing Features and GUI │ │ ├── SnakeGamer.java │ │ ├── README.md │ │ └── GameFrame.java │ ├── MaximumSubArraySum.java │ └── GuessTheNumber.java ├── helloWorld.java ├── Factory Method │ ├── CarFactory.java │ ├── Car.java │ ├── SedanCarFactory.java │ ├── SUVCarFactory.java │ ├── HatchbackCarFactory.java │ ├── HatchbackCar.java │ ├── SUVCar.java │ ├── SedanCar.java │ └── TestFactoryPattern.java ├── patterns │ ├── README.md │ ├── Pattern1.java │ ├── Pattern2.java │ ├── Pattern5.java │ ├── Pattern3.java │ ├── Pattern4.java │ ├── Pattern8.java │ ├── Pattern6.java │ ├── Pattern9.java │ └── Pattern7.java ├── ForLoop.java ├── Circular Integer LinkedList │ ├── Node.java │ ├── Main.java │ └── circularLinkedList.java ├── ReverseString.java ├── SquareEveryDigit.java ├── arrayOutOfBounds.java ├── FactorialDemo.java ├── isValidPerfectSquare.java ├── Overriding.java ├── input.java ├── ThisPointerExplicit.java ├── Check_If_Sorted.java ├── PrintPattern.java ├── StaticMemberFunctions.java ├── ThisPointerImplicit.java ├── arithExceptions.java ├── GenClassMethod.java ├── factoflargenum.java ├── SumOfArrayNos.java ├── largestNum.java ├── LinearSearch.java ├── HttpsRequest.java ├── areaRect.java ├── ExponentialSearch.java ├── kadane.java ├── integers.java ├── JavaClasses.java ├── FindIndexValue.java ├── nestedTry.java ├── seive.java ├── StudentInterface.java ├── derivedConstructor.java ├── BubbleSort.java ├── overloading.java ├── primeNumbers.java ├── SwitchCase.java ├── excThrow.java ├── Palindrome.java ├── SwitchingLetters.java ├── genProg.java ├── InsertionSort.java ├── TwoDArrays.java ├── fibo.java ├── SelectionSort.java ├── IncomeTaxCalculator.java ├── constructors.java ├── CountingSort.java ├── Decimal_to_Binary.java ├── ShellSort.java ├── CeilingFloor.java ├── FunctionalInterfaces.java ├── RockPaperScissor.java ├── LuckyNumber.java ├── DepthFirstSearch.java ├── arrayLists.java ├── WashingMachine │ ├── LavadoraImplementada.java │ └── Lavadora.java ├── Xorpalindrome.java ├── abstractClass.java ├── QuickSort.java ├── RabinKarp.java ├── BucketSort.java ├── CombinationCoinChange.java ├── LongestCommonSubsequence.java ├── BreathFirstSearch.java ├── TwoElementsOccurOnceWhileOthersOccurTwice.java ├── list_1.java ├── BinarySearch.java ├── InterpolationSearch.java ├── Fibonacci.java ├── KMP.java ├── MatrixAdd.java ├── Floyd_Warshall_Algorithm.java ├── BFS.java ├── Stack.java ├── DFS.java ├── Two_Sum.java ├── Anagram.java ├── StaticCount.java ├── Sieve_Of_Eratosthenes.java ├── Calculator.java ├── MultipleInheritance.java ├── KnapSack.java ├── JavaStreams.java ├── eduInstitute.java ├── HuffmanCoding.java ├── WiggleSorting.java ├── matrix │ └── Matrix_Multiply.java ├── Circular_Queue.java ├── NoDupArray.java ├── NumberToRoman.java ├── FordFulkerson.java ├── StrassensMultiplication.java ├── HeapSort.java ├── MergeSort.java ├── excHandling.java ├── ToDoList.java ├── ReverseList.java ├── Soundex.java ├── Dijkstra.java ├── ADTFractionApp.java ├── BellmanFord.java ├── Mcolor.java ├── PrimsAlgorithm.java ├── Kruskal.java ├── SortNonBoundary.java ├── ComplexNosOps.java ├── MergeKsortedLists.java ├── Swing_Simple_Registration_Form.java ├── BinaryTreeInorder.java ├── Trie_Implementation.java ├── Gssarray.java ├── bookShop.java ├── RotateLinkedList.java ├── CeaserCipher.java └── eduEmpDb.java ├── palindrome.java ├── NumberOfDigit.java └── mersenneprime.java /Programs/Games/peg-solitaire/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/1.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/2.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/3.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/4.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/5.png -------------------------------------------------------------------------------- /Programs/Games/peg-solitaire/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Java/HEAD/Programs/Games/peg-solitaire/6.png -------------------------------------------------------------------------------- /Programs/helloWorld.java: -------------------------------------------------------------------------------- 1 | public class helloWorld { 2 | public static void main(String args[]) { 3 | System.out.println("Hello World!!"); 4 | } 5 | } -------------------------------------------------------------------------------- /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/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/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/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/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/ForLoop.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of for loop - 2 | package ForLoop; 3 | public class ForLoop { 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | int i; 7 | for (i = 0; i <= 5; i++) { 8 | System.out.println(i); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /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/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/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/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/ReverseString.java: -------------------------------------------------------------------------------- 1 | public class ReverseString { 2 | public static void main(String[] args) { 3 | String word = "Hello Jorge"; 4 | String reverseWord = ""; 5 | 6 | for (int i = word.length(); i != 0; i--) { 7 | reverseWord += word.substring(i-1,i); 8 | } 9 | 10 | System.out.println(reverseWord); 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Programs/SquareEveryDigit.java: -------------------------------------------------------------------------------- 1 | public class SquareDigit { 2 | 3 | public int squareDigits(int n) { 4 | 5 | String strDigits = String.valueOf(n); 6 | String result = ""; 7 | 8 | for (char c : strDigits.toCharArray()) { 9 | int digit = Character.digit(c, 10); 10 | result += digit * digit; 11 | } 12 | 13 | return Integer.parseInt(result); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /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/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/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/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/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/ThisPointerExplicit.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate 'this' pointer (explicit method) - 2 | package thisPointerExplicit; 3 | class Box { 4 | int len = 50; 5 | void display() { 6 | int len = 100; 7 | System.out.println("Local value = " + len); 8 | System.out.println("Instance value = " + this.len); 9 | } 10 | } 11 | public class ThisPointerExplicit { 12 | public static void main(String[] args) { 13 | // TODO Auto-generated method stub 14 | Box b = new Box(); 15 | b.display(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /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/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/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/patterns/Pattern1.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern1 { 4 | public static void main(String[] args) { 5 | pattern1(4); 6 | } 7 | // * 8 | // * * 9 | // * * * 10 | // * * * * 11 | private static void pattern1(int n) { 12 | // for every row, run the col 13 | for (int row = 0; row <= n; row++) { 14 | for (int col = 0; col < row; col++) { 15 | System.out.print("* "); 16 | } 17 | System.out.println(); 18 | } 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /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/StaticMemberFunctions.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of static member functions - 2 | package staticMemberFunctions; 3 | class staticFunc { 4 | static int a = 5, b; 5 | static void method(int x) { 6 | System.out.println("x = " + x); 7 | System.out.println("a = " + a); 8 | System.out.println("b = " + b); 9 | } 10 | static { 11 | System.out.println("Static block"); 12 | b = a * 10; 13 | } 14 | } 15 | public class StaticMemberFunctions { 16 | 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | staticFunc.method(10); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern2.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern2 { 4 | public static void main(String[] args) { 5 | patter2(4); 6 | } 7 | // * * * * 8 | // * * * * 9 | // * * * * 10 | // * * * * 11 | // * * * * 12 | private static void patter2(int n) { 13 | // for every row, run the col 14 | for (int row = 0; row <= n; row++) { 15 | for (int col = 0; col < n; col++) { 16 | System.out.print("* "); 17 | } 18 | System.out.println(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /palindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class palindrome 3 | { 4 | public static void main() 5 | { 6 | Scanner sc= new Scanner(System.in); 7 | System.out.println("enter a number"); 8 | int num= sc.nextInt(); 9 | int d,num1,rev;rev=0; 10 | num1=num; 11 | while(num!=0) 12 | { 13 | d=num%10; 14 | rev=rev*10+d; 15 | num=num/10; 16 | } 17 | if(num1==rev) 18 | System.out.println("the number is palindromic"); 19 | else 20 | System.out.println("the number is not palindromic"); 21 | } 22 | } 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Programs/ThisPointerImplicit.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate the use of 'this' pointer - 2 | package thisPointerImplicit; 3 | class Box { 4 | int l, h, b; 5 | Box(int l, int b, int h) { 6 | this.l = l; 7 | this.b = b; 8 | this.h = h; 9 | } 10 | int vol() { 11 | return l * b * h; 12 | } 13 | } 14 | public class ThisPointerImplicit { 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | Box b1 = new Box(2, 4, 6); 18 | Box b2 = new Box(5, 5, 5); 19 | System.out.println("Volume = " + b1.vol()); 20 | System.out.println("Volume = " + b2.vol()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern5.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern5 { 4 | public static void main(String[] args) { 5 | pattern5(4); 6 | } 7 | // * 8 | // * * 9 | // * * * 10 | // * * * * 11 | // * * * 12 | // * * 13 | // * 14 | static void pattern5(int n) { 15 | for (int row = 0; row < 2 * n; row++) { 16 | int totalColsInRow = row > 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/Pattern3.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern3 { 4 | public static void main(String[] args) { 5 | pattern3(4); 6 | } 7 | // * * * * 8 | // * * * 9 | // * * 10 | // * 11 | 12 | static void pattern3(int n) { 13 | for (int row = 1; row <= n; row++) { 14 | // for every row, run the col 15 | for (int col = 1; col <= n-row+1; col++) { 16 | System.out.print("* "); 17 | } 18 | // when one row is printed, we need to add a newline 19 | System.out.println(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Programs/arithExceptions.java: -------------------------------------------------------------------------------- 1 | // Program to show ArithmeticException Error handling - 2 | public class arithExceptions { 3 | public static void main(String[] args) { 4 | // try block - 5 | try { 6 | int a = 20, b; 7 | b = a/0; 8 | System.out.println("Value of b = " + b); 9 | } 10 | // catch block - 11 | catch(ArithmeticException e) { 12 | System.out.println("Exception occured!"); 13 | } 14 | // finally block - 15 | finally { 16 | System.out.println("Quit"); 17 | System.out.println("This block will always execute!"); 18 | } 19 | // finally block can be used to catch any exception 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Programs/patterns/Pattern4.java: -------------------------------------------------------------------------------- 1 | package Programs.patterns; 2 | 3 | public class Pattern4 { 4 | public static void main(String[] args) { 5 | pattern4(4); 6 | } 7 | // 1 8 | // 1 2 9 | // 1 2 3 10 | // 1 2 3 4 11 | static void pattern4(int n) { 12 | for (int row = 1; row <= n; row++) { 13 | // for every row, run the col 14 | for (int col = 1; col <= row; col++) { 15 | System.out.print(col + " "); 16 | } 17 | // when one row is printed, we need to add a newline 18 | System.out.println(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /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/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/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/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/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/SumOfArrayNos.java: -------------------------------------------------------------------------------- 1 | // Program to add all the numbers in an array - 2 | package sumOfNos; 3 | import java.util.Scanner; 4 | public class SumOfNos { 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | int sum = 0; // Initializing a variable for the sum of the numbers 8 | int numbers[] = new int[25]; // Initializing an array for integers 9 | Scanner sc = new Scanner(System.in); 10 | // For loop to take user input for the array and adding the numbers to the sum variable 11 | for (int i = 0; i < 20; i++) { 12 | System.out.println("Enter number: "); 13 | numbers[i] = sc.nextInt(); 14 | sum = sum + numbers[i]; 15 | } 16 | System.out.println("Sum = " + sum); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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/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/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/areaRect.java: -------------------------------------------------------------------------------- 1 | // Program to calculate the area of rectangle using return values - 2 | package area; 3 | class Rectangle { 4 | public int l, b; 5 | public void getData(int m, int n) { 6 | l = m; 7 | b = n; 8 | } 9 | public int calcArea() { 10 | int area = l * b; 11 | return area; 12 | } 13 | } 14 | public class AreaRect { 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | int a1, a2; 18 | Rectangle r1 = new Rectangle(); 19 | Rectangle r2 = new Rectangle(); 20 | r1.l = 10; 21 | r1.b = 15; 22 | a1 = r1.l * r1.b; 23 | r2.getData(20, 30); 24 | a2 = r2.calcArea(); 25 | System.out.println("The area of first rectangle = " + a1); 26 | System.out.println("The area of second rectangle = " + a2); 27 | } 28 | } -------------------------------------------------------------------------------- /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/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/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/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/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/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/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/nestedTry.java: -------------------------------------------------------------------------------- 1 | package nestedBlocks; 2 | 3 | public class NestedTry { 4 | 5 | public static void main(String[] args) { 6 | int a = 20, b; 7 | int ch[] = new int[20]; 8 | try { 9 | b = a/0; 10 | try { 11 | System.out.println("Value of b = " + b); 12 | } 13 | catch(Exception e) { 14 | System.out.println("Inner block Exception occured!"); 15 | } 16 | } 17 | catch(Exception e) { 18 | System.out.println("Outer block exception occured!"); 19 | } 20 | finally { 21 | System.out.println("Quit"); 22 | System.out.println("This block will always execute!"); 23 | } 24 | // finally block can be used to catch any exception 25 | } 26 | } 27 | 28 | /* Note: Inner catch will use the outer catch block but outer catch will not use inner catch block exception 29 | * */ 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Programs/StudentInterface.java: -------------------------------------------------------------------------------- 1 | package inheritInterface; 2 | interface it1 { 3 | int x = 10, y = 20; 4 | public void add(int a, int b); 5 | public void sub(int a, int b); 6 | } 7 | class arithmOp implements it1 { 8 | public void add(int p, int q) { 9 | System.out.println("Addition of two numbers: " + (p + q)); 10 | } 11 | public void sub(int p, int q) { 12 | System.out.println("Addition of two numbers: " + (p - q)); 13 | } 14 | } 15 | 16 | public class StudentInterface { 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | arithmOp obj = new arithmOp(); 20 | obj.add(10, 15); 21 | obj.sub(15, 10); 22 | System.out.println(it1.x + it1.y); // This works without errors (actually a wrong method - don't use) 23 | System.out.println(obj.x + obj.y); // This works but gives errors. 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /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/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/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/overloading.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate overloading in Java - 2 | package overloading; 3 | class SqRectArea { 4 | public void Area(int a) { 5 | System.out.println("The side of square = " + a); 6 | System.out.println("The area of square = " + (a * a)); 7 | } 8 | public void Area(int l, int b) { 9 | System.out.println("Length = " + l); 10 | System.out.println("Breadth = " + b); 11 | System.out.println("The area of rectangle = " + (l * b)); 12 | } 13 | } 14 | public class Overloading { 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | SqRectArea sq = new SqRectArea(); // New object instantiation for square 18 | sq.Area(5); // Calling function with 1 parameter 19 | SqRectArea rect = new SqRectArea(); // New object instantiation for rectangle 20 | rect.Area(10, 5); // Calling function with 2 parameters 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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/SwitchCase.java: -------------------------------------------------------------------------------- 1 | // Program to demonstrate switch case statements in Java 2 | package switchCase; 3 | import java.util.Scanner; 4 | public class SwitchCase { 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Enter a number from 1 to 5: "); 9 | int num = sc.nextInt(); 10 | switch (num) { 11 | case 1: 12 | System.out.println("You have entered 1."); 13 | break; 14 | case 2: 15 | System.out.println("You have entered 2."); 16 | break; 17 | case 3: 18 | System.out.println("You have entered 3."); 19 | break; 20 | case 4: 21 | System.out.println("You have entered 4."); 22 | break; 23 | case 5: 24 | System.out.println("You have entered 5."); 25 | break; 26 | default: 27 | System.out.println("You have entered a number less than 1 or greater than 5."); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /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/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/SwitchingLetters.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SwitchingLetters { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner keyboard = new Scanner(System.in); 8 | 9 | System.out.println("Please enter two numbers:"); 10 | int index1 = keyboard.nextInt() - 1; 11 | int index2 = keyboard.nextInt() - 1; 12 | 13 | keyboard.nextLine(); 14 | System.out.println("Please enter a sentence:"); 15 | String sentence = keyboard.nextLine(); 16 | 17 | System.out.println("The new sentence:\n" + switchLetters(index1, index2, sentence)); 18 | } 19 | 20 | /* Switches letters according to given indexes. */ 21 | 22 | public static String switchLetters(int index1, int index2, String sentence) { 23 | return sentence.substring(0,index1) + sentence.charAt(index2) + sentence.substring(index1 + 1, index2) + sentence.charAt(index1) + sentence.substring(index2 + 1, sentence.length()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Programs/genProg.java: -------------------------------------------------------------------------------- 1 | package genericProgramming; 2 | public class genProg { 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/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/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/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; i5f && 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/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/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; i0){ 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/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/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/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/RockPaperScissor.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | import java.util.Scanner; 3 | 4 | public class Rockpaperscissor { 5 | 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Choose Any One:\n1. Rock \n2. Paper \n3. Scissor"); 9 | int user = sc.nextInt(); 10 | if (user > 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/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/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/arrayLists.java: -------------------------------------------------------------------------------- 1 | package ArrayLists; 2 | import java.util.*; 3 | 4 | public class ArrayLists { 5 | public static void main(String[] args) { 6 | ArrayList 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/WashingMachine/LavadoraImplementada.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | *Clase creada para pedir datos a los usuarios de la lavadora 1 5 | *Se hace uso de la clase LavadoraSamsung creada por el desarrollador externo 6 | *Se crea un package llamado libreria, se copia la clase que fue enviada por el desarrollador externo 7 | y se importa en esta clase main. 8 | *Se piden datos por teclado y se realiza la implementacion del metodo visible cicloFinalizado(). 9 | */ 10 | 11 | public class LavadoraImplementada { 12 | public static void main(String[] args) { 13 | Scanner sc = new Scanner(System.in); 14 | 15 | System.out.println("Seleccione el tipo de ropa: "); 16 | System.out.println("Seleccione 1 - ropa blanca / 2 - ropa color"); 17 | int tipoRopa = sc.nextInt(); 18 | 19 | System.out.println("Digite la cantidad de kilos de ropa: "); 20 | System.out.println("Maximo 12 kilos"); 21 | int kilos = sc.nextInt(); 22 | 23 | Lavadora ls = new Lavadora(kilos, tipoRopa); 24 | ls.setTipoRopa(2); 25 | System.out.println("tipor de ropa es: "+ls.getTipoRopa()); 26 | ls.cicloFinalizado(); 27 | } 28 | } -------------------------------------------------------------------------------- /Programs/Xorpalindrome.java: -------------------------------------------------------------------------------- 1 | //code for xorpalindrome in Java 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | 8 | class Xorpalindrome 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | // your code goes here 13 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 14 | BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); 15 | int t=Integer.parseInt(br.readLine()); 16 | StringBuffer sb=new StringBuffer(); 17 | while(t-->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;itwoindexlist=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[] 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/CombinationCoinChange.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | /*Print all the Combinations of Change for a given Amount*/ 5 | class CoinChangeCombination { 6 | 7 | private static List 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/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/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/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 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/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= 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/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/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 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/Stack.java: -------------------------------------------------------------------------------- 1 | //Demostrate the Implementation of Stack Using 2 | public class Node { 3 | 4 | private int data; 5 | private Node nextNode; 6 | 7 | public Node(int data){ 8 | this.data = data; 9 | } 10 | 11 | public int getData() { 12 | return data; 13 | } 14 | 15 | public void setData(int data) { 16 | this.data = data; 17 | } 18 | 19 | public Node getNextNode() { 20 | return nextNode; 21 | } 22 | public void setNextNode(Node nextNode) { 23 | this.nextNode = nextNode; 24 | } 25 | } 26 | 27 | 28 | // Different Stack operation 29 | public class CustomStack { 30 | 31 | int length = 0; 32 | Node top = null; 33 | 34 | public CustomStack(){ 35 | } 36 | 37 | public int size(){ 38 | return length; 39 | } 40 | 41 | public boolean isEmpty(){ 42 | return length == 0; 43 | } 44 | 45 | public void push(int data) { 46 | Node tempNode = new Node(data); 47 | tempNode.setNextNode(top); 48 | top = tempNode; 49 | length++; 50 | } 51 | 52 | public int pop() { 53 | if(isEmpty()){ 54 | throw new EmptyStackException(); 55 | } 56 | Node node = top; 57 | top = top.getNextNode(); 58 | length--; 59 | return node.getData(); 60 | } 61 | 62 | public int peek(){ 63 | if(isEmpty()){ 64 | throw new EmptyStackException(); 65 | } 66 | return top.getData(); 67 | } 68 | } -------------------------------------------------------------------------------- /Programs/DFS.java: -------------------------------------------------------------------------------- 1 | //Note - for disconnected graph use the approach for checking connected components. 2 | 3 | package project0; 4 | 5 | import java.util.Iterator; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | class Graph{ 10 | private int v ; //total number of vertices 11 | private LinkedList 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/Two_Sum.java: -------------------------------------------------------------------------------- 1 | //In this code a array is taken along with an target element. The sum of two elements matching with the target element is displayed 2 | 3 | 4 | import java.util.*; 5 | public class Two_Sum { 6 | public static void main(String args[]) 7 | { 8 | try (Scanner sc = new Scanner(System.in)) { 9 | int n = sc.nextInt(); 10 | // length of the array is taken 11 | int a[] = new int[n]; 12 | for(int i = 0; i < n; i++) 13 | { 14 | a[i] = sc.nextInt(); 15 | } 16 | int target=sc.nextInt(); 17 | // target value is initialzized 18 | int array[] = new int[2]; 19 | a=twoSum(array,target); 20 | // method is called 21 | for(int i=0;i<2;i++) 22 | { 23 | System.out.print(a[i]+" "); 24 | } 25 | System.out.println(); 26 | } 27 | } 28 | public static int[] twoSum(int[] n, int target) { 29 | Map 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 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 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/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/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/WiggleSorting.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | import java.util.*; 3 | 4 | class SortWave { 5 | 6 | // A utility method to swap two numbers. 7 | void swap(int[] arr, int a, int b) { 8 | int temp = arr[a]; 9 | arr[a] = arr[b]; 10 | arr[b] = temp; 11 | } 12 | 13 | // This function sorts arr[0..n-1] in wave form, i.e., 14 | // arr[0] >= 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] `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/FordFulkerson.java: -------------------------------------------------------------------------------- 1 | // Ford-Fulkerson algorith in Java 2 | 3 | import java.util.LinkedList; 4 | 5 | class FordFulkerson { 6 | static final int V = 6; 7 | 8 | // Using BFS as a searching algorithm 9 | boolean bfs(int Graph[][], int s, int t, int p[]) { 10 | boolean visited[] = new boolean[V]; 11 | for (int i = 0; i < V; ++i) 12 | visited[i] = false; 13 | 14 | LinkedList 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/StrassensMultiplication.java: -------------------------------------------------------------------------------- 1 | //Program to multiply two square matrices using Strassen's Multiplication 2 | import java.util.*; 3 | public class StrassensMultiplication 4 | { 5 | public static void main(String[] args) 6 | { 7 | int n,m; 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows and columns of the first matrix : "); 10 | n = sc.nextInt(); 11 | System.out.println("Enter the number of rows and columns of the second matrix : "); 12 | m = sc.nextInt(); 13 | int[][] a = new int[n][n]; 14 | int[][] b = new int[m][m]; 15 | int[][] c = new int[2][2]; 16 | int i, j, m1, m2, m3, m4, m5, m6, m7; 17 | 18 | //Taking input from the user 19 | System.out.println("Enter all the elemens of the first matrix : "); 20 | for(i=0; 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/MergeSort.java: -------------------------------------------------------------------------------- 1 | // Program that implements Merge sort 2 | // Best case: O(nlogn) 3 | // Average case: O(nlogn) 4 | // Worst case: O(nlogn) 5 | 6 | public class MergeSortMain { 7 | 8 | static int arr[]={100,20,15,30,5,75,40}; 9 | 10 | public static void main(String args[]) 11 | { 12 | System.out.println("Array before sorting:"); 13 | printArray(arr,0,arr.length-1); 14 | System.out.println("-----------------------------"); 15 | 16 | mergeSort(0,arr.length-1); 17 | 18 | System.out.println("-----------------------------"); 19 | 20 | System.out.println("Array After sorting:"); 21 | printArray(arr,0,arr.length-1); 22 | 23 | } 24 | 25 | public static void mergeSort(int start,int end) 26 | { 27 | int mid=(start+end)/2; 28 | if(start 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/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 tasks = new ArrayList<>(); 9 | list(tasks); 10 | } 11 | 12 | public static void list(ArrayList tasks) { 13 | Scanner sc = new Scanner(System.in); 14 | System.out.print("Function you want to apply(1-4):\n" 15 | + "1- View\n" 16 | + "2- Add\n" 17 | + "3- Delete All Tasks\n" 18 | + "> "); 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/ReverseList.java: -------------------------------------------------------------------------------- 1 | // In this code a linkedlist is taken as input and the reversed form is displayed 2 | import java.util.*; 3 | public class ReverseList { 4 | public static void main(String args[]) 5 | { 6 | try (Scanner sc = new Scanner(System.in)) { 7 | ListNode fresh,start=null,prev=null,ptr=null; 8 | int c; 9 | do 10 | { 11 | fresh=new ListNode(); 12 | System.out.println("Enter the data"); 13 | fresh.data=sc.nextInt(); 14 | if(start==null) 15 | { 16 | start=fresh; 17 | // stores the starting address 18 | } 19 | else 20 | { 21 | prev.next=fresh; 22 | } 23 | prev=fresh; 24 | System.out.println("Press 1 to for next node initialization else press any number other than 1 to exit"); 25 | c=sc.nextInt(); 26 | // for next node initialization option is asked from the user 27 | }while(c==1); 28 | Solution nm=new Solution(); 29 | System.out.println("The original LinkedList is "); 30 | for(ptr=start;ptr!=null;ptr=ptr.next) 31 | { 32 | System.out.print(ptr.data+" "); 33 | } 34 | System.out.println(); 35 | // displayes the original linkedlist 36 | System.out.println("The reversed LinkedList is "); 37 | nm.reverseList(start); 38 | for(ptr=start;ptr!=null;ptr=ptr.next) 39 | { 40 | System.out.print(ptr.data+" "); 41 | } 42 | System.out.println(); 43 | // displays the reserved linkedlist 44 | } 45 | } 46 | } 47 | class Solution 48 | { 49 | public ListNode reverseList(ListNode start) 50 | { 51 | if(start==null) 52 | return null; 53 | // if there is no elements in the linkedlist then it returns null 54 | else 55 | { 56 | ListNode ptr,ptr1,ptr2; 57 | for(ptr=null,ptr1=start,ptr2=start.next,ptr1.next=null;ptr2!=null;ptr2=ptr2.next,ptr1.next=ptr) 58 | { 59 | ptr=ptr1; 60 | ptr1=ptr2; 61 | } 62 | start=ptr1; 63 | return start; 64 | // returns the start position of the linkedlist after reversing the list 65 | } 66 | } 67 | } 68 | // Solution class contains reverseList method which takes the start address as input and reverses the whole linkedlist 69 | class ListNode 70 | { 71 | int data; 72 | ListNode next; 73 | } 74 | // ListNode class is created for linklist creation -------------------------------------------------------------------------------- /Programs/Soundex.java: -------------------------------------------------------------------------------- 1 | /* The main principle behind Soundex algorithm is that consonants are grouped depending on the ordinal numbers and 2 | finally encoded into a value against which others are matched. 3 | It aims to find a code for every word by above process which is called soundex code. 4 | */ 5 | 6 | 7 | 8 | public class Soundex { 9 | public static String getGode(String s) 10 | { 11 | char[] x = s.toUpperCase().toCharArray(); 12 | 13 | 14 | char firstLetter = x[0]; 15 | 16 | //RULE [ 2 ] 17 | //Convert letters to numeric code 18 | for (int i = 0; i < x.length; i++) { 19 | switch (x[i]) { 20 | case 'B': 21 | case 'F': 22 | case 'P': 23 | case 'V': { 24 | x[i] = '1'; 25 | break; 26 | } 27 | 28 | case 'C': 29 | case 'G': 30 | case 'J': 31 | case 'K': 32 | case 'Q': 33 | case 'S': 34 | case 'X': 35 | case 'Z': { 36 | x[i] = '2'; 37 | break; 38 | } 39 | 40 | case 'D': 41 | case 'T': { 42 | x[i] = '3'; 43 | break; 44 | } 45 | 46 | case 'L': { 47 | x[i] = '4'; 48 | break; 49 | } 50 | 51 | case 'M': 52 | case 'N': { 53 | x[i] = '5'; 54 | break; 55 | } 56 | 57 | case 'R': { 58 | x[i] = '6'; 59 | break; 60 | } 61 | 62 | default: { 63 | x[i] = '0'; 64 | break; 65 | } 66 | } 67 | } 68 | 69 | //Remove duplicates 70 | //RULE [ 1 ] 71 | String output = "" + firstLetter; 72 | 73 | //RULE [ 3 ] 74 | for (int i = 1; i < x.length; i++) 75 | if (x[i] != x[i - 1] && x[i] != '0') 76 | output += x[i]; 77 | 78 | //RULE [ 4 ] 79 | //Pad with 0's or truncate 80 | output = output + "0000"; 81 | return output.substring(0, 4); 82 | } 83 | 84 | public static void main(String[] args) 85 | { 86 | String name1 = "Tail"; 87 | String name2 = "Tale"; 88 | String name3 = "Tailor"; 89 | 90 | System.out.println(Soundex.getGode(name1)); 91 | System.out.println(Soundex.getGode(name2)); 92 | System.out.println(Soundex.getGode(name3)); 93 | } 94 | } 95 | 96 | /* 97 | t is clear from above output that words “tail” and “tale” have same code. 98 | Hence they are phonetic. 99 | Word “tailor” has different code because it’s not phonetic same. 100 | */ 101 | 102 | 103 | -------------------------------------------------------------------------------- /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/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/WashingMachine/Lavadora.java: -------------------------------------------------------------------------------- 1 | /* 2 | *Se ha creado la clase Lavadora para realizar los metodos requeridos del funcionamiento de una lavadora, 3 | utilizando la encapsulacion correcta de metodos y variables. 4 | *Se solicito que el unico metodo visible sea el metodo 5 | cicloFinalizado(). 6 | 7 | *Instrucciones del programa: 8 | *La variable kilosRopa puede cambiar y se digitaran numeros de 0 hasta 12 9 | *La variable tipoRopa puede ser modificada con dos opciones: 1 - ropa blanca | 2 - ropa color 10 | *Las variables llenado, lavado, secado son modificadas de 0 a 1 para verificar si esos procesos son realizados 11 | con exito 12 | */ 13 | 14 | public class Lavadora { 15 | 16 | private int kilosRopa = 0, tipoRopa = 0, llenado = 0, lavado = 0, secado = 0; 17 | 18 | //Constructor del programa 19 | public Lavadora(int kilosRopa, int tipoRopa){ 20 | this.kilosRopa = kilosRopa; 21 | this.tipoRopa = tipoRopa; 22 | } 23 | 24 | //Metodo llenadoAgua que valida la cantidad de kilos de ropa digitados 25 | private void llenadoAgua(){ 26 | if(kilosRopa <= 12){ 27 | llenado = 1; 28 | System.out.println("Llenando..."); 29 | System.out.println("Llenado"); 30 | }else{ 31 | System.out.println("Carga de ropa elevada, reduzca la carga"); 32 | } 33 | } 34 | 35 | //Metodo de Lavado que realiza la validacion de tipo de ropa 36 | private void Lavado(){ 37 | llenadoAgua(); 38 | if(llenado == 1){ 39 | if(tipoRopa == 1){ 40 | System.out.println("Ropa blanca / Lavado suave"); 41 | System.out.println("Lavando..."); 42 | lavado = 1; 43 | }else if(tipoRopa == 2){ 44 | System.out.println("Ropa Color / Lavado intenso"); 45 | System.out.println("Lavando..."); 46 | lavado = 1; 47 | }else{ 48 | System.out.println("El tipo de ropa es incorrecto"); 49 | System.out.println("Se tratara como Ropa Color / Lavado Intenso"); 50 | lavado = 1; 51 | } 52 | }else{ 53 | System.out.println("No se ha llenado la lavadora, no se puede lavar"); 54 | } 55 | } 56 | 57 | //Metodo Secado que verifica si se realizo el lavado y envia un mensaje por consola 58 | private void Secado(){ 59 | Lavado(); 60 | if(lavado == 1){ 61 | System.out.println("Secando..."); 62 | secado = 1; 63 | } 64 | } 65 | 66 | //Metodo visible que confirma si se realizaron correctamente los otros procesos 67 | public void cicloFinalizado(){ 68 | Secado(); 69 | if(secado == 1){ 70 | System.out.println("El lavado y secado se ha completado"); 71 | } 72 | } 73 | 74 | //Setter y Getter 75 | 76 | public int getTipoRopa(){ 77 | return tipoRopa; 78 | } 79 | 80 | public void setTipoRopa(int tipoRopa){ 81 | this.tipoRopa = tipoRopa; 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /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/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/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/Kruskal.java: -------------------------------------------------------------------------------- 1 | // Kruskal's algorithm in Java 2 | 3 | import java.util.*; 4 | 5 | class Graph { 6 | class Edge implements Comparable { 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/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 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 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/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/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/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/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/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/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/eduEmpDb.java: -------------------------------------------------------------------------------- 1 | // An educational institution wishes to maintain a database of employees. Database is divided into number of classes. 2 | // This hierarchical relationships are shown in the figure, it also shows minimum information required for each class and define methods to create a database 3 | // and retrieve individual info as and when required. 4 | import java.util.Scanner; 5 | class Staff { 6 | // code 7 | // name 8 | Scanner sc = new Scanner(System.in); 9 | public int emp_id; 10 | public String name; 11 | } 12 | 13 | class Teacher extends Staff { 14 | // subject 15 | // publication 16 | public String subject, publication; 17 | public void getData() { 18 | System.out.println("Enter employee details: "); 19 | System.out.println("Enter name: "); 20 | name = sc.nextLine(); 21 | System.out.println("Enter employee id: "); 22 | emp_id = sc.nextInt(); 23 | System.out.println("Enter subject: "); 24 | subject = sc.nextLine(); 25 | System.out.println("Enter publication: "); 26 | publication = sc.nextLine(); 27 | } 28 | public void displayData() { 29 | System.out.println("Displaying employee details: "); 30 | System.out.println("Name: " + name); 31 | System.out.println("Employee id: " + emp_id); 32 | System.out.println("Subject: " + subject); 33 | System.out.println("Publication: " + publication); 34 | } 35 | } 36 | 37 | class Typist extends Staff { 38 | // speed 39 | public double speed; 40 | public void getData() { 41 | System.out.println("Enter employee details: "); 42 | System.out.println("Enter name: "); 43 | name = sc.nextLine(); 44 | System.out.println("Enter employee id: "); 45 | emp_id = sc.nextInt(); 46 | System.out.println("Enter speed: "); 47 | speed = sc.nextDouble(); 48 | } 49 | public void displayData() { 50 | System.out.println("Displaying employee details: "); 51 | System.out.println("Name: " + name); 52 | System.out.println("Employee id: " + emp_id); 53 | System.out.println("Speed: " + speed); 54 | } 55 | } 56 | 57 | class Officer extends Staff { 58 | // grade 59 | public String grade; 60 | public void getData() { 61 | System.out.println("Enter employee details: "); 62 | System.out.println("Enter name: "); 63 | name = sc.nextLine(); 64 | System.out.println("Enter employee id: "); 65 | emp_id = sc.nextInt(); 66 | System.out.println("Enter grade: "); 67 | grade = sc.next(); 68 | } 69 | public void displayData() { 70 | System.out.println("Displaying employee details: "); 71 | System.out.println("Name: " + name); 72 | System.out.println("Employee id: " + emp_id); 73 | System.out.println("Grade: " + grade); 74 | } 75 | } 76 | 77 | class Regular extends Typist { 78 | 79 | } 80 | 81 | class Casual extends Typist { 82 | // daily wages 83 | public double dwages; 84 | public void getData() { 85 | System.out.println("Enter employee details: "); 86 | System.out.println("Enter name: "); 87 | name = sc.nextLine(); 88 | System.out.println("Enter employee id: "); 89 | emp_id = sc.nextInt(); 90 | System.out.println("Enter daily wages: "); 91 | dwages = sc.nextDouble(); 92 | } 93 | public void displayData() { 94 | System.out.println("Displaying employee details: "); 95 | System.out.println("Name: " + name); 96 | System.out.println("Employee id: " + emp_id); 97 | System.out.println("Daily wages: " + dwages); 98 | } 99 | } 100 | public class EduEmpDB { 101 | public static void main(String[] args) { 102 | // TODO Auto-generated method stub 103 | Scanner sc = new Scanner(System.in); 104 | int choice = 0; 105 | do { 106 | System.out.println("Enter 1 for teacher, 2 for regular typist, 3 for casual typist, 4 for officer, 5 to exit: "); 107 | choice = sc.nextInt(); 108 | switch (choice) { 109 | case 1: 110 | Teacher t = new Teacher(); 111 | t.getData(); 112 | t.displayData(); 113 | break; 114 | case 2: 115 | Regular r = new Regular(); 116 | r.getData(); 117 | r.displayData(); 118 | break; 119 | case 3: 120 | Casual c = new Casual(); 121 | c.getData(); 122 | c.displayData(); 123 | break; 124 | case 4: 125 | Officer o = new Officer(); 126 | o.getData(); 127 | o.displayData(); 128 | break; 129 | default: 130 | if (choice != 5) { 131 | System.out.println("Invalid input!"); 132 | } 133 | else if (choice == 5) { 134 | System.out.println("End of program"); 135 | } 136 | } 137 | } while(choice != 5); 138 | } 139 | } 140 | --------------------------------------------------------------------------------