diff --git a/.classpath b/.classpath new file mode 100644 index 00000000..67d5f6d3 --- /dev/null +++ b/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ae3c1726 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/.project b/.project new file mode 100644 index 00000000..ea54703d --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + Java + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/Binary Search.java b/Binary Search.java deleted file mode 100644 index a108de7e..00000000 --- a/Binary Search.java +++ /dev/null @@ -1,53 +0,0 @@ -import java.util.Scanner; - -class BinarySearch -{ - public static int BS(int array[], int key, int lb, int ub) - { - if (lb>ub) - { - return -1; - } - - int mid=(lb+ub)/2; - - if (keyarray[mid]) - { - return (BS(array, key, mid+1, ub)); - } - else - { - return mid; - } - } - - public static void main(String[] args) - { - Scanner input=new Scanner(System.in); - int array[]=new int[10] ; - int key; - - //Input - System.out.println("Enter an array of 10 numbers : "); - for (int i=0; i<10 ;i++ ) - { - array[i]=input.nextInt(); - } - System.out.println("Enter the number to be searched : "); - key=input.nextInt(); - - int index=BS(array, key, 0, 9); - if (index!=-1) - { - System.out.println("Number found at index number : " + index); - } - else - { - System.out.println("Not found"); - } - } -} \ No newline at end of file diff --git a/Bubble Sort.java b/Bubble Sort.java deleted file mode 100644 index b1147d1b..00000000 --- a/Bubble Sort.java +++ /dev/null @@ -1,38 +0,0 @@ -import java.util.Scanner; - -class BubbleSort -{ - public static void main(String[] args) - { - int array[]=new int[6]; - Scanner input=new Scanner(System.in); - - //Input - System.out.println("Enter any 6 Numbers for Unsorted Array : "); - for(int i=0; i<6; i++) - { - array[i]=input.nextInt(); - } - - //Sorting - for(int i=0; i<6; i++) - { - for(int j=0; j<5; j++) - { - if(array[j]>array[j+1]) - { - int temp=array[j]; - array[j]=array[j+1]; - array[j+1]=temp; - } - } - } - - //Output - for(int i=0; i<6; i++) - { - System.out.print(array[i]+"\t"); - } - - } -} \ No newline at end of file diff --git a/Conversions/AnyBaseToDecimal.java b/Conversions/AnyBaseToDecimal.java new file mode 100644 index 00000000..5e04bcf1 --- /dev/null +++ b/Conversions/AnyBaseToDecimal.java @@ -0,0 +1,59 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +// Driver program +public class AnyBaseToDecimal { + public static void main (String[] args) throws Exception{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String inp = br.readLine(); + int base = Integer.parseInt(br.readLine()); + + System.out.println("Input in base " + base + " is: " + inp); + System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base)); + + br.close(); + } + + /** + * This method produces a decimal value of any given input number of any base + * @param inp_num String of which we need the decimal value and base in integer format + * @return string format of the decimal value + */ + + public static String convertToDecimal(String inp_num, int base) { + int len = inp_num.length(); + int num = 0; + int pow = 1; + + for (int i=len-1; i>=0; i--) { + if (valOfChar(inp_num.charAt(i)) >= base) { + return "Invalid Number"; + } + num += valOfChar(inp_num.charAt(i))*pow; + pow *= base; + } + return String.valueOf(num); + } + + /** + * This method produces integer value of the input character and returns it + * @param c Char of which we need the integer value of + * @return integer value of input char + */ + + public static int valOfChar(char c) { + if (c >= '0' && c <= '9') { + return (int)c - '0'; + } + else { + return (int)c - 'A' + 10; + } + } +} diff --git a/Conversions/BinaryToDecimal.java b/Conversions/BinaryToDecimal.java new file mode 100644 index 00000000..9e5494ee --- /dev/null +++ b/Conversions/BinaryToDecimal.java @@ -0,0 +1,33 @@ +import java.util.Scanner; + +/** + * This class converts a Binary number to a Decimal number + * + * @author Unknown + * + */ +class BinaryToDecimal +{ + + /** + * Main Method + * + * @param args Command line arguments + */ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int n,k,d,s=0,c=0; + System.out.print("Binary number: "); + n=sc.nextInt(); + k=n; + while(k!=0) + { + d=k%10; + s+=d*(int)Math.pow(2,c++); + k/=10; + } + System.out.println("Decimal equivalent:"+s); + sc.close(); + } +} diff --git a/Conversions/BinaryToOctal.java b/Conversions/BinaryToOctal.java new file mode 100644 index 00000000..cb04fe54 --- /dev/null +++ b/Conversions/BinaryToOctal.java @@ -0,0 +1,43 @@ +import java.util.Scanner; + +/** + * Converts any Binary number to an Octal Number + * + * @author Zachary Jones + * + */ +public class BinaryToOctal { + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int b = sc.nextInt(); + System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); + sc.close(); + + } + + /** + * This method converts a binary number to + * an octal number. + * + * @param b The binary number + * @return The octal number + */ + public static int convertBinaryToOctal(int b) { + int o = 0, r=0, j =1 ; + while(b!=0) + { + r = b % 10; + o = o + r * j; + j = j * 2; + b = b / 10; + } + return o; + } + +} diff --git a/Conversions/DecimalToAnyBase.java b/Conversions/DecimalToAnyBase.java new file mode 100644 index 00000000..d3927ff8 --- /dev/null +++ b/Conversions/DecimalToAnyBase.java @@ -0,0 +1,65 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +// Driver Program +public class DecimalToAnyBase { + public static void main (String[] args) throws Exception{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter the decimal input below: "); + int decInput = Integer.parseInt(br.readLine()); + System.out.println(); + + System.out.println("Enter the base below: "); + int base = Integer.parseInt(br.readLine()); + System.out.println(); + + System.out.println("Decimal Input" + " is: " + decInput); + System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); + + br.close(); + } + + /** + * This method produces a String value of any given input decimal in any base + * @param inp Decimal of which we need the value in base in String format + * @return string format of the converted value in the given base + */ + + public static String convertToAnyBase(int inp, int base) { + ArrayList charArr = new ArrayList<>(); + + while (inp > 0) { + charArr.add(reVal(inp%base)); + inp /= base; + } + + StringBuilder str = new StringBuilder(charArr.size()); + + for(Character ch: charArr) + { + str.append(ch); + } + + return str.reverse().toString(); + } + + /** + * This method produces character value of the input integer and returns it + * @param num integer of which we need the character value of + * @return character value of input integer + */ + + public static char reVal(int num) { + if (num >= 0 && num <= 9) + return (char)(num + '0'); + else + return (char)(num - 10 + 'A'); + } +} diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java new file mode 100644 index 00000000..671cedf2 --- /dev/null +++ b/Conversions/DecimalToBinary.java @@ -0,0 +1,32 @@ +import java.util.Scanner; + +/** + * This class converts a Decimal number to a Binary number + * + * @author Unknown + * + */ +class DecimalToBinary +{ + /** + * Main Method + * + * @param args Command Line Arguments + */ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int n,k,s=0,c=0,d; + System.out.print("Decimal number: "); + n=sc.nextInt(); + k=n; + while(k!=0) + { + d=k%2; + s=s+d*(int)Math.pow(10,c++); + k/=2; + }//converting decimal to binary + System.out.println("Binary equivalent:"+s); + sc.close(); + } +} diff --git a/Conversions/DecimalToHexaDecimal.java b/Conversions/DecimalToHexaDecimal.java new file mode 100644 index 00000000..3072dec0 --- /dev/null +++ b/Conversions/DecimalToHexaDecimal.java @@ -0,0 +1,33 @@ +import java.lang.StringBuilder; +import java.util.Scanner; + +class Test { + private static final int sizeOfIntInHalfBytes = 8; + private static final int numberOfBitsInAHalfByte = 4; + private static final int halfByte = 0x0F; + private static final char[] hexDigits = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + + public static String decToHex(int dec) { + StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); + hexBuilder.setLength(sizeOfIntInHalfBytes); + for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) + { + int j = dec & halfByte; + hexBuilder.setCharAt(i, hexDigits[j]); + dec >>= numberOfBitsInAHalfByte; + } + return hexBuilder.toString(); + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Write your Number to convert into HexaDecimal: ") + int dec = 305445566; + String hex = Integer.toHexString(dec); + String hex = decToHex(dec); + System.out.println(hex); + } +} \ No newline at end of file diff --git a/Conversions/DecimalToOctal.java b/Conversions/DecimalToOctal.java new file mode 100644 index 00000000..1efa00f8 --- /dev/null +++ b/Conversions/DecimalToOctal.java @@ -0,0 +1,33 @@ +import java.util.Scanner; + +/** + * This class converts Decimal numbers to Octal Numbers + * + * @author Unknown + * + */ +class Decimal_Octal +{ + /** + * Main Method + * + * @param args Command line Arguments + */ + public static void main(String[] args) + { + Scanner sc=new Scanner(System.in); + int n,k,d,s=0,c=0; + System.out.print("Decimal number: "); + n=sc.nextInt(); + k=n; + while(k!=0) + { + d=k%8; + s+=d*(int)Math.pow(10,c++); + k/=8; + } + + System.out.println("Octal equivalent:"+s); + sc.close(); + } +} diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java new file mode 100644 index 00000000..e43bb1de --- /dev/null +++ b/Conversions/HexaDecimalToBinary.java @@ -0,0 +1,37 @@ +import java.lang.StringBuilder; +import java.util.*; +import java.util.Scanner; +import javax.swing.*; + +public class HexaToBin { + + private final int LONG_BITS = 8; + + public void convert(String numHex) { + //String a HexaDecimal: + int conHex = Integer.parseInt(numHex, 16); + //Hex a Binary: + String binary = Integer.toBinaryString(conHex); + //Presentation: + System.out.println(numHex + " = " + completeDigits(binary)); + } + + public String completeDigits(String binNum) { + for (int i = binNum.length(); i < LONG_BITS; i++) { + binNum = "0" + binNum; + } + return binNum; + } + + public static void main(String[] args) { + + //Testing Numbers: + String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", + "19", "01", "02", "03", "04"}; + Convert objConvert = new Convert(); + + for (String num : hexNums) { + objConvert.convert(num); + } + } +} \ No newline at end of file diff --git a/Conversions/OctalToBinary.java b/Conversions/OctalToBinary.java new file mode 100644 index 00000000..6a011c09 --- /dev/null +++ b/Conversions/OctalToBinary.java @@ -0,0 +1,49 @@ +import java.util.Scanner; + +/** + * Converts any Octal number to a Binary number + * + * @author Zachary Jones + * + */ +public class OctalToBinary { + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int o = sc.nextInt(); + System.out.println("Binary equivalent: " + convertOctalToBinary(o)); + sc.close(); + } + + /** + * This method converts an octal number + * to a binary number. + * + * @param o The octal number + * @return The binary number + */ + public static int convertOctalToBinary(int o) { + Scanner scan; + int num; + + void getVal() { + + System.out.println("Octal to Binary"); + scan = new Scanner(System.in); + // Entering the needed number + System.out.println("\nEnter the number : "); + num = Integer.parseInt(scan.nextLine(), 8); + } + + void convert() { + + String binary = Integer.toBinaryString(num); + System.out.println("Binary Value is : " + binary); + } + } +} \ No newline at end of file diff --git a/Conversions/OctalToDecimal.java b/Conversions/OctalToDecimal.java new file mode 100644 index 00000000..637b8f2e --- /dev/null +++ b/Conversions/OctalToDecimal.java @@ -0,0 +1,48 @@ +import java.util.Scanner; + +/** + * Converts any Octal Number to a Decimal Number + * + * @author Zachary Jones + * + */ +public class OctalToDecimal { + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int o = sc.nextInt(); + System.out.println("Decimal equivalent: " + convertOctalToDecimal(o)); + sc.close(); + } + + /** + * This method converts an octal number to + * a decimal number. + * + * @param o The octal number + * @return The decimal number + */ + public static int convertOctalToDecimal(int o) { + System.out.print("Octal Input: "); + // Read the input from the console which we are expecting as an octal number: + Scanner s = new Scanner(System.in); + String inputHex = s.nextLine(); + try{ + // Actual conversion of Octal to Decimal: + Integer outputDecimal = Integer.parseInt(inputHex, 8); + System.out.println("Decimal Equivalent : " + outputDecimal); + } + catch(NumberFormatException ne){ + // Printing a warning message if the input is not a valid octal number: + System.out.println("Invalid Input, Expecting octal number 0-7"); + } + finally{ + s.close(); + } + } +} \ No newline at end of file diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java new file mode 100644 index 00000000..72048153 --- /dev/null +++ b/Dynamic Programming/Fibonacci.java @@ -0,0 +1,75 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.Map; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +public class Fibonacci { + + public static Map map = new HashMap(); + + public static void main(String[] args) throws Exception { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + + System.out.println(fibMemo(n)); // Returns 8 for n = 6 + System.out.println(fibBotUp(n)); // Returns 8 for n = 6 + } + + /** + * This method finds the nth fibonacci number using memoization technique + * + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + **/ + + public static int fibMemo(int n) { + if (map.containsKey(n)) { + return map.get(n); + } + + int f; + + if (n <= 2) { + f = 1; + } + else { + f = fib(n-1) + fib(n-2); + map.put(n,f); + } + + return f; + } + + /** + * This method finds the nth fibonacci number using bottom up + * + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + **/ + + public static int fibBotUp(int n) { + + Map fib = new HashMap(); + + for (int i=1;i= key) + r = m; + else + l = m; + } + + return r; + } + + public static int LIS(int[] array) { + int N = array.length; + if (N == 0) + return 0; + + int[] tail = new int[N]; + int length = 1; // always points empty slot in tail + + tail[0] = array[0]; + for (int i = 1; i < N; i++) { + + // new smallest value + if (array[i] < tail[0]) + tail[0] = array[i]; + + // array[i] extends largest subsequence + else if (array[i] > tail[length-1]) + tail[length++] = array[i]; + + // array[i] will become end candidate of an existing subsequence or + // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i] + // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it) + else + tail[upperBound(tail, -1, length-1, array[i])] = array[i]; + } + + return length; + } +} \ No newline at end of file diff --git a/Huffman.java b/Huffman.java new file mode 100644 index 00000000..b93b7e7c --- /dev/null +++ b/Huffman.java @@ -0,0 +1,158 @@ + +import java.util.Comparator; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; +import java.util.Stack; +/** + * + * @author Mayank Kumar (mk9440) + */ +/* +Output : + +Enter number of distinct letters +6 +Enter letters with its frequncy to encode +Enter letter : a +Enter frequncy : 45 + +Enter letter : b +Enter frequncy : 13 + +Enter letter : c +Enter frequncy : 12 + +Enter letter : d +Enter frequncy : 16 + +Enter letter : e +Enter frequncy : 9 + +Enter letter : f +Enter frequncy : 5 + +Letter Encoded Form +a 0 +b 1 0 1 +c 1 0 0 +d 1 1 1 +e 1 1 0 1 +f 1 1 0 0 + +*/ + +class Node{ +String letr=""; +int freq=0,data=0; +Node left=null,right=null; +} + +//A comparator class to sort list on the basis of their frequency +class comp implements Comparator{ + @Override + public int compare(Node o1, Node o2) { + if(o1.freq>o2.freq){return 1;} + else if(o1.freq it=li.iterator(); + while(it.hasNext()){Node n=it.next();System.out.print(n.freq+" ");}System.out.println(); + } + + //Function for making tree (Huffman Tree) + public static Node make_huffmann_tree(List li){ + //Sorting list in increasing order of its letter frequency + li.sort(new comp()); + Node temp=null; + Iterator it=li.iterator(); + //System.out.println(li.size()); + //Loop for making huffman tree till only single node remains in list + while(true){ + temp=new Node(); + //a and b are Node which are to be combine to make its parent + Node a=new Node(),b=new Node(); + a=null;b=null; + //checking if list is eligible for combining or not + //here first assignment of it.next in a will always be true as list till end will + //must have atleast one node + a=(Node)it.next(); + //Below condition is to check either list has 2nd node or not to combine + //If this condition will be false, then it means construction of huffman tree is completed + if(it.hasNext()){b=(Node)it.next();} + //Combining first two smallest nodes in list to make its parent whose frequncy + //will be equals to sum of frequency of these two nodes + if(b!=null){ + temp.freq=a.freq+b.freq;a.data=0;b.data=1;//assigining 0 and 1 to left and right nodes + temp.left=a;temp.right=b; + //after combing, removing first two nodes in list which are already combined + li.remove(0);//removes first element which is now combined -step1 + li.remove(0);//removes 2nd element which comes on 1st position after deleting first in step1 + li.add(temp);//adding new combined node to list + //print_list(li); //For visualizing each combination step + } + //Sorting after combining to again repeat above on sorted frequency list + li.sort(new comp()); + it=li.iterator();//resetting list pointer to first node (head/root of tree) + if(li.size()==1){return (Node)it.next();} //base condition ,returning root of huffman tree + } +} + + //Function for finding path between root and given letter ch + public static void dfs(Node n,String ch){ + Stack st=new Stack(); // stack for storing path + int freq=n.freq; // recording root freq to avoid it adding in path encoding + find_path_and_encode(st,n,ch,freq); + } + + //A simple utility function to print stack (Used for printing path) + public static void print_path(Stack st){ + for(int i=0;i st,Node root,String s,int f){ + //Base condition + if(root!= null){ + if(root.freq!=f){st.push(root);} // avoiding root to add in path/encoding bits + if(root.letr.equals(s)){print_path(st);return;} // Recursion stopping condition when path gets founded + find_path_and_encode(st,root.left,s,f); + find_path_and_encode(st,root.right,s,f); + //Popping if path not found in right or left of this node,because we previously + //pushed this node in taking a mindset that it might be in path + st.pop(); + } + } + + public static void main(String args[]){ + List li=new LinkedList<>(); + Scanner in=new Scanner(System.in); + System.out.println("Enter number of distinct letters "); + int n=in.nextInt(); + String s[]=new String[n]; + System.out.print("Enter letters with its frequncy to encode\n"); + for(int i=0;i=0 && tempcmp){ //Comparing previous edge value with current value - Cycle Case + w[x][y]=cmp; w[y][x]=cmp; + } + } + + //Implementing Dijkshtra's Algorithm + + Stack t=new Stack(); + int src=in.nextInt(); + for(int i=1;i<=n;i++){ + if(i!=src){t.push(i);}} + Stack p=new Stack(); + p.push(src); + w[src][src]=0; + while(!t.isEmpty()){int min=989997979,loc=-1; + for(int i=0;i0) { + // Obtain the first digit of n in the current base, + // which is equivalent to the integer remainder of (n/base). + // The next digit is obtained by dividing n by the base and + // continuing the process of getting the remainder. This is done + // until n is <=0 and the number in the new base is obtained. + digit = (num % base); + num/=base; + // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character + // form is just its value in ASCII. + + // NOTE: This may cause problems, as the capital letters are ASCII values + // 65-90. It may cause false positives when one digit is, for instance 10 and assigned + // 'A' from the character array and the other is 65 and also assigned 'A'. + + // Regardless, the character is added to the representation of n + // in the current base. + if (digit>=digits.length()) { + digitC=(char)(digit); + newNum+=digitC; + continue; + } + newNum+=digits.charAt(digit); + } + // Num is assigned back its original value for the next iteration. + num=num2; + // Auxiliary method reverses the number. + String reverse = reverse(newNum); + // If the number is read the same as its reverse, then it is a palindrome. + // The current base is returned. + if (reverse.equals(newNum)) { + foundBase=true; + return base; + } + } + } + // If all else fails, n is always a palindrome in base n-1. ("11") + return num-1; + } + + private static String reverse(String str) { + String reverse = ""; + for(int i=str.length()-1; i>=0; i--) { + reverse += str.charAt(i); + } + return reverse; + } + + private static String base2base(String n, int b1, int b2) { + // Declare variables: decimal value of n, + // character of base b1, character of base b2, + // and the string that will be returned. + int decimalValue = 0, charB2; + char charB1; + String output=""; + // Go through every character of n + for (int i=0; i9 and store it in charB2 + if (charB1 >= 'A' && charB1 <= 'Z') + charB2 = 10 + (charB1 - 'A'); + // Else, store the integer value in charB2 + else + charB2 = charB1 - '0'; + // Convert the digit to decimal and add it to the + // decimalValue of n + decimalValue = decimalValue * b1 + charB2; + } + + // Converting the decimal value to base b2: + // A number is converted from decimal to another base + // by continuously dividing by the base and recording + // the remainder until the quotient is zero. The number in the + // new base is the remainders, with the last remainder + // being the left-most digit. + + // While the quotient is NOT zero: + while (decimalValue != 0) { + // If the remainder is a digit < 10, simply add it to + // the left side of the new number. + if (decimalValue % b2 < 10) + output = Integer.toString(decimalValue % b2) + output; + // If the remainder is >= 10, add a character with the + // corresponding value to the new number. (A = 10, B = 11, C = 12, ...) + else + output = (char)((decimalValue % b2)+55) + output; + // Divide by the new base again + decimalValue /= b2; + } + return output; + } +} diff --git a/Misc/Node.java b/Misc/Node.java new file mode 100644 index 00000000..ab495b77 --- /dev/null +++ b/Misc/Node.java @@ -0,0 +1,16 @@ +public class Node { + public Object anElement; + public Node less; + public Node greater; + + public Node(Object theElement) { + this(theElement, null, null); //an empty node at the end will be by itself with no children, therefore the other 2 parameters are always null + //obviously the node can still be a child of other elements + } + + public Node(Object currentElement, Node lessSide, Node greaterSide) { + anElement = currentElement; + this.less = lessSide; + this.greater = greaterSide; + } +} diff --git a/Misc/Palindrome.java b/Misc/Palindrome.java new file mode 100644 index 00000000..6017f088 --- /dev/null +++ b/Misc/Palindrome.java @@ -0,0 +1,16 @@ +class Palindrome { + + public String reverseString(String x){ //*helper method + String output = ""; + for(int i=x.length()-1; i>=0; i--){ + output += x.charAt(i); //addition of chars create String + } + return output; + } + + + public Boolean isPalindrome(String x){ //*palindrome method, returns true if palindrome + return (x.equalsIgnoreCase(reverseString(x))); + } + + } diff --git a/Misc/ReverseString.java b/Misc/ReverseString.java new file mode 100644 index 00000000..81498858 --- /dev/null +++ b/Misc/ReverseString.java @@ -0,0 +1,46 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * This method produces a reversed version of a string + * + * @author Unknown + * + */ +class ReverseString +{ + + /** + * This method reverses the string str and returns it + * @param str String to be reversed + * @return Reversed string + */ + public static String reverse(String str){ + if(str.isEmpty() || str == null) return str; + + char arr[] = str.toCharArray(); + for(int i = 0, j = str.length() - 1; i < j; i++, j--){ + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + return new String(arr); + } + + /** + * Main Method + * + * @param args Command line arguments + * @throws IOException Exception thrown because of BufferedReader + */ + public static void main(String args[]) throws IOException + { + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter the string"); + String srr=br.readLine(); + System.out.println("Reverse="+reverseString(srr)); + br.close(); + } +} + diff --git a/Misc/countwords.java b/Misc/countwords.java new file mode 100644 index 00000000..065c9a10 --- /dev/null +++ b/Misc/countwords.java @@ -0,0 +1,26 @@ +import java.util.Scanner; + +/** + * You enter a string into this program, and it will return how + * many words were in that particular string + * + * @author Marcus + * + */ + class CountTheWords{ + + public static void main(String[] args){ + Scanner input = new Scanner(System.in); + System.out.println("Enter your text: "); + String str = input.nextLine(); + + System.out.println("Your text has " + wordCount(str) + " word(s)"); + input.close(); + } + + public static int wordCount(String s){ + if(s.isEmpty() || s == null) return -1; + return s.trim().split("[\\s]+").length; + } + + } diff --git a/Misc/ft.java b/Misc/ft.java new file mode 100644 index 00000000..815dbd29 --- /dev/null +++ b/Misc/ft.java @@ -0,0 +1,17 @@ +import java.util.Scanner; + + +class FloydTriangle { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); + int r = sc.nextInt(), n = 0; + + for(int i=0; i < r; i++) { + for(int j=0; j <= i; j++) { + System.out.print(++n + " "); + } + System.out.println(); + } + } +} diff --git a/Misc/krishnamurthy.java b/Misc/krishnamurthy.java new file mode 100644 index 00000000..f8137513 --- /dev/null +++ b/Misc/krishnamurthy.java @@ -0,0 +1,29 @@ +import java.util.Scanner; +class krishnamurthy +{ + int fact(int n) + { + int i,p=1; + for(i=n;i>=1;i--) + p=p*i; + return p; + } + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int a,b,s=0; + System.out.print("Enter the number : "); + a=sc.nextInt(); + int n=a; + while(a>0) + { + b=a%10; + s=s+fact(b); + a=a/10; + } + if(s==n) + System.out.print(n+" is a krishnamurthy number"); + else + System.out.print(n+" is not a krishnamurthy number"); + } +} diff --git a/Misc/removeDuplicateFromString.java b/Misc/removeDuplicateFromString.java new file mode 100644 index 00000000..ce8f3499 --- /dev/null +++ b/Misc/removeDuplicateFromString.java @@ -0,0 +1,45 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +public class removeDuplicateFromString { + public static void main (String[] args) throws Exception{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String inp_str = br.readLine(); + + System.out.println("Actual string is: " + inp_str); + System.out.println("String after removing duplicates: " + removeDuplicate(inp_str)); + + br.close(); + } + + /** + * This method produces a string after removing all the duplicate characters from input string and returns it + * Example: Input String - "aabbbccccddddd" + * Output String - "abcd" + * @param s String from which duplicate characters have to be removed + * @return string with only unique characters + */ + + public static String removeDuplicate(String s) { + if(s.isEmpty() || s == null) { + return s; + } + + StringBuilder sb = new StringBuilder(""); + int n = s.length(); + + for (int i = 0; i < n; i++) { + if (sb.toString().indexOf(s.charAt(i)) == -1) { + sb.append(String.valueOf(s.charAt(i))); + } + } + + return sb.toString(); + } +} diff --git a/README.md b/README.md index 36d8fbb4..4b563445 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,97 @@ -# Java -All Algorithms implemented in Java +# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Python.svg)](https://travis-ci.org/TheAlgorithms/Python) + +### All algorithms implemented in Java (for education) + +These are for demonstration purposes only. There are many implementations of sorts in the Java standard library that are much better for performance reasons. + +## Sort Algorithms + + +### Bubble +![alt text][bubble-image] + +From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][bubble-toptal] + + + +### Insertion +![alt text][insertion-image] + +From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][insertion-toptal] + + +### Merge +![alt text][merge-image] + +From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. + +__Properties__ +* Worst case performance O(n log n) +* Best case performance O(n) +* Average case performance O(n) + + +###### View the algorithm in [action][merge-toptal] + + + +### Selection +![alt text][selection-image] + +From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n^2) +* Average case performance O(n^2) + +###### View the algorithm in [action][selection-toptal] + + + +[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort +[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort +[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" + +[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort +[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort +[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" + +[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort +[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort +[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort" + +[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort +[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort +[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort" + +[selection-toptal]: https://www.toptal.com/developers/sorting-algorithms/selection-sort +[selection-wiki]: https://en.wikipedia.org/wiki/Selection_sort +[selection-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Selection_sort_animation.gif/250px-Selection_sort_animation.gif "Selection Sort Sort" + +[shell-toptal]: https://www.toptal.com/developers/sorting-algorithms/shell-sort +[shell-wiki]: https://en.wikipedia.org/wiki/Shellsort +[shell-image]: https://upload.wikimedia.org/wikipedia/commons/d/d8/Sorting_shellsort_anim.gif "Shell Sort" + +[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search +[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif + +[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm +[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png + + +[caesar]: https://upload.wikimedia.org/wikipedia/commons/4/4a/Caesar_cipher_left_shift_of_3.svg diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java new file mode 100644 index 00000000..3949f6a8 --- /dev/null +++ b/Searches/BinarySearch.java @@ -0,0 +1,71 @@ +import java.util.Scanner; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +class BinarySearch +{ + /** + * This method implements the Generic Binary Search + * + * @param array The array to make the binary search + * @param key The number you are looking for + * @param lb The lower bound + * @param ub The upper bound + * @return the location of the key + **/ + + public static > int BS(T array[], T key, int lb, int ub) + { + if ( lb > ub) + return -1; + + int mid = (ub+lb)/2; + int comp = key.compareTo(array[mid]); + + if (comp < 0) + return (BS(array, key, lb, mid-1)); + + if (comp > 0) + return (BS(array, key, mid + 1, ub)); + + return mid; + } + + // Driver Program + public static void main(String[] args) + { + Scanner input=new Scanner(System.in); + + // For INTEGER Input + Integer[] array = new Integer[10]; + int key = 5; + + for (int i = 0; i < 10 ; i++ ) + array[i] = i+1; + + int index = BS(array, key, 0, 9); + + if (index != -1) + System.out.println("Number " + key + " found at index number : " + index); + else + System.out.println("Not found"); + + + // For STRING Input + String[] array1 = {"a", "b", "c", "d", "e"}; + String key1 = "d"; + + int index1 = BS(array1, key1, 0, array1.length-1); + + if (index1 != -1) + System.out.println("String " + key1 + " found at index number : " + index1); + else + System.out.println("Not found"); + + input.close(); + } +} diff --git a/Searches/LinearSearch.java b/Searches/LinearSearch.java new file mode 100644 index 00000000..6c532252 --- /dev/null +++ b/Searches/LinearSearch.java @@ -0,0 +1,77 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +public class LinearSearch{ + /** + * The main method + * @param args Command line arguments + */ + public static void main(String[] args) throws Exception { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + // Test for Integer inputs + Integer[] myArray; + int size = 0; + + //Prompt user to create array and its elements + System.out.print("Enter the array size: "); + size = Integer.parseInt(br.readLine()); + myArray = new Integer[size]; + for (int i = 0; i < size; i++){ + System.out.print("For index " + i + ", enter an integer: "); + myArray[i] = Integer.parseInt(br.readLine()); + } + + //Prompt user to search for particular element + System.out.print("Enter integer to search for: "); + Integer key = Integer.parseInt(br.readLine()); + + //Output array and index of target element, if found + System.out.printf("The integer %d is found in index %d\n", key, linearSearch(myArray, key)); + + // Test for String inputs + String[] myArray1; + int size1 = 0; + + //Prompt user to create array and its elements + System.out.print("Enter the array size: "); + size1 = Integer.parseInt(br.readLine()); + myArray1 = new String[size]; + for (int i = 0; i < size1; i++){ + System.out.print("For index " + i + ", enter a String: "); + myArray1[i] = br.readLine(); + } + + //Prompt user to search for particular element + System.out.print("Enter String to search for: "); + String key1 = br.readLine(); + + //Output array and index of target element, if found + System.out.printf("The string %s is found in index %d\n", key1, linearSearch(myArray1, key1)); + } + + /** + * Generic Linear search method + * + * @param array List to be searched + * @param value Key being searched for + * @return Location of the key + */ + public static > int linearSearch(T[] array, T value) { + int lo = 0; + int hi = array.length - 1; + for (int i = lo; i <= hi; i++) { + if (array[i].compareTo(value) == 0) { + return i; + } + } + return -1; + } +} diff --git a/Selection Sort.java b/Selection Sort.java deleted file mode 100644 index d4f7c0cc..00000000 --- a/Selection Sort.java +++ /dev/null @@ -1,40 +0,0 @@ -import java.util.Scanner; - -class SelectionSort -{ - public static void main(String[] args) - { - int array[]=new int[6]; - Scanner input=new Scanner(System.in); - - //Input - System.out.println("Enter any 6 Numbers for Unsorted Array : "); - for(int i=0; i<6; i++) - { - array[i]=input.nextInt(); - } - - //Sorting - for(int i=0; i<6; i++) - { - int min=i; - for(int j=i+1; j<6; j++) - { - if(array[j]> void BS(T array[], int last) { + //Sorting + boolean swap; + do + { + swap = false; + for (int count = 0; count < last-1; count++) + { + int comp = array[count].compareTo(array[count + 1]); + if (comp > 0) + { + T temp = array[count]; + array[count] = array[count + 1]; + array[count + 1] = temp; + swap = true; + } + } + last--; + } while (swap); + } + + // Driver Program + public static void main(String[] args) + { + // Integer Input + int[] arr1 = {4,23,6,78,1,54,231,9,12}; + int last = arr1.length; + Integer[] array = new Integer[last]; + for (int i=0;i 1 4 6 9 12 23 54 78 231 + for(int i=0; i a b c d e + for(int i=0; i 0) { + int min = this.getRoot(); + sorted[index] = min; + index++; + } + return sorted; + } + + /** + * Gets input to sort + * + * @return unsorted array of integers to sort + */ + public static int[] getInput() { + final int numElements = 6; + int[] unsorted = new int[numElements]; + Scanner input = new Scanner(System.in); + System.out.println("Enter any 6 Numbers for Unsorted Array : "); + for (int i = 0; i < numElements; i++) { + unsorted[i] = input.nextInt(); + } + input.close(); + return unsorted; + } + + /** + * Prints elements in heap + * + * @param heap array representing heap + */ + public static void printData(int[] heap) { + System.out.println("Sorted Elements:"); + for (int i = 0; i < heap.length; i++) { + System.out.print(" " + heap[i] + " "); + } + } + + /** + * Main method + * + * @param args the command line arguments + */ + public static void main(String[] args) { + int[] heap = getInput(); + HeapSort data = new HeapSort(heap); + int[] sorted = data.sort(); + printData(sorted); + } + +} diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java new file mode 100644 index 00000000..c77b895f --- /dev/null +++ b/Sorts/InsertionSort.java @@ -0,0 +1,63 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +class InsertionSort { + + /** + * This method implements the Generic Insertion Sort + * + * @param array The array to be sorted + * @param last The count of total number of elements in array + * Sorts the array in increasing order + **/ + + public static > void IS(T array[], int last) { + T key; + for (int j=1;j=0 && key.compareTo(array[i]) < 0) { + array[i+1] = array[i]; + i--; + } + // Placing the key (Card) at its correct position in the sorted subarray + array[i+1] = key; + } + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + int[] arr1 = {4,23,6,78,1,54,231,9,12}; + int last = arr1.length; + Integer[] array = new Integer[arr1.length]; + for (int i=0;i 1 4 6 9 12 23 54 78 231 + for (int i=0;i a b c d e + for(int i=0; i 0; lastSortedIndex--){ + + //If our extracted element is smaller than element to the right, switch them. + if (sortedArray[lastSortedIndex-1] > extractedElement){ + //move the element to the left of extractedElement to the right in sortedArray + sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1]; + //And move the current extractedElement to the left one (since it's smaller). + sortedArray[lastSortedIndex-1] = extractedElement; + } + else{ + //insert element where it is. + sortedArray[lastSortedIndex] = extractedElement; + //Terminating loop since element is in the right spot. + break; + } + + } + + } + + return sortedArray; + + } + +} diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java new file mode 100644 index 00000000..b53451af --- /dev/null +++ b/Sorts/MergeSort.java @@ -0,0 +1,100 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +class MergeSort { + + /** + * This method implements the Generic Merge Sort + * + * @param arr The array to be sorted + * @param temp The copy of the actual array + * @param left The first index of the array + * @param right The last index of the array + * Recursively sorts the array in increasing order + **/ + + public static > void MS(T[] arr, T[] temp, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + MS(arr, temp, left, mid); + MS(arr, temp,mid + 1, right); + merge(arr, temp, left, mid, right); + } + + } + + /** + * This method implements the merge step of the merge sort + * + * @param arr The array to be sorted + * @param temp The copy of the actual array + * @param left The first index of the array + * @param mid The middle index of the array + * @param right The last index of the array + * merges two parts of an array in increasing order + **/ + + public static > void merge(T[] arr, T[] temp, int left, int mid, int right) { + for (int i=left;i<=right;i++) { + temp[i] = arr[i]; + } + + int i= left; + int j = mid + 1; + int k = left; + + while (i<=mid && j<=right) { + if (temp[i].compareTo(temp[j]) <= 0) { + arr[k] = temp[i]; + i++; + } + else { + arr[k] = temp[j]; + j++; + } + k++; + } + + while (i <= mid) { + arr[k] = temp[i]; + i++; + k++; + } + } + + // Driver program + public static void main(String[] args) { + + // Integer Input + int[] arr = {4,23,6,78,1,54,231,9,12}; + Integer[] array = new Integer[arr.length]; + for (int i=0;i 1 4 6 9 12 23 54 78 231 + for (int i=0;i a b c d e + for(int i=0; i> void QS(T array[], int start, int end) { + if (start < end) { + int PIndex = partition(array, start, end); + QS(array, start, PIndex - 1); + QS(array, PIndex + 1, end); + } + } + + /** + * This method finds the partition index for an array + * + * @param array The array to be sorted + * @param start The first index of an array + * @param end The last index of an array + * Finds the partition index of an array + **/ + + public static > int partition(T array[], int start, int end) { + T pivot = array[end]; + int PIndex = start; + for (int i=start;i> void swap(T[] array, int initial, int fin) { + T temp = array[initial]; + array[initial] = array[fin]; + array[fin] = temp; + } + + // Driver Program + public static void main(String[] args) { + + // For integer input + int[] arr = {3,4,1,32,0,2,44,111,5}; + Integer[] array = new Integer[arr.length]; + for (int i=0;i 0 1 2 3 4 5 32 44 111 + for (int i=0;i a b c d e + for(int i=0; i> void SS(T[] arr, int n) { + + for (int i=0;i 1 4 6 9 12 23 54 78 231 + for(int i=0; i a b c d e + for(int i=0; i= 1) { + for (int i = h; i < N; i++) { + for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) { + exch(array, j, j - h); + } + } + + h /= 3; + } + } + + /** + * Helper method for exchanging places in array + * @param array The array which elements we want to swap + * @param i index of the first element + * @param j index of the second element + */ + private static void exch(Comparable[] array, int i, int j) { + Comparable swap = array[i]; + array[i] = array[j]; + array[j] = swap; + } + + /** + * This method checks if first element is less then the other element + * @param v first element + * @param w second element + * @return true if the first element is less then the second element + */ + private static boolean less(Comparable v, Comparable w) { + return v.compareTo(w) < 0; + } + + public static void main(String[] args) { + // Integer Input + int[] arr1 = {4,23,6,78,1,54,231,9,12}; + Integer[] array = new Integer[arr1.length]; + + for (int i=0;i mx) + mx = arr[i]; + return mx; + } + + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; + int i; + int count[] = new int[10]; + Arrays.fill(count,0); + + for (i = 0; i < n; i++) + count[ (arr[i]/exp)%10 ]++; + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + for (i = n - 1; i >= 0; i--) + { + output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; + count[ (arr[i]/exp)%10 ]--; + } + + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + static void radixsort(int arr[], int n) + { + + int m = getMax(arr, n); + + + for (int exp = 1; m/exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + + static void print(int arr[], int n) + { + for (int i=0; i> { + + ArrayList verticies; + + public AdjacencyListGraph() { + verticies = new ArrayList<>(); + } + + private class Vertex { + E data; + ArrayList adjacentVerticies; + + public Vertex(E data) { + adjacentVerticies = new ArrayList<>(); + this.data = data; + } + + public boolean addAdjacentVertex(Vertex to) { + for (Vertex v: adjacentVerticies) { + if (v.data.compareTo(to.data) == 0) { + return false; // the edge already exists + } + } + return adjacentVerticies.add(to); // this will return true; + } + + public boolean removeAdjacentVertex(E to) { + // use indexes here so it is possible to + // remove easily without implementing + // equals method that ArrayList.remove(Object o) uses + for (int i = 0; i < adjacentVerticies.size(); i++) { + if (adjacentVerticies.get(i).data.compareTo(to) == 0) { + adjacentVerticies.remove(i); + return true; + } + } + return false; + } + } + + /** + * this method removes an edge from the graph between two specified + * verticies + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns false if the edge doesn't exist, returns true if the edge exists and is removed + */ + public boolean removeEdge(E from, E to) { + Vertex fromV = null; + for (Vertex v: verticies) { + if (from.compareTo(v.data) == 0) { + fromV = v; + break; + } + } + if (fromV == null) return false; + return fromV.removeAdjacentVertex(to); + } + /** + * this method adds an edge to the graph between two specified + * verticies + * + * @param from the data of the vertex the edge is from + * @param to the data of the vertex the edge is going to + * @return returns true if the edge did not exist, return false if it already did + */ + public boolean addEdge(E from, E to) { + Vertex fromV = null, toV = null; + for (Vertex v: verticies) { + if (from.compareTo(v.data) == 0) { // see if from vertex already exists + fromV = v; + } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists + toV = v; + } + if (fromV != null && toV != null) break; // both nodes exist so stop searching + } + if (fromV == null) { + fromV = new Vertex(from); + verticies.add(fromV); + } + if (toV == null) { + toV = new Vertex(to); + verticies.add(toV); + } + return fromV.addAdjacentVertex(toV); + } + + /** + * this gives a list of verticies in the graph and their adjacencies + * + * @return returns a string describing this graph + */ + public String toString() { + StringBuilder sb = new StringBuilder(); + for (Vertex v: verticies) { + sb.append("Vertex: "); + sb.append(v.data); + sb.append("\n"); + sb.append("Adjacent verticies: "); + for (Vertex v2: v.adjacentVerticies) { + sb.append(v2.data); + sb.append(" "); + } + sb.append("\n"); + } + return sb.toString(); + } +} + +public class Graphs { + + public static void main(String args[]) { + AdjacencyListGraph graph = new AdjacencyListGraph<>(); + assert graph.addEdge(1, 2); + assert graph.addEdge(1, 5); + assert graph.addEdge(2, 5); + assert !graph.addEdge(1, 2); + assert graph.addEdge(2, 3); + assert graph.addEdge(3, 4); + assert graph.addEdge(4, 1); + assert !graph.addEdge(2, 3); + System.out.println(graph); + } + +} diff --git a/data_structures/Graphs/bfs.java b/data_structures/Graphs/bfs.java new file mode 100644 index 00000000..4f3bd62d --- /dev/null +++ b/data_structures/Graphs/bfs.java @@ -0,0 +1,62 @@ +import java.util.*; + +/** + * Implementation of a Breadth First Search + * + * @author Unknown + * + */ +public class bfs{ + + /** + * The BFS implemented in code to use. + * + * @param a Structure to perform the search on a graph, adjacency matrix etc. + * @param vertices The vertices to use + * @param source The Source + */ + public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices + byte []b=new byte[vertices]; //flag container containing status of each vertices + Arrays.fill(b,(byte)-1); //status initialization + /* code status + -1 = ready + 0 = waiting + 1 = processed */ + + Stack st = new Stack(vertices); //operational stack + st.push(source); //assigning source + while(!st.isEmpty()){ + b[st.peek()]=(byte)0; //assigning waiting status + System.out.println(st.peek()); + int pop=st.peek(); + b[pop]=(byte)1; //assigning processed status + st.pop(); //removing head of the queue + for(int i=0;i { + public class hmnodes{ //HashMap nodes + K key; + V value; + } + + private int size=0; //size of hashmap + private LinkedList buckets[]; //array of addresses of list + + public HashMap(){ + buckets=new LinkedList[4]; //initially create bucket of any size + for(int i=0;i<4;i++) + buckets[i]=new LinkedList<>(); + } + + public void put(K key,V value) throws Exception{ + int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index + int fountAt=find(bi,key); //check if key already exists or not + if(fountAt==-1){ + hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert + temp.key=key; + temp.value=value; + buckets[bi].addLast(temp); + this.size++; + }else{ + buckets[bi].get(fountAt).value=value;//if already exist modify the value + } + + double lambda = (this.size*1.0)/this.buckets.length; + if(lambda>2.0){ + rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0 + } + + return; + } + + + public V get(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return null; + }else{ + return buckets[bi].get(fountAt).value; + } + } + + public V remove(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return null; + }else{ + this.size--; + return buckets[bi].remove(fountAt).value; + } + } + + public boolean containskey(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return false; + }else{ + return true; + } + } + + public int size(){ + return this.size; + } + + + public boolean isempty(){ + return this.size==0; + } + + public ArrayList keyset() throws Exception{ + ArrayList arr=new ArrayList<>(); + for(int i=0;i valueset() throws Exception{ + ArrayList arr=new ArrayList<>(); + for(int i=0;i"+temp.value+"]"); + } + System.out.println(); + } + } + + public int find(int bi,K key) throws Exception{ + for(int i=0;i ob[]= buckets; + buckets=new LinkedList[ob.length*2]; + for(int i=0;i(); + + size = 0; + for(int i=0;i{ + private static class Node{ + Node next; + E value; + private Node(E value, Node next){ + this.value = value; + this.next = next; + } + } + private int size; //For better O.O design this should be private allows for better black box design + private Node head; //this will point to dummy node; + public CircleLinkedList(){ //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; + head = new Node(null,head); //creation of the dummy node + size = 0; + } + public int getSize(){ return size;} // getter for the size... needed because size is private. + public void append(E value){ // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really. + if(value == null){ + throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list. + } + head.next = new Node(value,head); //head.next points to the last element; + size++;} + public E remove(int pos){ + if(pos>size || pos< 0){ + throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors + } + Node iterator = head.next; + Node before = head; //we need to keep track of the element before the element we want to remove we can see why bellow. + for(int i = 1; i<=pos; i++){ + iterator = iterator.next; + before = before.next; + } + E saved = iterator.value; + before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head. + iterator.next = null; // scrubbing + iterator.value = null; + return saved; + + } + + } + diff --git a/data_structures/Lists/DoublyLinkedList.java b/data_structures/Lists/DoublyLinkedList.java new file mode 100644 index 00000000..c3229d9c --- /dev/null +++ b/data_structures/Lists/DoublyLinkedList.java @@ -0,0 +1,214 @@ +/** + * This class implements a DoublyLinkedList. This is done using the classes + * LinkedList and Link. + * + * A linked list is simplar to an array, it holds values. However, + * links in a linked list do not have indees. With a linked list + * you do not need to predetermine it's size as it grows and shrinks + * as it is edited. This is an example of a double ended, doubly + * linked list. Each link references the next link and the previous + * one. + * + * @author Unknown + * + */ + +class DoublyLinkedList{ + /** Head refers to the front of the list */ + private Link head; + /** Tail refers to the back of the list */ + private Link tail; + + /** + * Constructor + */ + public DoublyLinkedList(){ + head = null; + tail = null; + } + + /** + * Insert an element at the head + * + * @param x Element to be inserted + */ + public void insertHead(int x){ + Link newLink = new Link(x); //Create a new link with a value attached to it + if(isEmpty()) //Set the first element added to be the tail + tail = newLink; + else + head.previous = newLink; // newLink <-- currenthead(head) + newLink.next = head; // newLink <--> currenthead(head) + head = newLink; // newLink(head) <--> oldhead + } + + /** + * Insert an element at the tail + * + * @param x Element to be inserted + */ + public void insertTail(int x){ + Link newLink = new Link(x); + newLink.next = null; // currentTail(tail) newlink --> + tail.next = newLink; // currentTail(tail) --> newLink --> + newLink.previous = tail; // currentTail(tail) <--> newLink --> + tail = newLink; // oldTail <--> newLink(tail) --> + } + + /** + * Delete the element at the head + * + * @return The new head + */ + public Link deleteHead(){ + Link temp = head; + head = head.next; // oldHead <--> 2ndElement(head) + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + if(head == null) + tail = null; + return temp; + } + + /** + * Delete the element at the tail + * + * @return The new tail + */ + public Link deleteTail(){ + Link temp = tail; + tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null + tail.next = null; // 2ndLast(tail) --> null + return temp; + } + + /** + * Delete the element from somewhere in the list + * + * @param x element to be deleted + * @return Link deleted + */ + public Link delete(int x){ + Link current = head; + + while(current.value != x) //Find the position to delete + current = current.next; + + if(current == head) + deleteHead(); + + else if(current == tail) + deleteTail(); + + else{ //Before: 1 <--> 2(current) <--> 3 + current.previous.next = current.next; // 1 --> 3 + current.next.previous = current.previous; // 1 <--> 3 + } + return current; + } + + /** + * Inserts element and reorders + * + * @param x Element to be added + */ + public void insertOrdered(int x){ + Link newLink = new Link(x); + Link current = head; + while(current != null && x > current.value) //Find the position to insert + current = current.next; + + if(current == head) + insertHead(x); + + else if(current == null) + insertTail(x); + + else{ //Before: 1 <--> 2(current) <--> 3 + newLink.previous = current.previous; // 1 <-- newLink + current.previous.next = newLink; // 1 <--> newLink + newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3 + current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3 + } + } + + /** + * Returns true if list is empty + * + * @return true if list is empty + */ + public boolean isEmpty(){ + return(head == null); + } + + /** + * Prints contents of the list + */ + public void display(){ //Prints contents of the list + Link current = head; + while(current!=null){ + current.displayLink(); + current = current.next; + } + System.out.println(); + } +} + +/** + * This class is used to implement the nodes of the + * linked list. + * + * @author Unknown + * + */ +class Link{ + /** Value of node */ + public int value; + /** This points to the link in front of the new link */ + public Link next; + /** This points to the link behind the new link */ + public Link previous; + + /** + * Constructor + * + * @param value Value of node + */ + public Link(int value){ + this.value = value; + } + + /** + * Displays the node + */ + public void displayLink(){ + System.out.print(value+" "); + } + + /** + * Main Method + * + * @param args Command line arguments + */ + public static void main(String args[]){ + DoublyLinkedList myList = new DoublyLinkedList(); + + myList.insertHead(13); + myList.insertHead(7); + myList.insertHead(10); + myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + + myList.insertTail(11); + myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> + + myList.deleteTail(); + myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> + + myList.delete(7); + myList.display(); // <-- 10(head) <--> 13(tail) --> + + myList.insertOrdered(23); + myList.insertOrdered(67); + myList.insertOrdered(3); + myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> + } +} \ No newline at end of file diff --git a/data_structures/Lists/SinglyLinkedList.java b/data_structures/Lists/SinglyLinkedList.java new file mode 100644 index 00000000..32747cf2 --- /dev/null +++ b/data_structures/Lists/SinglyLinkedList.java @@ -0,0 +1,151 @@ +/** + * This class implements a SinglyLinked List. This is done + * using SinglyLinkedList class and a LinkForLinkedList Class. + * + * A linked list is implar to an array, it hold values. + * However, links in a linked list do not have indexes. With + * a linked list you do not need to predetermine it's size as + * it gorws and shrinks as it is edited. This is an example of + * a singly linked list. Elements can only be added/removed + * at the head/front of the list. + * + * @author Unknown + * + */ +class SinglyLinkedList{ + /**Head refered to the front of the list */ + private Node head; + + /** + * Constructor of SinglyLinkedList + */ + public SinglyLinkedList(){ + head = null; + } + + /** + * This method inserts an element at the head + * + * @param x Element to be added + */ + public void insertHead(int x){ + Node newNode = new Node(x); //Create a new link with a value attached to it + newNode.next = head; //Set the new link to point to the current head + head = newNode; //Now set the new link to be the head + } + + + /** + * Inserts a new node at a specified position + * @param head head node of the linked list + * @param data data to be stored in a new node + * @param position position at which a new node is to be inserted + * @return reference of the head of the linked list + */ + + Node InsertNth(Node head, int data, int position) { + + Node newNode = new Node(); + newNode.data = data; + + if (position == 0) { + newNode.next = head; + return newNode; + } + + Node current = head; + + while (--position > 0) { + current = current.next; + } + + newNode.next = current.next; + current.next = newNode; + return head; + } + + /** + * This method deletes an element at the head + * + * @return The element deleted + */ + public Node deleteHead(){ + Node temp = head; + head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head + return temp; + } + + /** + * Checks if the list is empty + * + * @return true is list is empty + */ + public boolean isEmpty(){ + return(head == null); + } + + /** + * Prints contents of the list + */ + public void display(){ + Node current = head; + while(current!=null){ + System.out.print(current.getValue()+" "); + current = current.next; + } + System.out.println(); + } + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]){ + SinglyLinkedList myList = new SinglyLinkedList(); + + System.out.println(myList.isEmpty()); //Will print true + + myList.insertHead(5); + myList.insertHead(7); + myList.insertHead(10); + + myList.display(); // 10(head) --> 7 --> 5 + + myList.deleteHead(); + + myList.display(); // 7(head) --> 5 + } +} + +/** + * This class is the nodes of the SinglyLinked List. + * They consist of a vlue and a pointer to the node + * after them. + * + * @author Unknown + * + */ +class Node{ + /** The value of the node */ + public int value; + /** Point to the next node */ + public Node next; //This is what the link will point to + + /** + * Constructor + * + * @param valuein Value to be put in the node + */ + public Node(int valuein){ + value = valuein; + } + + /** + * Returns value of the node + */ + public int getValue(){ + return value; + } + +} diff --git a/data_structures/Matrix/Matrix.java b/data_structures/Matrix/Matrix.java new file mode 100644 index 00000000..652a4e83 --- /dev/null +++ b/data_structures/Matrix/Matrix.java @@ -0,0 +1,197 @@ +/** +* Matrix data-type. +* +* @author Kyler Smith, 2017 +*/ + + +public class Matrix { + + public static void main(String[] args) { + + int[][] data1 = new int[0][0]; + int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}; + + Matrix m1 = new Matrix(data1); + Matrix m2 = new Matrix(data2); + Matrix m3 = new Matrix(data3); + + System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns()); + System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns()); + System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns()); + + //check for reference issues + System.out.println("m2 -->\n" + m2); + data2[1][1] = 101; + System.out.println("m2 -->\n" + m2); + + //test equals + System.out.println("m2==null: " + m2.equals(null)); //false + System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false + System.out.println("m2==m1: " + m2.equals(m1)); //false + System.out.println("m2==m2: " + m2.equals(m2)); //true + System.out.println("m2==m3: " + m2.equals(m3)); //false + + //test operations (valid) + System.out.println("2 * m2:\n" + m2.scale(2)); + System.out.println("m2 + m3:\n" + m2.plus(m3)); + System.out.println("m2 - m3:\n" + m2.minus(m3)); + } + + + /** + * Data needs to be a deep copy as not to change the original state. + */ + private int[][] data; + + /** + * Constructor for the matrix takes in a 2D array + * + * @param pData + */ + public Matrix(int[][] pData) { + + /** Make a deep copy of the data */ + if(pData.length != 0) { + int[][] newData = new int[pData.length][pData[0].length]; + + for(int i = 0; i < pData.length; i++) + for(int j = 0; j < pData[0].length; j++) + newData[i][j] = pData[i][j]; + + this.data = newData; + } else { + this.data = null; + } + } + + /** + * Returns the element specified by the given location + * + * @param x : x cooridinate + * @param y : y cooridinate + * @return int : value at location + */ + public int getElement(int x, int y) { + return data[x][y]; + } + + /** + * Returns the number of rows in the Matrix + * + * @return rows + */ + public int getRows() { + if(this.data == null) + return 0; + + return data.length; + } + + /** + * Returns the number of rows in the Matrix + * + * @return columns + */ + public int getColumns() { + if(this.data == null) + return 0; + return data[0].length; + } + + /** + * Returns this matrix scaled by a factor. That is, computes sA where s is a + * constant and A is a matrix (this object). + * + * @param scalar : value to scale by + * @return A new matrix scaled by the scalar value + */ + public Matrix scale(int scalar) { + + int[][] newData = new int[this.data.length][this.data[0].length]; + + for (int i = 0; i < this.getRows(); ++i) + for(int j = 0; j < this.getColumns(); ++j) + newData[i][j] = this.data[i][j] * scalar; + + return new Matrix(newData); + } + + /** + * Adds this matrix to another matrix. + * + * @param other : Matrix to be added + * @return addend + */ + public Matrix plus(Matrix other) throws RuntimeException { + + int[][] newData = new int[this.data.length][this.data[0].length]; + + if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns()) + throw new RuntimeException("Not the same size matrix."); + + for (int i = 0; i < this.getRows(); ++i) + for(int j = 0; j < this.getColumns(); ++j) + newData[i][j] = this.data[i][j] + other.getElement(i, j); + + return new Matrix(newData); + } + + /** + * Subtracts this matrix from another matrix. + * + * @param other : Matrix to be subtracted + * @return difference + */ + public Matrix minus(Matrix other) throws RuntimeException { + + int[][] newData = new int[this.data.length][this.data[0].length]; + + if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns()) + throw new RuntimeException("Not the same size matrix."); + + for (int i = 0; i < this.getRows(); ++i) + for(int j = 0; j < this.getColumns(); ++j) + newData[i][j] = this.data[i][j] - other.getElement(i, j); + + return new Matrix(newData); + } + + /** + * Checks if the matrix passed is equal to this matrix + * + * @param other : the other matrix + * @return boolean + */ + public boolean equals(Matrix other) { + return this == other; + } + + /** + * Returns the Matrix as a String in the following format + * + * [ a b c ] ... + * [ x y z ] ... + * [ i j k ] ... + * ... + * + * @return Matrix as String + * TODO: Work formatting for different digit sizes + */ + public String toString() { + String str = ""; + + for(int i = 0; i < this.data.length; i++) { + str += "[ "; + for(int j = 0; j < this.data[0].length; j++) { + str += data[i][j]; + str += " "; + } + str += "]"; + str += "\n"; + } + + return str; + } +} diff --git a/data_structures/Queues/PriorityQueues.java b/data_structures/Queues/PriorityQueues.java new file mode 100644 index 00000000..acb6b552 --- /dev/null +++ b/data_structures/Queues/PriorityQueues.java @@ -0,0 +1,123 @@ +/** + * This class implements a PriorityQueue. + * + * A priority queue adds elements into positions based on their priority. + * So the most important elements are placed at the front/on the top. + * In this example I give numbers that are bigger, a higher priority. + * Queues in theory have no fixed size but when using an array + * implementation it does. + * + * @author Unknown + * + */ +class PriorityQueue{ + /** The max size of the queue */ + private int maxSize; + /** The array for the queue */ + private int[] queueArray; + /** How many items are in the queue */ + private int nItems; + + /** + * Constructor + * + * @param size Size of the queue + */ + public PriorityQueue(int size){ + maxSize = size; + queueArray = new int[size]; + nItems = 0; + } + + /** + * Inserts an element in it's appropriate place + * + * @param value Value to be inserted + */ + public void insert(int value){ + if(nItems == 0){ + queueArray[0] = value; + } + else{ + int j = nItems; + while(j > 0 && queueArray[j-1] > value){ + queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion + j--; + } + queueArray[j] = value; //Once the correct position is found the value is inserted + } + nItems++; + } + + /** + * Remove the element from the front of the queue + * + * @return The element removed + */ + public int remove(){ + return queueArray[--nItems]; + } + + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peek(){ + return queueArray[nItems-1]; + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty(){ + return(nItems == 0); + } + + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull(){ + return(nItems == maxSize); + } + + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize(){ + return nItems; + } +} + +/** + * This class implements the PriorityQueue class above. + * + * @author Unknown + * + */ +public class PriorityQueues{ + /** + * Main method + * + * @param args Command Line Arguments + */ + public static void main(String args[]){ + PriorityQueue myQueue = new PriorityQueue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + //[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top + + for(int i = 3; i>=0; i--) + System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2] + + //As you can see, a Priority Queue can be used as a sorting algotithm + } +} \ No newline at end of file diff --git a/data_structures/Queues/Queues.java b/data_structures/Queues/Queues.java new file mode 100644 index 00000000..84638cb2 --- /dev/null +++ b/data_structures/Queues/Queues.java @@ -0,0 +1,148 @@ +/** + * This implements Queues by using the class Queue. + * + * A queue data structure functions the same as a real world queue. + * The elements that are added first are the first to be removed. + * New elements are added to the back/rear of the queue. + * + * @author Unknown + * + */ +class Queue{ + /** Max size of the queue */ + private int maxSize; + /** The array representing the queue */ + private int[] queueArray; + /** Front of the queue */ + private int front; + /** Rear of the queue */ + private int rear; + /** How many items are in the queue */ + private int nItems; + + /** + * Constructor + * + * @param size Size of the new queue + */ + public Queue(int size){ + maxSize = size; + queueArray = new int[size]; + front = 0; + rear = -1; + nItems = 0; + } + + /** + * Inserts an element at the rear of the queue + * + * @param x element to be added + * @return True if the element was added successfully + */ + public boolean insert(int x){ + if(isFull()) + return false; + if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front + rear = -1; + rear++; + queueArray[rear] = x; + nItems++; + return true; + } + + /** + * Remove an element from the front of the queue + * + * @return the new front of the queue + */ + public int remove(){ //Remove an element from the front of the queue + if(isEmpty()){ + System.out.println("Queue is empty"); + return -1; + } + int temp = queueArray[front]; + front++; + if(front == maxSize) //Dealing with wrap-around again + front = 0; + nItems--; + return temp; + } + + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peekFront(){ + return queueArray[front]; + } + + /** + * Checks what's at the rear of the queue + * + * @return element at the rear of the queue + */ + public int peekRear(){ + return queueArray[rear]; + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty(){ + return(nItems == 0); + } + + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull(){ + return(nItems == maxSize); + } + + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize(){ + return nItems; + } +} + +/** + * This class is the example for the Queue class + * + * @author Unknown + * + */ +public class Queues{ + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]){ + Queue myQueue = new Queue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + //[10(front), 2, 5, 3(rear)] + + System.out.println(myQueue.isFull()); //Will print true + + myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue + //[10, 2(front), 5, 3(rear)] + + myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around + // [7(rear), 2(front), 5, 3] + + System.out.println(myQueue.peekFront()); //Will print 2 + System.out.println(myQueue.peekRear()); //Will print 7 + } +} \ No newline at end of file diff --git a/data_structures/Stacks/NodeStack.java b/data_structures/Stacks/NodeStack.java new file mode 100644 index 00000000..c598bb8f --- /dev/null +++ b/data_structures/Stacks/NodeStack.java @@ -0,0 +1,183 @@ +/** +* Implementation of a stack using nodes. +* Unlimited size, no arraylist. +* +* @author Kyler Smith, 2017 +*/ + + +public class NodeStack { + + /** + * Entry point for the program. + */ + public static void main(String[] args) { + NodeStack Stack = new NodeStack(); + + Stack.push(3); + Stack.push(4); + Stack.push(5); + System.out.println("Testing :"); + Stack.print(); // prints : 5 4 3 + + Integer x = Stack.pop(); // x = 5 + Stack.push(1); + Stack.push(8); + Integer y = Stack.peek(); // y = 8 + System.out.println("Testing :"); + Stack.print(); // prints : 8 1 4 3 + + System.out.println("Testing :"); + System.out.println("x : " + x); + System.out.println("y : " + y); + } + + /** + * Information each node should contain. + * @value data : information of the value in the node + * @value head : the head of the stack + * @value next : the next value from this node + * @value previous : the last value from this node + * @value size : size of the stack + */ + private Item data; + private static NodeStack head; + private NodeStack next; + private NodeStack previous; + private static int size = 0; + + + /** + * Constructors for the NodeStack. + */ + public NodeStack() { + } + + private NodeStack(Item item) { + this.data = item; + } + + /** + * Put a value onto the stack. + * + * @param item : value to be put on the stack. + */ + public void push(Item item) { + + NodeStack newNs = new NodeStack(item); + + if(this.isEmpty()) { + NodeStack.setHead(new NodeStack<>(item)); + newNs.setNext(null); + newNs.setPrevious(null); + } else { + newNs.setPrevious(NodeStack.head); + NodeStack.head.setNext(newNs); + NodeStack.head = newNs; + } + + NodeStack.setSize(NodeStack.getSize() + 1); + } + + /** + * Value to be taken off the stack. + * + * @return item : value that is returned. + */ + public Item pop() { + + Item item = (Item) NodeStack.head.getData(); + + NodeStack.head = NodeStack.head.getPrevious(); + NodeStack.head.setNext(null); + + NodeStack.setSize(NodeStack.getSize() - 1); + + return item; + } + + /** + * Value that is next to be taken off the stack. + * + * @return item : the next value that would be popped off the stack. + */ + public Item peek() { + return (Item) NodeStack.head.getData(); + } + + /** + * If the stack is empty or there is a value in. + * + * @return boolean : whether or not the stack has anything in it. + */ + public boolean isEmpty() { + return NodeStack.getSize() == 0; + } + + /** + * Returns the size of the stack. + * + * @return int : number of values in the stack. + */ + public int size() { + return NodeStack.getSize(); + } + + /** + * Print the contents of the stack in the following format. + * + * x <- head (next out) + * y + * z <- tail (first in) + * . + * . + * . + * + */ + public void print() { + for(NodeStack n = NodeStack.head; n != null; n = n.previous) { + System.out.println(n.getData().toString()); + } + } + + /** Getters and setters (private) */ + private NodeStack getHead() { + return NodeStack.head; + } + + private static void setHead(NodeStack ns) { + NodeStack.head = ns; + } + + private NodeStack getNext() { + return next; + } + + private void setNext(NodeStack next) { + this.next = next; + } + + private NodeStack getPrevious() { + return previous; + } + + private void setPrevious(NodeStack previous) { + this.previous = previous; + } + + private static int getSize() { + return size; + } + + private static void setSize(int size) { + NodeStack.size = size; + } + + private Item getData() { + return this.data; + } + + private void setData(Item item) { + this.data = item; + } +} diff --git a/data_structures/Stacks/Stacks.java b/data_structures/Stacks/Stacks.java new file mode 100644 index 00000000..21585631 --- /dev/null +++ b/data_structures/Stacks/Stacks.java @@ -0,0 +1,221 @@ +import java.util.ArrayList; + +/** + * This class implements a Stack using two different implementations. + * Stack is used with a regular array and Stack2 uses an ArrayList. + * + * A stack is exactly what it sounds like. An element gets added to the top of + * the stack and only the element on the top may be removed. This is an example + * of an array implementation of a Stack. So an element can only be added/removed + * from the end of the array. In theory stack have no fixed size, but with an + * array implementation it does. + * + * @author Unknown + * + */ +class Stack{ + /** The max size of the Stack */ + private int maxSize; + /** The array representation of the Stack */ + private int[] stackArray; + /** The top of the stack */ + private int top; + + /** + * Constructor + * + * @param size Size of the Stack + */ + public Stack(int size){ + maxSize = size; + stackArray = new int[maxSize]; + top = -1; + } + + /** + * Adds an element to the top of the stack + * + * @param value The element added + */ + public void push(int value){ + if(!isFull()){ //Checks for a full stack + top++; + stackArray[top] = value; + }else{ + System.out.println("The stack is full, can't insert value"); + } + } + + /** + * Removes the top element of the stack and returns the value you've removed + * + * @return value popped off the Stack + */ + public int pop(){ + if(!isEmpty()){ //Checks for an empty stack + return stackArray[top--]; + }else{ + System.out.println("The stack is already empty"); + return -1; + } + } + + /** + * Returns the element at the top of the stack + * + * @return element at the top of the stack + */ + public int peek(){ + if(!isEmpty()){ //Checks for an empty stack + return stackArray[top]; + }else{ + System.out.println("The stack is empty, cant peek"); + return -1; + } + } + + /** + * Returns true if the stack is empty + * + * @return true if the stack is empty + */ + public boolean isEmpty(){ + return(top == -1); + } + + /** + * Returns true if the stack is full + * + * @return true if the stack is full + */ + public boolean isFull(){ + return(top+1 == maxSize); + } + + /** + * Deletes everything in the Stack + * + * Doesn't delete elements in the array + * but if you call push method after calling + * makeEmpty it will overwrite previous + * values + */ + public void makeEmpty(){ //Doesn't delete elements in the array but if you call + top = -1; //push method after calling makeEmpty it will overwrite previous values + } +} + +/** + * This is an ArrayList Implementation of stack, Where size is not + * a problem we can extend the stack as much as we want. + * + * @author Unknown + * + */ +class Stack2{ + /** ArrayList representation of the stack */ + ArrayList stackList; + + /** + * Constructor + */ + Stack2(){ + stackList=new ArrayList<>(); + } + + /** + * Adds value to the end of list which + * is the top for stack + * + * @param value value to be added + */ + void push(int value){ + stackList.add(value); + } + + /** + * Pops last element of list which is indeed + * the top for Stack + * + * @return Element popped + */ + int pop(){ + + if(!isEmpty()){ // checks for an empty Stack + + int popValue=stackList.get(stackList.size()-1); + stackList.remove(stackList.size()-1); //removes the poped element from the list + return popValue; + } + else{ + System.out.print("The stack is already empty "); + return -1; + } + + } + + /** + * Checks for empty Stack + * + * @return true if stack is empty + */ + boolean isEmpty(){ + if(stackList.isEmpty()) + return true; + + else return false; + + } + + /** + * Top element of stack + * + * @return top element of stack + */ + int peek(){ + return stackList.get(stackList.size()-1); + } + } + +/** + * This class implements the Stack and Stack2 created above + * + * @author Unknown + * + */ +public class Stacks{ + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]){ + Stack myStack = new Stack(4); //Declare a stack of maximum size 4 + //Populate the stack + myStack.push(5); + myStack.push(8); + myStack.push(2); + myStack.push(9); + + System.out.println("*********************Stack Array Implementation*********************"); + System.out.println(myStack.isEmpty()); //will print false + System.out.println(myStack.isFull()); //will print true + System.out.println(myStack.peek()); //will print 9 + System.out.println(myStack.pop()); //will print 9 + System.out.println(myStack.peek()); // will print 2 + + Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4 + //Populate the stack + myStack2.push(5); + myStack2.push(8); + myStack2.push(2); + myStack2.push(9); + + System.out.println("*********************Stack List Implementation*********************"); + System.out.println(myStack2.isEmpty()); //will print false + System.out.println(myStack2.peek()); //will print 9 + System.out.println(myStack2.pop()); //will print 9 + System.out.println(myStack2.peek()); // will print 2 + System.out.println(myStack2.pop()); //will print 2 + } +} diff --git a/data_structures/Trees/AVLTree.java b/data_structures/Trees/AVLTree.java new file mode 100644 index 00000000..a3bde289 --- /dev/null +++ b/data_structures/Trees/AVLTree.java @@ -0,0 +1,212 @@ +public class AVLtree { + + private Node root; + + private class Node { + private int key; + private int balance; + private int height; + private Node left, right, parent; + + Node(int k, Node p) { + key = k; + parent = p; + } + } + + public boolean insert(int key) { + if (root == null) + root = new Node(key, null); + else { + Node n = root; + Node parent; + while (true) { + if (n.key == key) + return false; + + parent = n; + + boolean goLeft = n.key > key; + n = goLeft ? n.left : n.right; + + if (n == null) { + if (goLeft) { + parent.left = new Node(key, parent); + } else { + parent.right = new Node(key, parent); + } + rebalance(parent); + break; + } + } + } + return true; + } + + private void delete(Node node){ + if(node.left == null && node.right == null){ + if(node.parent == null) root = null; + else{ + Node parent = node.parent; + if(parent.left == node){ + parent.left = null; + }else parent.right = null; + rebalance(parent); + } + return; + } + if(node.left!=null){ + Node child = node.left; + while (child.right!=null) child = child.right; + node.key = child.key; + delete(child); + }else{ + Node child = node.right; + while (child.left!=null) child = child.left; + node.key = child.key; + delete(child); + } + } + + public void delete(int delKey) { + if (root == null) + return; + Node node = root; + Node child = root; + + while (child != null) { + node = child; + child = delKey >= node.key ? node.right : node.left; + if (delKey == node.key) { + delete(node); + return; + } + } + } + + private void rebalance(Node n) { + setBalance(n); + + if (n.balance == -2) { + if (height(n.left.left) >= height(n.left.right)) + n = rotateRight(n); + else + n = rotateLeftThenRight(n); + + } else if (n.balance == 2) { + if (height(n.right.right) >= height(n.right.left)) + n = rotateLeft(n); + else + n = rotateRightThenLeft(n); + } + + if (n.parent != null) { + rebalance(n.parent); + } else { + root = n; + } + } + + private Node rotateLeft(Node a) { + + Node b = a.right; + b.parent = a.parent; + + a.right = b.left; + + if (a.right != null) + a.right.parent = a; + + b.left = a; + a.parent = b; + + if (b.parent != null) { + if (b.parent.right == a) { + b.parent.right = b; + } else { + b.parent.left = b; + } + } + + setBalance(a, b); + + return b; + } + + private Node rotateRight(Node a) { + + Node b = a.left; + b.parent = a.parent; + + a.left = b.right; + + if (a.left != null) + a.left.parent = a; + + b.right = a; + a.parent = b; + + if (b.parent != null) { + if (b.parent.right == a) { + b.parent.right = b; + } else { + b.parent.left = b; + } + } + + setBalance(a, b); + + return b; + } + + private Node rotateLeftThenRight(Node n) { + n.left = rotateLeft(n.left); + return rotateRight(n); + } + + private Node rotateRightThenLeft(Node n) { + n.right = rotateRight(n.right); + return rotateLeft(n); + } + + private int height(Node n) { + if (n == null) + return -1; + return n.height; + } + + private void setBalance(Node... nodes) { + for (Node n : nodes) + reheight(n); + n.balance = height(n.right) - height(n.left); + } + + public void printBalance() { + printBalance(root); + } + + private void printBalance(Node n) { + if (n != null) { + printBalance(n.left); + System.out.printf("%s ", n.balance); + printBalance(n.right); + } + } + + private void reheight(Node node){ + if(node!=null){ + node.height=1 + Math.max(height(node.left), height(node.right)); + } + } + + public static void main(String[] args) { + AVLtree tree = new AVLtree(); + + System.out.println("Inserting values 1 to 10"); + for (int i = 1; i < 10; i++) + tree.insert(i); + + System.out.print("Printing balance: "); + tree.printBalance(); + } +} diff --git a/data_structures/Trees/BinaryTree.java b/data_structures/Trees/BinaryTree.java new file mode 100644 index 00000000..3d05f176 --- /dev/null +++ b/data_structures/Trees/BinaryTree.java @@ -0,0 +1,270 @@ +/** + * This entire class is used to build a Binary Tree data structure. + * There is the Node Class and the Tree Class, both explained below. + * + * @author Unknown + * + */ + + +/** + * This class implements the nodes that will go on the Binary Tree. + * They consist of the data in them, the node to the left, the node + * to the right, and the parent from which they came from. + * + * @author Unknown + * + */ +class Node{ + /** Data for the node */ + public int data; + /** The Node to the left of this one */ + public Node left; + /** The Node to the right of this one */ + public Node right; + /** The parent of this node */ + public Node parent; + + /** + * Constructor of Node + * + * @param value Value to put in the node + */ + public Node(int value){ + data = value; + left = null; + right = null; + parent = null; + } +} + + +/** + * A binary tree is a data structure in which an element + * has two successors(children). The left child is usually + * smaller than the parent, and the right child is usually + * bigger. + * + * @author Unknown + * + */ +class Tree{ + /** The root of the Binary Tree */ + private Node root; + + /** + * Constructor + */ + public Tree(){ + root = null; + } + + /** + * Method to find a Node with a certain value + * + * @param key Value being looked for + * @return The node if it finds it, otherwise returns the parent + */ + public Node find(int key){ + Node current = root; + Node last = root; + while(current != null){ + last = current; + if(key < current.data) + current = current.left; + else if(key > current.data) + current = current.right; + //If you find the value return it + else + return current; + } + return last; + } + + /** + * Inserts certain value into the Binary Tree + * + * @param value Value to be inserted + */ + public void put(int value){ + Node newNode = new Node(value); + if(root == null) + root = newNode; + else{ + //This will return the soon to be parent of the value you're inserting + Node parent = find(value); + + //This if/else assigns the new node to be either the left or right child of the parent + if(value < parent.data){ + parent.left = newNode; + parent.left.parent = parent; + return; + } + else{ + parent.right = newNode; + parent.right.parent = parent; + return; + } + } + } + + /** + * Deletes a given value from the Binary Tree + * + * @param value Value to be deleted + * @return If the value was deleted + */ + public boolean remove(int value){ + //temp is the node to be deleted + Node temp = find(value); + + //If the value doesn't exist + if(temp.data != value) + return false; + + //No children + if(temp.right == null && temp.left == null){ + if(temp == root) + root = null; + + //This if/else assigns the new node to be either the left or right child of the parent + else if(temp.parent.data < temp.data) + temp.parent.right = null; + else + temp.parent.left = null; + return true; + } + + //Two children + else if(temp.left != null && temp.right != null){ + Node successor = findSuccessor(temp); + + //The left tree of temp is made the left tree of the successor + successor.left = temp.left; + successor.left.parent = successor; + + //If the successor has a right child, the child's grandparent is it's new parent + if(successor.right != null && successor.parent != temp){ + successor.right.parent = successor.parent; + successor.parent.left = successor.right; + successor.right = temp.right; + successor.right.parent = successor; + } + if(temp == root){ + successor.parent = null; + root = successor; + return true; + } + + //If you're not deleting the root + else{ + successor.parent = temp.parent; + + //This if/else assigns the new node to be either the left or right child of the parent + if(temp.parent.data < temp.data) + temp.parent.right = successor; + else + temp.parent.left = successor; + return true; + } + } + //One child + else{ + //If it has a right child + if(temp.right != null){ + if(temp == root){ + root = temp.right; return true;} + + temp.right.parent = temp.parent; + + //Assigns temp to left or right child + if(temp.data < temp.parent.data) + temp.parent.left = temp.right; + else + temp.parent.right = temp.right; + return true; + } + //If it has a left child + else{ + if(temp == root){ + root = temp.left; return true;} + + temp.left.parent = temp.parent; + + //Assigns temp to left or right side + if(temp.data < temp.parent.data) + temp.parent.left = temp.left; + else + temp.parent.right = temp.left; + return true; + } + } + } + + /** + * This method finds the Successor to the Node given. + * Move right once and go left down the tree as far as you can + * + * @param n Node that you want to find the Successor of + * @return The Successor of the node + */ + public Node findSuccessor(Node n){ + if(n.right == null) + return n; + Node current = n.right; + Node parent = n.right; + while(current != null){ + parent = current; + current = current.left; + } + return parent; + } + + /** + * Returns the root of the Binary Tree + * + * @return the root of the Binary Tree + */ + public Node getRoot(){ + return root; + } + + /** + * Prints leftChild - root - rightChild + * + * @param localRoot The local root of the binary tree + */ + public void inOrder(Node localRoot){ + if(localRoot != null){ + inOrder(localRoot.left); + System.out.print(localRoot.data + " "); + inOrder(localRoot.right); + } + } + + /** + * Prints root - leftChild - rightChild + * + * @param localRoot The local root of the binary tree + */ + public void preOrder(Node localRoot){ + if(localRoot != null){ + System.out.print(localRoot.data + " "); + preOrder(localRoot.left); + preOrder(localRoot.right); + } + } + + /** + * Prints rightChild - leftChild - root + * + * @param localRoot The local root of the binary tree + */ + public void postOrder(Node localRoot){ + if(localRoot != null){ + postOrder(localRoot.left); + postOrder(localRoot.right); + System.out.print(localRoot.data + " "); + } + } +} diff --git a/data_structures/Trees/GenericTree.Java b/data_structures/Trees/GenericTree.Java new file mode 100644 index 00000000..061403c2 --- /dev/null +++ b/data_structures/Trees/GenericTree.Java @@ -0,0 +1,226 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Scanner; + +public class treeclass { + private class Node { + int data; + ArrayList child = new ArrayList<>(); + } + + private Node root; + private int size; + + /* + A generic tree is a tree which can have as many children as it can be + It might be possible that every node present is directly connected to + root node. + + In this code + Every function has two copies: one function is helper function which can be called from + main and from that function a private function is called which will do the actual work. + I have done this, while calling from main one have to give minimum parameters. + + */ + public treeclass() { //Constructor + Scanner scn = new Scanner(System.in); + root = create_treeG(null, 0, scn); + } + + private Node create_treeG(Node node, int childindx, Scanner scn) { + // display + if (node == null) { + System.out.println("Enter root's data"); + } else { + System.out.println("Enter data of parent of index " + node.data + " " + childindx); + } + // input + node = new Node(); + node.data = scn.nextInt(); + System.out.println("number of children"); + int number = scn.nextInt(); + for (int i = 0; i < number; i++) { + Node childd = create_treeG(node, i, scn); + size++; + node.child.add(childd); + } + return node; + } + + /* + Function to display the generic tree + */ + public void display() { //Helper function + display_1(root); + return; + } + + private void display_1(Node parent) { + System.out.print(parent.data + "=>"); + for (int i = 0; i < parent.child.size(); i++) { + System.out.print(parent.child.get(i).data + " "); + } + System.out.println("."); + for (int i = 0; i < parent.child.size(); i++) { + display_1(parent.child.get(i)); + } + return; + } + + /* + One call store the size directly but if you are asked compute size this function to calcuate + size goes as follows + */ + + public int size2call() { + return size2(root); + } + + public int size2(Node roott) { + int sz = 0; + for (int i = 0; i < roott.child.size(); i++) { + sz += size2(roott.child.get(i)); + } + return sz + 1; + } + + /* + Function to compute maximum value in the generic tree + */ + public int maxcall() { + int maxi = root.data; + return max(root, maxi); + } + + private int max(Node roott, int maxi) { + if (maxi < roott.data) + maxi = roott.data; + for (int i = 0; i < roott.child.size(); i++) { + maxi = max(roott.child.get(i), maxi); + } + + return maxi; + } + + /* + Function to compute HEIGHT of the generic tree + */ + + public int heightcall() { + return height(root) - 1; + } + + private int height(Node node) { + int h = 0; + for (int i = 0; i < node.child.size(); i++) { + int k = height(node.child.get(i)); + if (k > h) + h = k; + } + return h + 1; + } + + /* + Function to find whether a number is present in the generic tree or not + */ + + public boolean findcall(int info) { + return find(root, info); + } + + private boolean find(Node node, int info) { + if (node.data == info) + return true; + for (int i = 0; i < node.child.size(); i++) { + if (find(node.child.get(i), info)) + return true; + } + return false; + } + + /* + Function to calculate depth of generic tree + */ + public void depthcaller(int dep) { + depth(root, dep); + } + + public void depth(Node node, int dep) { + if (dep == 0) { + System.out.println(node.data); + return; + } + for (int i = 0; i < node.child.size(); i++) + depth(node.child.get(i), dep - 1); + return; + } + + /* + Function to print generic tree in pre-order + */ + public void preordercall() { + preorder(root); + System.out.println("."); + } + + private void preorder(Node node) { + System.out.print(node.data + " "); + for (int i = 0; i < node.child.size(); i++) + preorder(node.child.get(i)); + } + + /* + Function to print generic tree in post-order + */ + public void postordercall() { + postorder(root); + System.out.println("."); + } + + private void postorder(Node node) { + for (int i = 0; i < node.child.size(); i++) + postorder(node.child.get(i)); + System.out.print(node.data + " "); + } + + /* + Function to print generic tree in level-order + */ + + public void levelorder() { + LinkedList q = new LinkedList<>(); + q.addLast(root); + while (!q.isEmpty()) { + int k = q.getFirst().data; + System.out.print(k + " "); + + for (int i = 0; i < q.getFirst().child.size(); i++) { + q.addLast(q.getFirst().child.get(i)); + } + q.removeFirst(); + } + System.out.println("."); + } + + /* + Function to remove all leaves of generic tree + */ + public void removeleavescall() { + removeleaves(root); + } + + private void removeleaves(Node node) { + ArrayList arr = new ArrayList<>(); + for (int i = 0; i < node.child.size(); i++) { + if (node.child.get(i).child.size() == 0) { + arr.add(i); + // node.child.remove(i); + // i--; + } else + removeleaves(node.child.get(i)); + } + for (int i = arr.size() - 1; i >= 0; i--) { + node.child.remove(arr.get(i) + 0); + } + } + diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java new file mode 100644 index 00000000..c4ff92d0 --- /dev/null +++ b/data_structures/Trees/TreeTraversal.java @@ -0,0 +1,92 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +// Driver Program +public class TreeTraversal { + public static void main(String[] args) { + Node tree = new Node(5); + tree.insert(3); + tree.insert(7); + + // Prints 3 5 7 + tree.printInOrder(); + System.out.println(); + + // Prints 5 3 7 + tree.printPreOrder(); + System.out.println(); + + // Prints 3 7 5 + tree.printPostOrder(); + System.out.println(); + } +} + +/** + * The Node class which initializes a Node of a tree + * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder + * printInOrder: LEFT -> ROOT -> RIGHT + * printPreOrder: ROOT -> LEFT -> RIGHT + * printPostOrder: LEFT -> RIGHT -> ROOT + */ +class Node { + Node left, right; + int data; + + public Node(int data) { + this.data = data; + } + + public void insert (int value) { + if (value < data) { + if (left == null) { + left = new Node(value); + } + else { + left.insert(value); + } + } + else { + if (right == null) { + right = new Node(value); + } + else { + right.insert(value); + } + } + } + + public void printInOrder() { + if (left != null) { + left.printInOrder(); + } + System.out.print(data + " "); + if (right != null) { + right.printInOrder(); + } + } + + public void printPreOrder() { + System.out.print(data + " "); + if (left != null) { + left.printPreOrder(); + } + if (right != null) { + right.printPreOrder(); + } + } + + public void printPostOrder() { + if (left != null) { + left.printPostOrder(); + } + if (right != null) { + right.printPostOrder(); + } + System.out.print(data + " "); + } +} + diff --git a/data_structures/heaps/EmptyHeapException.java b/data_structures/heaps/EmptyHeapException.java new file mode 100644 index 00000000..b7d853c5 --- /dev/null +++ b/data_structures/heaps/EmptyHeapException.java @@ -0,0 +1,18 @@ +/** + * + */ +package heaps; + +/** + * @author Nicolas Renard + * Exception to be thrown if the getElement method is used on an empty heap. + * + */ +@SuppressWarnings("serial") +public class EmptyHeapException extends Exception { + + public EmptyHeapException(String message) { + super(message); + } + +} diff --git a/data_structures/heaps/Heap.java b/data_structures/heaps/Heap.java new file mode 100644 index 00000000..02b2ba27 --- /dev/null +++ b/data_structures/heaps/Heap.java @@ -0,0 +1,41 @@ +package heaps; + +/** + * Interface common to heap data structures.
+ *

Heaps are tree-like data structures that allow storing elements in a specific + * way. Each node corresponds to an element and has one parent node (except for the root) and + * at most two children nodes. Every element contains a key, and those keys + * indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall + * be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a + * max-heap).

+ *

All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in + * O(log n) time.

+ * @author Nicolas Renard + * + * + */ +public interface Heap { + + /** + * + * @return the top element in the heap, the one with lowest key for min-heap or with + * the highest key for max-heap + * @throws Exception if heap is empty + */ + public abstract HeapElement getElement() throws EmptyHeapException; + /** + * Inserts an element in the heap. Adds it to then end and toggle it until it finds its + * right position. + * + * @param element an instance of the HeapElement class. + */ + public abstract void insertElement(HeapElement element); + + /** + * Delete an element in the heap. + * + * @param elementIndex int containing the position in the heap of the element to be deleted. + */ + public abstract void deleteElement(int elementIndex); + +} diff --git a/data_structures/heaps/HeapElement.java b/data_structures/heaps/HeapElement.java new file mode 100644 index 00000000..e0cc93cc --- /dev/null +++ b/data_structures/heaps/HeapElement.java @@ -0,0 +1,132 @@ +/** + * + */ +package heaps; + +import java.lang.Double; +import java.lang.Object; + +/** + * Class for heap elements.
+ *

A heap element contains two attributes: a key which will be used to build the tree (int + * or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit + * to carry any information he/she likes. Be aware that the use of a mutable object might + * jeopardize the integrity of this information.

+ * @author Nicolas Renard + * + */ +public class HeapElement { + private final double key; + private final Object additionalInfo; + + // Constructors + + /** + * + * @param key : a number of primitive type 'double' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(double key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * + * @param key : a number of primitive type 'int' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(int key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * + * @param key : a number of object type 'Integer' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(Integer key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * + * @param key : a number of object type 'Double' + * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry + * additional information of use for the user + */ + public HeapElement(Double key, Object info) { + this.key = key; + this.additionalInfo = info; + } + + /** + * + * @param key : a number of primitive type 'double' + */ + public HeapElement(double key) { + this.key = key; + this.additionalInfo = null; + } + + /** + * + * @param key : a number of primitive type 'int' + */ + public HeapElement(int key) { + this.key = key; + this.additionalInfo = null; + } + + /** + * + * @param key : a number of object type 'Integer' + */ + public HeapElement(Integer key) { + this.key = key; + this.additionalInfo = null; + } + + /** + * + * @param key : a number of object type 'Double' + */ + public HeapElement(Double key) { + this.key = key; + this.additionalInfo = null; + } + + // Getters + /** + * @return the object containing the additional info provided by the user. + */ + public Object getInfo() { + return additionalInfo; + } + /** + * @return the key value of the element + */ + public double getKey() { + return key; + } + + // Overridden object methods + + public String toString() { + return "Key: " + key + " - " +additionalInfo.toString(); + } + /** + * + * @param otherHeapElement + * @return true if the keys on both elements are identical and the additional info objects + * are identical. + */ + public boolean equals(HeapElement otherHeapElement) { + return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); + } +} diff --git a/data_structures/heaps/MaxHeap.java b/data_structures/heaps/MaxHeap.java new file mode 100644 index 00000000..5f774e35 --- /dev/null +++ b/data_structures/heaps/MaxHeap.java @@ -0,0 +1,115 @@ +package heaps; + +import java.util.ArrayList; +import java.util.List; + +/** + * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal + * to its children's. + * @author Nicolas Renard + * + */ +public class MaxHeap implements Heap { + + private final List maxHeap; + + public MaxHeap(List listElements) throws Exception { + maxHeap = new ArrayList(); + for (HeapElement heapElement : listElements) { + if (heapElement != null) insertElement(heapElement); + else System.out.println("Null element. Not added to heap"); + } + if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap."); + } + + // Get the element at a given index. The key for the list is equal to index value - 1 + public HeapElement getElement(int elementIndex) { + if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range"); + return maxHeap.get(elementIndex - 1); + } + + // Get the key of the element at a given index + private double getElementKey(int elementIndex) { + return maxHeap.get(elementIndex - 1).getKey(); + } + + // Swaps two elements in the heap + private void swap(int index1, int index2) { + HeapElement temporaryElement = maxHeap.get(index1 - 1); + maxHeap.set(index1 - 1, maxHeap.get(index2 - 1)); + maxHeap.set(index2 - 1, temporaryElement); + } + + // Toggle an element up to its right place as long as its key is lower than its parent's + private void toggleUp(int elementIndex) { + double key = maxHeap.get(elementIndex - 1).getKey(); + while (getElementKey((int) Math.floor(elementIndex/2)) < key) { + swap(elementIndex, (int) Math.floor(elementIndex/2)); + elementIndex = (int) Math.floor(elementIndex/2); + } + } + + // Toggle an element down to its right place as long as its key is higher + // than any of its children's + private void toggleDown(int elementIndex) { + double key = maxHeap.get(elementIndex - 1).getKey(); + boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size()))); + while ((2*elementIndex <= maxHeap.size()) && wrongOrder) { + // Check whether it shall swap the element with its left child or its right one if any. + if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) { + swap(elementIndex, 2*elementIndex + 1); + elementIndex = 2*elementIndex + 1; + } + else { + swap(elementIndex, 2*elementIndex); + elementIndex = 2*elementIndex; + } + wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size()))); + + } + } + + private HeapElement extractMax() { + HeapElement result = maxHeap.get(0); + deleteElement(0); + return result; + } + + @Override + public void insertElement(HeapElement element) { + maxHeap.add(element); + toggleUp(maxHeap.size()); + + } + + @Override + public void deleteElement(int elementIndex) { + if (maxHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range"); + // The last element in heap replaces the one to be deleted + maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); + maxHeap.remove(maxHeap.size()); + // Shall the new element be moved up... + if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex); + // ... or down ? + else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) || + ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex); + } + + @Override + public HeapElement getElement() throws EmptyHeapException { + try { + return extractMax(); + } catch (Exception e) { + throw new EmptyHeapException("Heap is empty. Error retrieving element"); + } + } + +} + + diff --git a/data_structures/heaps/MinHeap.java b/data_structures/heaps/MinHeap.java new file mode 100644 index 00000000..fbf2b86f --- /dev/null +++ b/data_structures/heaps/MinHeap.java @@ -0,0 +1,115 @@ +/** + * + */ +package heaps; + +import java.util.ArrayList; +import java.util.List; + +/** + * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal + * to its children's. + * @author Nicolas Renard + * + */ +public class MinHeap implements Heap { + + private final List minHeap; + + public MinHeap(List listElements) throws Exception { + minHeap = new ArrayList(); + for (HeapElement heapElement : listElements) { + if (heapElement != null) insertElement(heapElement); + else System.out.println("Null element. Not added to heap"); + } + if (minHeap.size() == 0) System.out.println("No element has been added, empty heap."); + } + + // Get the element at a given index. The key for the list is equal to index value - 1 + public HeapElement getElement(int elementIndex) { + if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range"); + return minHeap.get(elementIndex - 1); + } + + // Get the key of the element at a given index + private double getElementKey(int elementIndex) { + return minHeap.get(elementIndex - 1).getKey(); + } + + // Swaps two elements in the heap + private void swap(int index1, int index2) { + HeapElement temporaryElement = minHeap.get(index1 - 1); + minHeap.set(index1 - 1, minHeap.get(index2 - 1)); + minHeap.set(index2 - 1, temporaryElement); + } + + // Toggle an element up to its right place as long as its key is lower than its parent's + private void toggleUp(int elementIndex) { + double key = minHeap.get(elementIndex - 1).getKey(); + while (getElementKey((int) Math.floor(elementIndex/2)) > key) { + swap(elementIndex, (int) Math.floor(elementIndex/2)); + elementIndex = (int) Math.floor(elementIndex/2); + } + } + + // Toggle an element down to its right place as long as its key is higher + // than any of its children's + private void toggleDown(int elementIndex) { + double key = minHeap.get(elementIndex - 1).getKey(); + boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size()))); + while ((2*elementIndex <= minHeap.size()) && wrongOrder) { + // Check whether it shall swap the element with its left child or its right one if any. + if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) { + swap(elementIndex, 2*elementIndex + 1); + elementIndex = 2*elementIndex + 1; + } + else { + swap(elementIndex, 2*elementIndex); + elementIndex = 2*elementIndex; + } + wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size()))); + + } + } + + private HeapElement extractMin() { + HeapElement result = minHeap.get(0); + deleteElement(0); + return result; + } + + @Override + public void insertElement(HeapElement element) { + minHeap.add(element); + toggleUp(minHeap.size()); + + } + + @Override + public void deleteElement(int elementIndex) { + if (minHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range"); + // The last element in heap replaces the one to be deleted + minHeap.set(elementIndex - 1, getElement(minHeap.size())); + minHeap.remove(minHeap.size()); + // Shall the new element be moved up... + if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex); + // ... or down ? + else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) || + ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex); + } + + @Override + public HeapElement getElement() throws EmptyHeapException { + try { + return extractMin(); + } catch (Exception e) { + throw new EmptyHeapException("Heap is empty. Error retrieving element"); + } + } +} diff --git a/insert_delete_in_array.java b/insert_delete_in_array.java new file mode 100644 index 00000000..12bbdc19 --- /dev/null +++ b/insert_delete_in_array.java @@ -0,0 +1,46 @@ +import java.util.*; +public class Array { + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); // Input statement + System.out.println("Enter the size of the array"); + int size = s.nextInt(); + int a[] = new int[size]; + int i; + + // To enter the initial elements + for(i=0;i