Formatted with Google Java Formatter

This commit is contained in:
github-actions
2020-10-24 10:23:28 +00:00
parent a23bac99e8
commit 5d59a2e828
219 changed files with 13758 additions and 14582 deletions

View File

@ -6,19 +6,18 @@ import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Class for converting from "any" base to "any" other base, when "any" means from 2-36.
* Works by going from base 1 to decimal to base 2. Includes auxiliary method for
* determining whether a number is valid for a given base.
* Class for converting from "any" base to "any" other base, when "any" means from 2-36. Works by
* going from base 1 to decimal to base 2. Includes auxiliary method for determining whether a
* number is valid for a given base.
*
* @author Michael Rolland
* @version 2017.10.10
*/
public class AnyBaseToAnyBase {
/**
* Smallest and largest base you want to accept as valid input
*/
/** Smallest and largest base you want to accept as valid input */
static final int MINIMUM_BASE = 2;
static final int MAXIMUM_BASE = 36;
public static void main(String[] args) {
@ -29,7 +28,8 @@ public class AnyBaseToAnyBase {
try {
System.out.print("Enter number: ");
n = in.next();
System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
System.out.print(
"Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!");
@ -39,7 +39,8 @@ public class AnyBaseToAnyBase {
System.out.println("The number is invalid for this base!");
continue;
}
System.out.print("Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
System.out.print(
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!");
@ -55,25 +56,21 @@ public class AnyBaseToAnyBase {
in.close();
}
/**
* Checks if a number (as a String) is valid for a given base.
*/
/** Checks if a number (as a String) is valid for a given base. */
public static boolean validForBase(String n, int base) {
char[] validDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'};
char[] validDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
// digitsForBase contains all the valid digits for the base given
char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);
// Convert character array into set for convenience of contains() method
HashSet<Character> digitsList = new HashSet<>();
for (int i = 0; i < digitsForBase.length; i++)
digitsList.add(digitsForBase[i]);
for (int i = 0; i < digitsForBase.length; i++) digitsList.add(digitsForBase[i]);
// Check that every digit in n is within the list of valid digits for that base.
for (char c : n.toCharArray())
if (!digitsList.contains(c))
return false;
for (char c : n.toCharArray()) if (!digitsList.contains(c)) return false;
return true;
}
@ -99,11 +96,9 @@ public class AnyBaseToAnyBase {
// store the character in charB1
charB1 = n.charAt(i);
// if it is a non-number, convert it to a decimal value >9 and store it in charB2
if (charB1 >= 'A' && charB1 <= 'Z')
charB2 = 10 + (charB1 - 'A');
if (charB1 >= 'A' && charB1 <= 'Z') charB2 = 10 + (charB1 - 'A');
// Else, store the integer value in charB2
else
charB2 = charB1 - '0';
else charB2 = charB1 - '0';
// Convert the digit to decimal and add it to the
// decimalValue of n
decimalValue = decimalValue * b1 + charB2;
@ -115,18 +110,15 @@ public class AnyBaseToAnyBase {
// 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.
if (0 == decimalValue)
return "0";
if (0 == decimalValue) return "0";
// 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 (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;
else output = (char) ((decimalValue % b2) + 55) + output;
// Divide by the new base again
decimalValue /= b2;
}

View File

@ -1,8 +1,6 @@
package Conversions;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
// Driver program
public class AnyBaseToDecimal {

View File

@ -1,7 +1,8 @@
package Conversions;
import java.util.Scanner;
//given a source number , source base, destination base, this code can give you the destination number.
// given a source number , source base, destination base, this code can give you the destination
// number.
// sn ,sb,db ---> ()dn . this is what we have to do .
public class AnytoAny {
@ -26,5 +27,4 @@ public class AnytoAny {
System.out.println(dn);
scn.close();
}
}

View File

@ -2,10 +2,7 @@ package Conversions;
import java.util.Scanner;
/**
* This class converts a Binary number to a Decimal number
*
*/
/** This class converts a Binary number to a Decimal number */
class BinaryToDecimal {
/**

View File

@ -10,14 +10,14 @@ import java.util.*;
public class BinaryToHexadecimal {
/**
* This method converts a binary number to
* a hexadecimal number.
* This method converts a binary number to a hexadecimal number.
*
* @param binary The binary number
* @return The hexadecimal number
*/
static String binToHex(int binary) {
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
// hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for
// decimal numbers 0 to 15
HashMap<Integer, String> hm = new HashMap<>();
// String to store hexadecimal code
String hex = "";

View File

@ -20,12 +20,10 @@ public class BinaryToOctal {
int b = sc.nextInt();
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
sc.close();
}
/**
* This method converts a binary number to
* an octal number.
* This method converts a binary number to an octal number.
*
* @param binary The binary number
* @return The octal number
@ -46,5 +44,4 @@ public class BinaryToOctal {
}
return octal;
}
}

View File

@ -4,11 +4,7 @@ import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
// Driver Program
public class DecimalToAnyBase {
@ -23,17 +19,18 @@ public class DecimalToAnyBase {
System.out.println();
System.out.println("Decimal Input" + " is: " + decInput);
System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
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<Character> charArr = new ArrayList<>();
@ -44,8 +41,7 @@ public class DecimalToAnyBase {
StringBuilder str = new StringBuilder(charArr.size());
for(Character ch: charArr)
{
for (Character ch : charArr) {
str.append(ch);
}
@ -54,14 +50,12 @@ public class DecimalToAnyBase {
/**
* 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');
if (num >= 0 && num <= 9) return (char) (num + '0');
else return (char) (num - 10 + 'A');
}
}

View File

@ -2,11 +2,7 @@ package Conversions;
import java.util.Scanner;
/**
* This class converts a Decimal number to a Binary number
*
*
*/
/** This class converts a Decimal number to a Binary number */
class DecimalToBinary {
/**
@ -19,11 +15,7 @@ class DecimalToBinary {
bitwiseConversion();
}
/**
* This method converts a decimal number
* to a binary number using a conventional
* algorithm.
*/
/** This method converts a decimal number to a binary number using a conventional algorithm. */
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
@ -38,11 +30,7 @@ class DecimalToBinary {
input.close();
}
/**
* This method converts a decimal number
* to a binary number using a bitwise
* algorithm
*/
/** This method converts a decimal number to a binary number using a bitwise algorithm */
public static void bitwiseConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
@ -56,5 +44,4 @@ class DecimalToBinary {
System.out.println("\tBinary number: " + b);
input.close();
}
}

View File

@ -5,8 +5,9 @@ class DecimalToHexaDecimal {
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' };
private static final char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
// Returns the hex value of the dec entered in the parameter.
public static String decToHex(int dec) {

View File

@ -2,11 +2,7 @@ package Conversions;
import java.util.Scanner;
/**
* This class converts Decimal numbers to Octal Numbers
*
*
*/
/** This class converts Decimal numbers to Octal Numbers */
public class DecimalToOctal {
/**
* Main Method

View File

@ -48,6 +48,7 @@ public class HexToOct {
/**
* Main method that gets the hex input from user and converts it into octal.
*
* @param args arguments
*/
public static void main(String args[]) {
@ -59,7 +60,10 @@ public class HexToOct {
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
decnum =
hex2decimal(
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum
// convert decimal to octal
octalnum = decimal2octal(decnum);

View File

@ -25,8 +25,7 @@ public class HexaDecimalToBinary {
public static void main(String[] args) {
// Testing Numbers:
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB",
"19", "01", "02", "03", "04"};
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"};
HexaDecimalToBinary objConvert = new HexaDecimalToBinary();
for (String num : hexNums) {

View File

@ -35,6 +35,5 @@ public class HexaDecimalToDecimal {
*/
System.out.println("Number in Decimal: " + dec_output);
scan.close();
}
}

View File

@ -3,24 +3,14 @@ package Conversions;
/**
* Converting Integers into Roman Numerals
*
*('I', 1);
*('IV',4);
*('V', 5);
*('IV',9);
*('X', 10);
*('XL',40;
*('L', 50);
*('XC',90);
*('C', 100);
*('D', 500);
*('M', 1000);
*
* <p>('I', 1); ('IV',4); ('V', 5); ('IV',9); ('X', 10); ('XL',40; ('L', 50); ('XC',90); ('C', 100);
* ('D', 500); ('M', 1000);
*/
public class IntegerToRoman {
private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
private static int[] allArabianRomanNumbers =
new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] allRomanNumbers =
new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
// Value must be > 0

View File

@ -6,31 +6,27 @@ 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
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Octal Input: ");
String inputOctal = sc.nextLine();
int result = convertOctalToDecimal(inputOctal);
if (result != -1)
System.out.println("Result convertOctalToDecimal : " + result);
if (result != -1) System.out.println("Result convertOctalToDecimal : " + result);
sc.close();
}
/**
* This method converts an octal number to a decimal number.
*
* @param inputOctal
* The octal number
* @param inputOctal The octal number
* @return The decimal number
*/
public static int convertOctalToDecimal(String inputOctal) {

View File

@ -34,8 +34,7 @@ public class OctalToHexadecimal {
*/
public static String decimalToHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0)
return "0";
if (d <= 0) return "0";
String hex = "";
while (d > 0) {
int digit = d % 16;
@ -45,7 +44,6 @@ public class OctalToHexadecimal {
return hex;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
@ -62,4 +60,3 @@ public class OctalToHexadecimal {
input.close();
}
}

View File

@ -4,10 +4,9 @@ import java.util.*;
public class RomanToInteger {
private static Map<Character, Integer> map = new HashMap<Character, Integer>() {
/**
*
*/
private static Map<Character, Integer> map =
new HashMap<Character, Integer>() {
/** */
private static final long serialVersionUID = 87605733047260530L;
{
@ -18,7 +17,8 @@ public class RomanToInteger {
put('C', 100);
put('D', 500);
put('M', 1000);
}};
}
};
// Roman Number = Roman Numerals
/**

View File

@ -18,31 +18,23 @@ public class Bag<Element> implements Iterable<Element> {
private Node<Element> nextElement;
}
/**
* Create an empty bag
*/
/** Create an empty bag */
public Bag() {
firstElement = null;
size = 0;
}
/**
* @return true if this bag is empty, false otherwise
*/
/** @return true if this bag is empty, false otherwise */
public boolean isEmpty() {
return firstElement == null;
}
/**
* @return the number of elements
*/
/** @return the number of elements */
public int size() {
return size;
}
/**
* @param element - the element to add
*/
/** @param element - the element to add */
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
@ -67,9 +59,7 @@ public class Bag<Element> implements Iterable<Element> {
return false;
}
/**
* @return an iterator that iterates over the elements in this bag in arbitrary order
*/
/** @return an iterator that iterates over the elements in this bag in arbitrary order */
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
@ -86,26 +76,21 @@ public class Bag<Element> implements Iterable<Element> {
return currentElement != null;
}
/**
* remove is not allowed in a bag
*/
/** remove is not allowed in a bag */
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public Element next() {
if (!hasNext())
throw new NoSuchElementException();
if (!hasNext()) throw new NoSuchElementException();
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
/**
* main-method for testing
*/
/** main-method for testing */
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
@ -122,5 +107,4 @@ public class Bag<Element> implements Iterable<Element> {
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
}

View File

@ -26,11 +26,9 @@ public class CircularBuffer {
return i % _buffer_size;
}
public Character readOutChar() {
Character result = null;
// if we have data to read
if (_readable_data.get() > 0) {

View File

@ -7,6 +7,7 @@ import java.util.stream.StreamSupport;
/**
* This class implements a dynamic array
*
* @param <E> the type that each index of the array will hold
*/
public class DynamicArray<E> implements Iterable<E> {
@ -17,6 +18,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* constructor
*
* @param capacity the starting length of the desired array
*/
public DynamicArray(final int capacity) {
@ -25,9 +27,7 @@ public class DynamicArray<E> implements Iterable<E> {
this.elements = new Object[this.capacity];
}
/**
* No-args constructor
*/
/** No-args constructor */
public DynamicArray() {
this.size = 0;
this.capacity = 10;
@ -36,6 +36,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* Doubles the capacity of the array
*
* @return int the new capacity of the array
*/
public int newCapacity() {
@ -45,8 +46,8 @@ public class DynamicArray<E> implements Iterable<E> {
}
/**
* Adds an element to the array
* If full, creates a copy array twice the size of the current one
* Adds an element to the array If full, creates a copy array twice the size of the current one
*
* @param element the element of type <E> to be added to the array
*/
public void add(final E element) {
@ -60,6 +61,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* Places element of type <E> at the desired index
*
* @param index the index for the element to be placed
* @param element the element to be inserted
*/
@ -68,8 +70,8 @@ public class DynamicArray<E> implements Iterable<E> {
}
/**
* get method for element at a given index
* returns null if the index is empty
* get method for element at a given index returns null if the index is empty
*
* @param index the desired index of the element
* @return <E> the element at the specified index
*/
@ -79,6 +81,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* Removes an element from the array
*
* @param index the index of the element to be removed
* @return <E> the element removed
*/
@ -91,6 +94,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* get method for size field
*
* @return int size
*/
public int getSize() {
@ -99,6 +103,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* isEmpty helper method
*
* @return boolean true if the array contains no elements, false otherwise
*/
public boolean isEmpty() {
@ -125,6 +130,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* returns a String representation of this object
*
* @return String a String representing the array
*/
@Override
@ -134,6 +140,7 @@ public class DynamicArray<E> implements Iterable<E> {
/**
* Creates and returns a new Dynamic Array Iterator
*
* @return Iterator a Dynamic Array Iterator
*/
@Override
@ -154,7 +161,8 @@ public class DynamicArray<E> implements Iterable<E> {
public E next() {
if (this.cursor > DynamicArray.this.size) throw new NoSuchElementException();
if (this.cursor > DynamicArray.this.elements.length) throw new ConcurrentModificationException();
if (this.cursor > DynamicArray.this.elements.length)
throw new ConcurrentModificationException();
final E element = DynamicArray.this.getElement(this.cursor);
this.cursor++;
@ -181,8 +189,8 @@ public class DynamicArray<E> implements Iterable<E> {
}
/**
* This class is the driver for the DynamicArray<E> class
* it tests a variety of methods and prints the output
* This class is the driver for the DynamicArray<E> class it tests a variety of methods and prints
* the output
*/
public static void main(String[] args) {
DynamicArray<String> names = new DynamicArray<>();

View File

@ -20,7 +20,9 @@ public class A_Star {
}
}
private ArrayList<Edge> getNeighbours(int from) { return this.graph[from]; }
private ArrayList<Edge> getNeighbours(int from) {
return this.graph[from];
}
// Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) {
@ -40,18 +42,25 @@ public class A_Star {
this.weight = weight;
}
public int getFrom() { return from; }
public int getFrom() {
return from;
}
public int getTo() { return to; }
public int getTo() {
return to;
}
public int getWeight() { return weight; }
public int getWeight() {
return weight;
}
}
// class to iterate during the algorithm execution, and also used to return the solution.
private static class PathAndDistance {
private int distance; // distance advanced so far.
private ArrayList<Integer> path; // list of visited nodes in this path.
private int estimated; //heuristic value associated to the last node od the path (current node).
private int
estimated; // heuristic value associated to the last node od the path (current node).
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
this.distance = distance;
@ -59,18 +68,23 @@ public class A_Star {
this.estimated = estimated;
}
public int getDistance() { return distance; }
public int getDistance() {
return distance;
}
public ArrayList<Integer> getPath() { return path; }
public ArrayList<Integer> getPath() {
return path;
}
public int getEstimated() { return estimated; }
public int getEstimated() {
return estimated;
}
private void printSolution() {
if (this.path != null)
System.out.println("Optimal path: " + this.path.toString() +
", distance: " + this.distance);
else
System.out.println("There is no path available to connect the points");
System.out.println(
"Optimal path: " + this.path.toString() + ", distance: " + this.distance);
else System.out.println("There is no path available to connect the points");
}
}
@ -109,29 +123,31 @@ public class A_Star {
public static void main(String[] args) {
// heuristic function optimistic values
int[] heuristic = {366, 0, 160, 242, 161, 178, 77, 151, 226,
244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374};
int[] heuristic = {
366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374
};
Graph graph = new Graph(20);
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null,
0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null,
16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null,
2, 14, 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null,
15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, 101, null,
6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null,
17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
ArrayList<Integer> graphData =
new ArrayList<>(
Arrays.asList(
0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151,
null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14,
146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14,
13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null,
17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic);
solution.printSolution();
}
public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
//nodes are prioritised by the less value of the current distance of their paths, and the estimated value
// nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value
// given by the heuristic function to reach the destination point from the current point.
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>
(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
PriorityQueue<PathAndDistance> queue =
new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(Arrays.asList(from)), 0));
@ -140,20 +156,24 @@ public class A_Star {
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring.
int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); //current node.
if (currentPosition == to)
solutionFound = true;
int currentPosition =
currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) solutionFound = true;
else
for (Edge edge : graph.getNeighbours(currentPosition))
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path.
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(),
updatedPath, heuristic[edge.getTo()]));
queue.add(
new PathAndDistance(
currentData.getDistance() + edge.getWeight(),
updatedPath,
heuristic[edge.getTo()]));
}
}
return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1);
//Out of while loop, if there is a solution, the current Data stores the optimal path, and its distance
// Out of while loop, if there is a solution, the current Data stores the optimal path, and its
// distance
}
}

View File

@ -1,6 +1,7 @@
package DataStructures.Graphs;
import java.util.*;
class BellmanFord
/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
start vertex, end vertes and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/
@ -8,14 +9,14 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
int vertex, edge;
private Edge edges[];
private int index = 0;
BellmanFord(int v,int e)
{
BellmanFord(int v, int e) {
vertex = v;
edge = e;
edges = new Edge[e];
}
class Edge
{
class Edge {
int u, v;
int w;
/**
@ -23,8 +24,7 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
* @param v End vertex
* @param c Weight
*/
public Edge(int a,int b,int c)
{
public Edge(int a, int b, int c) {
u = a;
v = b;
w = c;
@ -34,19 +34,21 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
* @param p[] Parent array which shows updates in edges
* @param i Current vertex under consideration
*/
void printPath(int p[],int i)
{
void printPath(int p[], int i) {
if (p[i] == -1) // Found the path back to parent
return;
printPath(p, p[i]);
System.out.print(i + " ");
}
public static void main(String args[])
{
public static void main(String args[]) {
BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables
obj.go();
}
public void go()//Interactive run for understanding the class first time. Assumes source vertex is 0 and shows distaance to all vertices
public void
go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
// shows distaance to all vertices
{
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
int i, v, e, u, ve, w, j, neg = 0;
@ -55,25 +57,24 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
e = sc.nextInt();
Edge arr[] = new Edge[e]; // Array of edges
System.out.println("Input edges");
for(i=0;i<e;i++)
{
for (i = 0; i < e; i++) {
u = sc.nextInt();
ve = sc.nextInt();
w = sc.nextInt();
arr[i] = new Edge(u, ve, w);
}
int dist[]=new int[v];//Distance array for holding the finalized shortest path distance between source and all vertices
int dist[] =
new int
[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
int p[] = new int[v]; // Parent array for holding the paths
for(i=0;i<v;i++)
dist[i]=Integer.MAX_VALUE;//Initializing distance values
for (i = 0; i < v; i++) dist[i] = Integer.MAX_VALUE; // Initializing distance values
dist[0] = 0;
p[0] = -1;
for(i=0;i<v-1;i++)
{
for(j=0;j<e;j++)
{
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
{
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@ -81,8 +82,7 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
}
// Final cycle for negative checking
for (j = 0; j < e; j++)
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
{
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
@ -90,11 +90,9 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
if (neg == 0) // Go ahead and show results of computaion
{
System.out.println("Distances are: ");
for(i=0;i<v;i++)
System.out.println(i+" "+dist[i]);
for (i = 0; i < v; i++) System.out.println(i + " " + dist[i]);
System.out.println("Path followed:");
for(i=0;i<v;i++)
{
for (i = 0; i < v; i++) {
System.out.print("0 ");
printPath(p, i);
System.out.println();
@ -107,22 +105,25 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
* @param end Ending vertex
* @param Edge Array of edges
*/
public void show(int source,int end, Edge arr[])//Just shows results of computation, if graph is passed to it. The graph should
public void show(
int source,
int end,
Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should
// be created by using addEdge() method and passed by calling getEdgeArray() method
{
int i, j, v = vertex, e = edge, neg = 0;
double dist[]=new double[v];//Distance array for holding the finalized shortest path distance between source and all vertices
double dist[] =
new double
[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
int p[] = new int[v]; // Parent array for holding the paths
for(i=0;i<v;i++)
dist[i]=Integer.MAX_VALUE;//Initializing distance values
for (i = 0; i < v; i++) dist[i] = Integer.MAX_VALUE; // Initializing distance values
dist[source] = 0;
p[source] = -1;
for(i=0;i<v-1;i++)
{
for(j=0;j<e;j++)
{
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
{
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@ -130,8 +131,7 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
}
// Final cycle for negative checking
for (j = 0; j < e; j++)
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
{
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
@ -154,8 +154,8 @@ start vertex, end vertes and weights. Vertices should be labelled with a number
{
edges[index++] = new Edge(x, y, z);
}
public Edge[] getEdgeArray()
{
public Edge[] getEdgeArray() {
return edges;
}
}

View File

@ -37,8 +37,7 @@ class Graph<E extends Comparable<E>> {
}
/**
* Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they
* will be added to it.
* Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they will be added to it.
*
* @param startNode the starting Node from the edge
* @param endNode the ending Node from the edge
@ -65,10 +64,9 @@ class Graph<E extends Comparable<E>> {
}
/**
* Main method used for counting the connected components. Iterates through
* the array of nodes to do a depth first search to get all nodes of the
* graph from the actual node. These nodes are added to the array
* markedNodes and will be ignored if they are chosen in the nodeList.
* Main method used for counting the connected components. Iterates through the array of nodes to
* do a depth first search to get all nodes of the graph from the actual node. These nodes are
* added to the array markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*/

View File

@ -1,8 +1,7 @@
package DataStructures.Graphs;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Scanner;
class Cycle {
@ -11,7 +10,6 @@ class Cycle {
private boolean[] visited;
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
public Cycle() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of nodes: ");
@ -35,7 +33,6 @@ class Cycle {
adjacencyMatrix[start][end] = 1;
}
in.close();
}
public void start() {
@ -78,9 +75,7 @@ class Cycle {
System.out.println(cycles.get(i).get(0));
System.out.println();
}
}
}
public class Cycles {

View File

@ -9,12 +9,17 @@ public class FloydWarshall {
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1];//stores the value of distance from all the possible path form the source vertex to destination vertex
DistanceMatrix =
new int[numberofvertices + 1]
[numberofvertices
+ 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex
Arrays.fill(DistanceMatrix, 0);
this.numberofvertices = numberofvertices;
}
public void floydwarshall(int AdjacencyMatrix[][])//calculates all the distances from source to destination vertex
public void floydwarshall(
int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex
{
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
@ -29,14 +34,13 @@ public class FloydWarshall {
// if the new distance calculated is less then the earlier shortest
// calculated distance it get replaced as new shortest distance
{
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
+ DistanceMatrix[intermediate][destination];
DistanceMatrix[source][destination] =
DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
}
}
}
}
for (int source = 1; source <= numberofvertices; source++)
System.out.print("\t" + source);
for (int source = 1; source <= numberofvertices; source++) System.out.print("\t" + source);
System.out.println();
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");

View File

@ -1,7 +1,6 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.lang.StringBuilder;
class AdjacencyListGraph<E extends Comparable<E>> {
@ -44,8 +43,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
/**
* this method removes an edge from the graph between two specified
* verticies
* 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
@ -64,8 +62,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
/**
* this method adds an edge to the graph between two specified
* verticies
* 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
@ -129,5 +126,4 @@ public class Graphs {
assert !graph.addEdge(2, 3);
System.out.println(graph);
}
}

View File

@ -1,8 +1,12 @@
// Problem -> Connect all the edges with the minimum cost.
//Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the group of edges with the minimum sum of their weights that connect the whole graph.
//The graph needs to be connected, because if there are nodes impossible to reach, there are no edges that could connect every node in the graph.
//KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a Priority Queue is used, to take first those less weighted.
//This implementations below has some changes compared to conventional ones, but they are explained all along the code.
// Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the
// group of edges with the minimum sum of their weights that connect the whole graph.
// The graph needs to be connected, because if there are nodes impossible to reach, there are no
// edges that could connect every node in the graph.
// KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a
// Priority Queue is used, to take first those less weighted.
// This implementations below has some changes compared to conventional ones, but they are explained
// all along the code.
import java.util.Comparator;
import java.util.HashSet;
@ -10,7 +14,8 @@ import java.util.PriorityQueue;
public class Kruskal {
//Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of vertices
// Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of
// vertices
private static class Edge {
private int from;

View File

@ -14,7 +14,6 @@ public class MatrixGraphs {
graph.addEdge(2, 3);
System.out.println(graph);
}
}
class AdjacencyMatrixGraph {
@ -81,8 +80,7 @@ class AdjacencyMatrixGraph {
}
/**
* This method adds an edge to the graph between two specified
* vertices
* This method adds an edge to the graph between two specified vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
@ -102,8 +100,7 @@ class AdjacencyMatrixGraph {
}
/**
* this method removes an edge from the graph between two specified
* vertices
* this method removes an edge from the graph between two specified vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
@ -142,5 +139,4 @@ class AdjacencyMatrixGraph {
}
return s;
}
}

View File

@ -1,8 +1,8 @@
package DataStructures.Graphs;
/**
* A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
* adjacency matrix representation of the graph
* A Java program for Prim's Minimum Spanning Tree (MST) algorithm. adjacency matrix representation
* of the graph
*/
class PrimMST {
// Number of vertices in the graph
@ -28,8 +28,7 @@ class PrimMST {
void printMST(int parent[], int n, int graph[][]) {
System.out.println("Edge Weight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + " " +
graph[i][parent[i]]);
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented
@ -72,8 +71,7 @@ class PrimMST {
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] != 0 && mstSet[v] == false &&
graph[u][v] < key[v]) {
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
@ -93,11 +91,9 @@ class PrimMST {
(3)-------(4)
9 */
PrimMST t = new PrimMST();
int graph[][] = new int[][]{{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
int graph[][] =
new int[][] {
{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0},
};
// Print the solution

View File

@ -15,8 +15,7 @@ public class HashMap {
public int hashing(int key) {
int hash = key % hsize;
if (hash < 0)
hash += hsize;
if (hash < 0) hash += hsize;
return hash;
}
@ -25,7 +24,6 @@ public class HashMap {
buckets[hash].insert(key);
}
public void deleteHash(int key) {
int hash = hashing(key);
@ -71,7 +69,6 @@ public class HashMap {
System.out.println("List is empty");
return null;
}
}
private Node findKey(Node n, int key) {

View File

@ -3,9 +3,8 @@ package DataStructures.HashMap.Hashing;
import java.util.*;
/**
* This class is an implementation of a hash table using linear probing
* It uses a dynamic array to lengthen the size of the hash table when
* load factor > .7
* This class is an implementation of a hash table using linear probing It uses a dynamic array to
* lengthen the size of the hash table when load factor > .7
*/
public class HashMapLinearProbing {
private int hsize; // size of the hash table
@ -15,6 +14,7 @@ public class HashMapLinearProbing {
/**
* Constructor initializes buckets array, hsize, and creates dummy object for AVAILABLE
*
* @param hsize the desired size of the hash map
*/
public HashMapLinearProbing(int hsize) {
@ -26,6 +26,7 @@ public class HashMapLinearProbing {
/**
* The Hash Function takes a given key and finds an index based on its data
*
* @param key the desired key to be converted
* @return int an index corresponding to the key
*/
@ -39,6 +40,7 @@ public class HashMapLinearProbing {
/**
* inserts the key into the hash map by wrapping it as an Integer object
*
* @param key the desired key to be inserted in the hash map
*/
public void insertHash(int key) {
@ -67,6 +69,7 @@ public class HashMapLinearProbing {
/**
* deletes a key from the hash map and adds an available placeholder
*
* @param key the desired key to be deleted
*/
public void deleteHash(int key) {
@ -94,9 +97,7 @@ public class HashMapLinearProbing {
System.out.println("Key " + key + " not found");
}
/**
* Displays the hash table line by line
*/
/** Displays the hash table line by line */
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
if (buckets[i] == null || buckets[i] == AVAILABLE) {
@ -104,12 +105,12 @@ public class HashMapLinearProbing {
} else {
System.out.println("Bucket " + i + ": " + buckets[i].toString());
}
}
}
/**
* Finds the index of location based on an inputed key
*
* @param key the desired key to be found
* @return int the index where the key is located
*/
@ -128,7 +129,8 @@ public class HashMapLinearProbing {
buckets[hash] = AVAILABLE;
return hash;
}
} catch (Exception E) {}
} catch (Exception E) {
}
if (hash + 1 < hsize) {
hash++;
@ -147,9 +149,8 @@ public class HashMapLinearProbing {
}
/**
* Checks the load factor of the hash table
* if greater than .7, automatically lengthens table
* to prevent further collisions
* Checks the load factor of the hash table if greater than .7, automatically lengthens table to
* prevent further collisions
*/
public void checkLoadFactor() {
double factor = (double) size / hsize;
@ -163,6 +164,7 @@ public class HashMapLinearProbing {
/**
* isFull returns true if the hash map is full and false if not full
*
* @return boolean is Empty
*/
public boolean isFull() {
@ -178,6 +180,7 @@ public class HashMapLinearProbing {
/**
* isEmpty returns true if the hash map is empty and false if not empty
*
* @return boolean is Empty
*/
public boolean isEmpty() {

View File

@ -20,29 +20,32 @@ public class Main {
choice = In.nextInt();
switch (choice) {
case 1: {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2: {
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3: {
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4: {
case 4:
{
In.close();
return;
}
}
}
}
}

View File

@ -22,39 +22,44 @@ public class MainLinearProbing {
choice = In.nextInt();
switch (choice) {
case 1: {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2: {
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3: {
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4: {
case 4:
{
In.close();
return;
}
case 5: {
case 5:
{
System.out.println("Enter the Key to find and print: ");
key = In.nextInt();
System.out.println("Key: " + key + " is at index: " + h.findHash(key));
break;
}
case 6: {
case 6:
{
h.checkLoadFactor();
break;
}
}
}
}
}

View File

@ -1,8 +1,7 @@
package DataStructures.Heaps;
/**
* @author Nicolas Renard
* Exception to be thrown if the getElement method is used on an empty heap.
* @author Nicolas Renard Exception to be thrown if the getElement method is used on an empty heap.
*/
@SuppressWarnings("serial")
public class EmptyHeapException extends Exception {
@ -10,5 +9,4 @@ public class EmptyHeapException extends Exception {
public EmptyHeapException(String message) {
super(message);
}
}

View File

@ -2,29 +2,30 @@ package DataStructures.Heaps;
/**
* Interface common to heap data structures.<br>
* <p>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).</p>
* <p>All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in
* O(log n) time.</p>
*
* <p>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).
*
* <p>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
* @return the top element in the heap, the one with lowest key for min-heap or with the highest
* key for max-heap
* @throws EmptyHeapException if heap is empty
*/
HeapElement getElement() throws EmptyHeapException;
/**
* Inserts an element in the heap. Adds it to then end and toggle it until it finds its
* right position.
* 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.
*/
@ -36,5 +37,4 @@ public interface Heap {
* @param elementIndex int containing the position in the heap of the element to be deleted.
*/
void deleteElement(int elementIndex);
}

View File

@ -1,14 +1,13 @@
package DataStructures.Heaps;
import java.lang.Double;
import java.lang.Object;
/**
* Class for heap elements.<br>
* <p>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. </p>
*
* <p>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
*/
@ -58,33 +57,25 @@ public class HeapElement {
this.additionalInfo = info;
}
/**
* @param key : a number of primitive type 'double'
*/
/** @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'
*/
/** @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'
*/
/** @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'
*/
/** @param key : a number of object type 'Double' */
public HeapElement(Double key) {
this.key = key;
this.additionalInfo = null;
@ -92,16 +83,12 @@ public class HeapElement {
// Getters
/**
* @return the object containing the additional info provided by the user.
*/
/** @return the object containing the additional info provided by the user. */
public Object getInfo() {
return additionalInfo;
}
/**
* @return the key value of the element
*/
/** @return the key value of the element */
public double getKey() {
return key;
}
@ -114,15 +101,16 @@ public class HeapElement {
/**
* @param otherHeapElement
* @return true if the keys on both elements are identical and the additional info objects
* are identical.
* @return true if the keys on both elements are identical and the additional info objects are
* identical.
*/
@Override
public boolean equals(Object o) {
if (o != null) {
if (!(o instanceof HeapElement)) return false;
HeapElement otherHeapElement = (HeapElement) o;
return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
return (this.key == otherHeapElement.key)
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo));
}
return false;
}

View File

@ -4,8 +4,8 @@ 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.
* 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
*/
@ -59,18 +59,22 @@ public class MaxHeap implements Heap {
// 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())));
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))) {
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())));
wrongOrder =
(key < getElementKey(elementIndex * 2))
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
}
}
@ -84,7 +88,6 @@ public class MaxHeap implements Heap {
public void insertElement(HeapElement element) {
maxHeap.add(element);
toggleUp(maxHeap.size());
}
@Override
@ -101,10 +104,13 @@ public class MaxHeap implements Heap {
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.0))) toggleUp(elementIndex);
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0)))
toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) ||
((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))))
else if (((2 * elementIndex <= maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2))))
toggleDown(elementIndex);
}

View File

@ -4,8 +4,8 @@ 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.
* 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
*/
@ -54,18 +54,22 @@ public class MinHeap implements Heap {
// 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())));
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))) {
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())));
wrongOrder =
(key > getElementKey(elementIndex * 2))
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
}
}
@ -79,7 +83,6 @@ public class MinHeap implements Heap {
public void insertElement(HeapElement element) {
minHeap.add(element);
toggleUp(minHeap.size());
}
@Override
@ -96,10 +99,13 @@ public class MinHeap implements Heap {
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.0))) toggleUp(elementIndex);
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0)))
toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) ||
((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))))
else if (((2 * elementIndex <= minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2))))
toggleDown(elementIndex);
}

View File

@ -1,17 +1,14 @@
package DataStructures.Heaps;
/**
* Minimum Priority Queue
* It is a part of heap data structure
* A heap is a specific tree based data structure
* in which all the nodes of tree are in a specific order.
* that is the children are arranged in some
* respect of their parents, can either be greater
* or less than the parent. This makes it a min priority queue
* or max priority queue.
* Minimum Priority Queue It is a part of heap data structure A heap is a specific tree based data
* structure in which all the nodes of tree are in a specific order. that is the children are
* arranged in some respect of their parents, can either be greater or less than the parent. This
* makes it a min priority queue or max priority queue.
*
* <p>
* <p>
* Functions: insert, delete, peek, isEmpty, print, heapSort, sink
*
* <p>Functions: insert, delete, peek, isEmpty, print, heapSort, sink
*/
public class MinPriorityQueue {
private int[] heap;
@ -28,8 +25,7 @@ public class MinPriorityQueue {
// inserts the key at the end and rearranges it
// so that the binary heap is in appropriate order
public void insert(int key) {
if (this.isFull())
return;
if (this.isFull()) return;
this.heap[this.size + 1] = key;
int k = this.size + 1;
while (k > 1) {
@ -50,22 +46,19 @@ public class MinPriorityQueue {
// returns boolean value whether the heap is empty or not
public boolean isEmpty() {
if (0 == this.size)
return true;
if (0 == this.size) return true;
return false;
}
// returns boolean value whether the heap is full or not
public boolean isFull() {
if (this.size == this.capacity)
return true;
if (this.size == this.capacity) return true;
return false;
}
// prints the heap
public void print() {
for (int i = 1; i <= this.capacity; i++)
System.out.print(this.heap[i] + " ");
for (int i = 1; i <= this.capacity; i++) System.out.print(this.heap[i] + " ");
System.out.println();
}
@ -73,8 +66,7 @@ public class MinPriorityQueue {
// delete function to the number of times of the size of the heap
// it returns reverse sort because it is a min priority queue
public void heapSort() {
for (int i = 1; i < this.capacity; i++)
this.delete();
for (int i = 1; i < this.capacity; i++) this.delete();
}
// this function reorders the heap after every delete function

View File

@ -16,7 +16,8 @@ public class CircleLinkedList<E> {
// this will point to dummy node;
private Node<E> head = null;
//constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
// constructer for class.. here we will make a dummy node for circly linked list implementation
// with reduced error catching as our list will never be empty;
public CircleLinkedList() {
// creation of the dummy node
head = new Node<E>(null, head);
@ -28,7 +29,8 @@ public class CircleLinkedList<E> {
return size;
}
// 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.
// 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.
public void append(E value) {
if (value == null) {
// we do not want to add null elements to the list.
@ -44,20 +46,20 @@ public class CircleLinkedList<E> {
// catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
//we need to keep track of the element before the element we want to remove we can see why bellow.
// we need to keep track of the element before the element we want to remove we can see why
// bellow.
Node<E> before = head;
for (int i = 1; i <= pos; i++) {
before = before.next;
}
Node<E> destroy = before.next;
E saved = destroy.value;
// assigning the next reference to the the element following the element we want to remove... the last element will be assigned to the head.
// assigning the next reference to the the element following the element we want to remove...
// the last element will be assigned to the head.
before.next = before.next.next;
// scrubbing
destroy = null;
size--;
return saved;
}
}

View File

@ -4,7 +4,6 @@ import java.util.Objects;
public class CursorLinkedList<T> {
private static class Node<T> {
T element;
@ -20,9 +19,7 @@ public class CursorLinkedList<T> {
private int head;
private final Node<T>[] cursorSpace;
private int count;
private final static int CURSOR_SPACE_SIZE = 100;
private static final int CURSOR_SPACE_SIZE = 100;
{
// init at loading time
@ -33,7 +30,6 @@ public class CursorLinkedList<T> {
cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0;
}
public CursorLinkedList() {
os = 0;
count = 0;
@ -44,7 +40,6 @@ public class CursorLinkedList<T> {
if (head != -1) {
int start = head;
while (start != -1) {
@ -53,17 +48,14 @@ public class CursorLinkedList<T> {
start = cursorSpace[start].next;
}
}
}
/**
* @return the logical index of the element within the list , not the actual
* index of the [cursorSpace] array
* @return the logical index of the element within the list , not the actual index of the
* [cursorSpace] array
*/
public int indexOf(T element) {
Objects.requireNonNull(element);
Node<T> iterator = cursorSpace[head];
for (int i = 0; i < count; i++) {
@ -73,18 +65,14 @@ public class CursorLinkedList<T> {
iterator = cursorSpace[iterator.next];
}
return -1;
}
/**
* @param position , the logical index of the element , not the actual one
* within the [cursorSpace] array .
* this method should be used to get the index give by indexOf() method.
* @param position , the logical index of the element , not the actual one within the
* [cursorSpace] array . this method should be used to get the index give by indexOf() method.
* @return
*/
public T get(int position) {
if (position >= 0 && position < count) {
@ -101,13 +89,11 @@ public class CursorLinkedList<T> {
start = cursorSpace[start].next;
counter++;
}
}
return null;
}
public void removeByIndex(int index) {
if (index >= 0 && index < count) {
@ -115,12 +101,10 @@ public class CursorLinkedList<T> {
T element = get(index);
remove(element);
}
}
public void remove(T element) {
Objects.requireNonNull(element);
// case element is in the head
@ -146,12 +130,9 @@ public class CursorLinkedList<T> {
prev_index = current_index;
current_index = cursorSpace[prev_index].next;
}
}
count--;
}
private void free(int index) {
@ -161,10 +142,8 @@ public class CursorLinkedList<T> {
cursorSpace[os].next = index;
cursorSpace[index].element = null;
cursorSpace[index].next = os_next;
}
public void append(T element) {
Objects.requireNonNull(element);
@ -183,16 +162,12 @@ public class CursorLinkedList<T> {
cursorSpace[iterator].next = availableIndex;
cursorSpace[availableIndex].next = -1;
count++;
}
/**
* @return the index of the next available node
*/
/** @return the index of the next available node */
private int alloc() {
// 1- get the index at which the os is pointing
int availableNodeIndex = cursorSpace[os].next;
@ -209,8 +184,5 @@ public class CursorLinkedList<T> {
cursorSpace[availableNodeIndex].next = -1;
return availableNodeIndex;
}
}

View File

@ -1,37 +1,25 @@
package DataStructures.Lists;
/**
* This class implements a DoublyLinkedList. This is done using the classes
* LinkedList and Link.
* <p>
* A linked list is similar to an array, it holds values. However,
* links in a linked list do not have indexes. With a linked list
* you do not need to predetermine it's size as it grows and shrinks
* as it is edited. This is an example of a double ended, doubly
* linked list. Each link references the next link and the previous
* one.
* This class implements a DoublyLinkedList. This is done using the classes LinkedList and Link.
*
* <p>A linked list is similar to an array, it holds values. However, links in a linked list do not
* have indexes. With a linked list you do not need to predetermine it's size as it grows and
* shrinks as it is edited. This is an example of a double ended, doubly linked list. Each link
* references the next link and the previous one.
*
* @author Unknown
*/
public class DoublyLinkedList {
/**
* Head refers to the front of the list
*/
/** Head refers to the front of the list */
private Link head;
/**
* Tail refers to the back of the list
*/
/** Tail refers to the back of the list */
private Link tail;
/**
* Size refers to the number of elements present in the list
*/
/** Size refers to the number of elements present in the list */
private int size;
/**
* Default Constructor
*/
/** Default Constructor */
public DoublyLinkedList() {
head = null;
tail = null;
@ -61,8 +49,7 @@ public class DoublyLinkedList {
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)
else head.previous = newLink; // newLink <-- currenthead(head)
newLink.next = head; // newLink <--> currenthead(head)
head = newLink; // newLink(head) <--> oldhead
++size;
@ -92,7 +79,6 @@ public class DoublyLinkedList {
*
* @param x Element to be inserted
* @param index Index(from start) at which the element x to be inserted
*
*/
public void insertElementByIndex(int x, int index) {
if (index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
@ -115,7 +101,6 @@ public class DoublyLinkedList {
}
}
++size;
}
/**
@ -130,7 +115,8 @@ public class DoublyLinkedList {
if (head == null) {
tail = null;
} else {
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
head.previous =
null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
}
--size;
return temp;
@ -171,12 +157,8 @@ public class DoublyLinkedList {
}
}
if (current == head)
deleteHead();
else if (current == tail)
deleteTail();
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
@ -195,12 +177,8 @@ public class DoublyLinkedList {
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);
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
@ -240,10 +218,7 @@ public class DoublyLinkedList {
}
}
/**
* Clears List
*
*/
/** Clears List */
public void clearList() {
head = null;
tail = null;
@ -259,9 +234,7 @@ public class DoublyLinkedList {
return (head == null);
}
/**
* Prints contents of the list
*/
/** Prints contents of the list */
public void display() { // Prints contents of the list
Link current = head;
while (current != null) {
@ -273,23 +246,16 @@ public class DoublyLinkedList {
}
/**
* This class is used to implement the nodes of the
* linked list.
* This class is used to implement the nodes of the linked list.
*
* @author Unknown
*/
class Link {
/**
* Value of node
*/
/** Value of node */
public int value;
/**
* This points to the link in front of the new link
*/
/** This points to the link in front of the new link */
public Link next;
/**
* This points to the link behind the new link
*/
/** This points to the link behind the new link */
public Link previous;
/**
@ -301,9 +267,7 @@ class Link {
this.value = value;
}
/**
* Displays the node
*/
/** Displays the node */
public void displayLink() {
System.out.print(value + " ");
}

View File

@ -3,10 +3,7 @@ package DataStructures.Lists;
import java.util.ArrayList;
import java.util.List;
/**
* @author https://github.com/shellhub
*/
/** @author https://github.com/shellhub */
public class MergeSortedArrayList {
public static void main(String[] args) {
List<Integer> listA = new ArrayList<>();
@ -56,5 +53,4 @@ public class MergeSortedArrayList {
listC.add(listB.get(pb++));
}
}
}

View File

@ -4,9 +4,7 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author Arun Pandey (https://github.com/pandeyarun709)
*/
/** @author Arun Pandey (https://github.com/pandeyarun709) */
public class Merge_K_SortedLinkedlist {
/**

View File

@ -10,8 +10,7 @@ public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
for (int i = 1; i <= 10; ++i) {
assert list.search(i);
}
assert !list.search(-1)
&& !list.search(100);
assert !list.search(-1) && !list.search(100);
}
/**

View File

@ -1,30 +1,22 @@
package DataStructures.Lists;
/**
* This class implements a SinglyLinked List. This is done
* using SinglyLinkedList class and a LinkForLinkedList Class.
* <p>
* A linked list is similar to an array, it hold values.
* However, links in a linked list do not have indexes. With
* a linked list you do not need to predetermine it's size as
* it grows and shrinks as it is edited. This is an example of
* a singly linked list. Elements can only be added/removed
* at the head/front of the list.
* This class implements a SinglyLinked List. This is done using SinglyLinkedList class and a
* LinkForLinkedList Class.
*
* <p>A linked list is similar to an array, it hold values. However, links in a linked list do not
* have indexes. With a linked list you do not need to predetermine it's size as it grows and
* shrinks as it is edited. This is an example of a singly linked list. Elements can only be
* added/removed at the head/front of the list.
*/
public class SinglyLinkedList {
/**
* Head refer to the front of the list
*/
/** Head refer to the front of the list */
private Node head;
/**
* Size of SinglyLinkedList
*/
/** Size of SinglyLinkedList */
private int size;
/**
* Init SinglyLinkedList
*/
/** Init SinglyLinkedList */
public SinglyLinkedList() {
head = null;
size = 0;
@ -68,11 +60,13 @@ public class SinglyLinkedList {
public void insertNth(int data, int position) {
checkBounds(position, 0, size);
Node newNode = new Node(data);
if (head == null) { /* the list is empty */
if (head == null) {
/* the list is empty */
head = newNode;
size++;
return;
} else if (position == 0) { /* insert at the head of the list */
} else if (position == 0) {
/* insert at the head of the list */
newNode.next = head;
head = newNode;
size++;
@ -87,24 +81,17 @@ public class SinglyLinkedList {
size++;
}
/**
* Deletes a node at the head
*/
/** Deletes a node at the head */
public void deleteHead() {
deleteNth(0);
}
/**
* Deletes an element at the tail
*/
/** Deletes an element at the tail */
public void delete() {
deleteNth(size - 1);
}
/**
* Deletes an element at Nth position
*/
/** Deletes an element at Nth position */
public void deleteNth(int position) {
checkBounds(position, 0, size - 1);
if (position == 0) {
@ -138,9 +125,7 @@ public class SinglyLinkedList {
}
}
/**
* Clear all nodes in the list
*/
/** Clear all nodes in the list */
public void clear() {
Node cur = head;
while (cur != null) {
@ -226,7 +211,6 @@ public class SinglyLinkedList {
return cur.value;
}
@Override
public String toString() {
if (size == 0) {
@ -241,15 +225,11 @@ public class SinglyLinkedList {
return builder.replace(builder.length() - 2, builder.length(), "").toString();
}
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] arg) {
SinglyLinkedList list = new SinglyLinkedList();
assert list.isEmpty();
assert list.size() == 0
&& list.count() == 0;
assert list.size() == 0 && list.count() == 0;
assert list.toString().equals("");
/* Test insert function */
@ -261,15 +241,10 @@ public class SinglyLinkedList {
assert list.toString().equals("10->7->5->3->1");
/* Test search function */
assert list.search(10)
&& list.search(5)
&& list.search(1)
&& !list.search(100);
assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
/* Test get function */
assert list.getNth(0) == 10
&& list.getNth(2) == 5
&& list.getNth(4) == 1;
assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
/* Test delete function */
list.deleteHead();
@ -277,8 +252,7 @@ public class SinglyLinkedList {
list.delete();
assert list.toString().equals("7->3");
assert list.size == 2
&& list.size() == list.count();
assert list.size == 2 && list.size() == list.count();
list.clear();
assert list.isEmpty();
@ -293,24 +267,17 @@ public class SinglyLinkedList {
}
/**
* This class is the nodes of the SinglyLinked List.
* They consist of a value and a pointer to the node
* after them.
* This class is the nodes of the SinglyLinked List. They consist of a value and a pointer to the
* node after them.
*/
class Node {
/**
* The value of the node
*/
/** The value of the node */
int value;
/**
* Point to the next node
*/
/** Point to the next node */
Node next;
Node() {
}
Node() {}
/**
* Constructor
@ -323,6 +290,7 @@ class Node {
/**
* Constructor
*
* @param value Value to be put in the node
* @param next Reference to the next node
*/

View File

@ -4,18 +4,14 @@ import java.util.ArrayList;
/**
* This class implements a GenericArrayListQueue.
* <p>
* A GenericArrayListQueue data structure functions the same as any specific-typed queue.
* The GenericArrayListQueue holds elemets of types to-be-specified at runtime.
* The elements that are added first are the first to be removed (FIFO)
* New elements are added to the back/rear of the queue.
*
* <p>A GenericArrayListQueue data structure functions the same as any specific-typed queue. The
* GenericArrayListQueue holds elemets of types to-be-specified at runtime. The elements that are
* added first are the first to be removed (FIFO) New elements are added to the back/rear of the
* queue.
*/
public class GenericArrayListQueue<T> {
/**
* The generic ArrayList for the queue
* T is the generic element
*/
/** The generic ArrayList for the queue T is the generic element */
ArrayList<T> _queue = new ArrayList<T>();
/**
@ -34,7 +30,9 @@ public class GenericArrayListQueue<T> {
*/
public T peek() {
T result = null;
if(this.hasElements()) { result = _queue.get(0); }
if (this.hasElements()) {
result = _queue.get(0);
}
return result;
}
@ -55,7 +53,9 @@ public class GenericArrayListQueue<T> {
*/
public T poll() {
T result = null;
if(this.hasElements()) { result = _queue.remove(0); }
if (this.hasElements()) {
result = _queue.remove(0);
}
return result;
}

View File

@ -21,24 +21,16 @@ public class LinkedQueue {
}
}
/**
* Front of Queue
*/
/** Front of Queue */
private Node front;
/**
* Rear of Queue
*/
/** Rear of Queue */
private Node rear;
/**
* Size of Queue
*/
/** Size of Queue */
private int size;
/**
* Init LinkedQueue
*/
/** Init LinkedQueue */
public LinkedQueue() {
front = rear = new Node();
}
@ -121,9 +113,7 @@ public class LinkedQueue {
return size;
}
/**
* Clear all nodes in queue
*/
/** Clear all nodes in queue */
public void clear() {
while (!isEmpty()) {
dequeue();

View File

@ -2,25 +2,18 @@ package DataStructures.Queues;
/**
* This class implements a PriorityQueue.
* <p>
* 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.
*
* <p>A priority queue adds elements into positions based on their priority. So the most important
* elements are placed at the front/on the top. In this example I give numbers that are bigger, a
* higher priority. Queues in theory have no fixed size but when using an array implementation it
* does.
*/
class PriorityQueue {
/**
* The max size of the queue
*/
/** The max size of the queue */
private int maxSize;
/**
* The array for the queue
*/
/** The array for the queue */
private int[] queueArray;
/**
* How many items are in the queue
*/
/** How many items are in the queue */
private int nItems;
/**
@ -119,7 +112,8 @@ public class PriorityQueues {
// [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]
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
}

View File

@ -2,42 +2,26 @@ package DataStructures.Queues;
/**
* This implements Queues by using the class Queue.
* <p>
* 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.
*
* <p>A queue data structure functions the same as a real world queue. The elements that are added
* first are the first to be removed. New elements are added to the back/rear of the queue.
*/
class Queue {
/**
* Default initial capacity.
*/
/** Default initial capacity. */
private static final int DEFAULT_CAPACITY = 10;
/**
* Max size of the queue
*/
/** Max size of the queue */
private int maxSize;
/**
* The array representing the queue
*/
/** The array representing the queue */
private int[] queueArray;
/**
* Front of the queue
*/
/** Front of the queue */
private int front;
/**
* Rear of the queue
*/
/** Rear of the queue */
private int rear;
/**
* How many items are in the queue
*/
/** How many items are in the queue */
private int nItems;
/**
* init with DEFAULT_CAPACITY
*/
/** init with DEFAULT_CAPACITY */
public Queue() {
this(DEFAULT_CAPACITY);
}
@ -62,8 +46,7 @@ class Queue {
* @return True if the element was added successfully
*/
public boolean insert(int x) {
if (isFull())
return false;
if (isFull()) return false;
// If the back of the queue is the end of the array wrap around to the front
rear = (rear + 1) % maxSize;
queueArray[rear] = x;

View File

@ -3,14 +3,12 @@ package DataStructures.Stacks;
import java.util.Stack;
/**
* The nested brackets problem is a problem that determines if a sequence of
* brackets are properly nested. A sequence of brackets s is considered properly
* nested if any of the following conditions are true: - s is empty - s has the
* form (U) or [U] or {U} where U is a properly nested string - s has the form
* VW where V and W are properly nested strings For example, the string
* "()()[()]" is properly nested but "[(()]" is not. The function called
* is_balanced takes as input a string S which is a sequence of brackets and
* returns true if S is nested and false otherwise.
* The nested brackets problem is a problem that determines if a sequence of brackets are properly
* nested. A sequence of brackets s is considered properly nested if any of the following conditions
* are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s
* has the form VW where V and W are properly nested strings For example, the string "()()[()]" is
* properly nested but "[(()]" is not. The function called is_balanced takes as input a string S
* which is a sequence of brackets and returns true if S is nested and false otherwise.
*
* @author akshay sharma
* @author <a href="https://github.com/khalil2535">khalil2535<a>
@ -23,8 +21,8 @@ class BalancedBrackets {
*
* @param leftBracket left bracket
* @param rightBracket right bracket
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired,
* otherwise {@code false}
* @return {@code true} if {@code leftBracket} and {@code rightBracket} is paired, otherwise
* {@code false}
*/
public static boolean isPaired(char leftBracket, char rightBracket) {
char[][] pairedBrackets = {
@ -73,7 +71,6 @@ class BalancedBrackets {
return bracketsStack.isEmpty();
}
public static void main(String[] args) {
assert isBalanced("[()]{}{[()()]()}");
assert !isBalanced("[(])");

View File

@ -25,9 +25,7 @@ public class DecimalToAnyUsingStack {
String.format("Invalid input -> number:%d,radius:%d", number, radix));
}
char[] tables = {
'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
Stack<Character> bits = new Stack<>();
do {

View File

@ -1,17 +1,12 @@
package DataStructures.Stacks;
/**
* Implementation of a stack using nodes.
* Unlimited size, no arraylist.
* Implementation of a stack using nodes. Unlimited size, no arraylist.
*
* @author Kyler Smith, 2017
*/
public class NodeStack<Item> {
/**
* Entry point for the program.
*/
/** Entry point for the program. */
public static void main(String[] args) {
NodeStack<Integer> Stack = new NodeStack<Integer>();
@ -35,6 +30,7 @@ public class NodeStack<Item> {
/**
* 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
@ -42,17 +38,14 @@ public class NodeStack<Item> {
* @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() {
}
/** Constructors for the NodeStack. */
public NodeStack() {}
private NodeStack(Item item) {
this.data = item;
@ -127,13 +120,7 @@ public class NodeStack<Item> {
/**
* Print the contents of the stack in the following format.
*
* x <- head (next out)
* y
* z <- tail (first in)
* .
* .
* .
*
* <p>x <- head (next out) y z <- tail (first in) . . .
*/
public void print() {
for (NodeStack<?> n = NodeStack.head; n != null; n = n.previous) {

View File

@ -2,18 +2,15 @@ package DataStructures.Stacks;
/**
* This class implements a Stack using a regular array.
* <p>
* 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.
*
* <p>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.
*/
public class StackArray {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
// Declare a stack of maximum size 4
StackArray myStackArray = new StackArray(4);
@ -35,29 +32,19 @@ public class StackArray {
assert myStackArray.size() == 3;
}
/**
* Default initial capacity.
*/
/** Default initial capacity. */
private static final int DEFAULT_CAPACITY = 10;
/**
* The max size of the Stack
*/
/** The max size of the Stack */
private int maxSize;
/**
* The array representation of the Stack
*/
/** The array representation of the Stack */
private int[] stackArray;
/**
* The top of the stack
*/
/** The top of the stack */
private int top;
/**
* init Stack with DEFAULT_CAPACITY
*/
/** init Stack with DEFAULT_CAPACITY */
public StackArray() {
this(DEFAULT_CAPACITY);
}
@ -152,11 +139,9 @@ public class StackArray {
/**
* Deletes everything in the Stack
* <p>
* Doesn't delete elements in the array
* but if you call push method after calling
* makeEmpty it will overwrite previous
* values
*
* <p>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

View File

@ -5,18 +5,16 @@ import java.util.EmptyStackException;
/**
* This class implements a Stack using an ArrayList.
* <p>
* 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.
* <p>
* This is an ArrayList Implementation of a stack, where size is not
* a problem we can extend the stack as much as we want.
*
* <p>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.
*
* <p>This is an ArrayList Implementation of a stack, where size is not a problem we can extend the
* stack as much as we want.
*/
public class StackArrayList {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
StackArrayList stack = new StackArrayList();
assert stack.isEmpty();
@ -41,24 +39,18 @@ public class StackArrayList {
} catch (EmptyStackException e) {
assert true; /* this should happen */
}
}
/**
* ArrayList representation of the stack
*/
/** ArrayList representation of the stack */
private ArrayList<Integer> stack;
/**
* Constructor
*/
/** Constructor */
public StackArrayList() {
stack = new ArrayList<>();
}
/**
* Adds value to the end of list which
* is the top for stack
* Adds value to the end of list which is the top for stack
*
* @param value value to be added
*/

View File

@ -2,9 +2,7 @@ package DataStructures.Stacks;
import java.util.NoSuchElementException;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
// An implementation of a Stack using a Linked List
@ -44,25 +42,18 @@ class Node {
/**
* A class which implements a stack using a linked list
* <p>
* Contains all the stack methods : push, pop, printStack, isEmpty
**/
*
* <p>Contains all the stack methods : push, pop, printStack, isEmpty
*/
class LinkedListStack {
/**
* Top of stack
*/
/** Top of stack */
Node head;
/**
* Size of stack
*/
/** Size of stack */
private int size;
/**
* Init properties
*/
/** Init properties */
public LinkedListStack() {
head = null;
size = 0;

View File

@ -17,14 +17,12 @@ public class AVLTree {
}
public boolean insert(int key) {
if (root == null)
root = new Node(key, null);
if (root == null) root = new Node(key, null);
else {
Node n = root;
Node parent;
while (true) {
if (n.key == key)
return false;
if (n.key == key) return false;
parent = n;
@ -71,8 +69,7 @@ public class AVLTree {
}
public void delete(int delKey) {
if (root == null)
return;
if (root == null) return;
Node node = root;
Node child = root;
@ -90,16 +87,12 @@ public class AVLTree {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
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 (height(n.right.right) >= height(n.right.left)) n = rotateLeft(n);
else n = rotateRightThenLeft(n);
}
if (n.parent != null) {
@ -116,8 +109,7 @@ public class AVLTree {
a.right = b.left;
if (a.right != null)
a.right.parent = a;
if (a.right != null) a.right.parent = a;
b.left = a;
a.parent = b;
@ -142,8 +134,7 @@ public class AVLTree {
a.left = b.right;
if (a.left != null)
a.left.parent = a;
if (a.left != null) a.left.parent = a;
b.right = a;
a.parent = b;
@ -172,8 +163,7 @@ public class AVLTree {
}
private int height(Node n) {
if (n == null)
return -1;
if (n == null) return -1;
return n.height;
}
@ -204,17 +194,14 @@ public class AVLTree {
public boolean search(int key) {
Node result = searchHelper(this.root, key);
if(result != null)
return true ;
if (result != null) return true;
return false;
}
private Node searchHelper(Node root, int key)
{
private Node searchHelper(Node root, int key) {
// root is null or key is present at root
if (root==null || root.key==key)
return root;
if (root == null || root.key == key) return root;
// key is greater than root's key
if (root.key > key)
@ -229,8 +216,7 @@ public class AVLTree {
AVLTree tree = new AVLTree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
for (int i = 1; i < 10; i++) tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();

View File

@ -1,29 +1,23 @@
package DataStructures.Trees;
/**
* This entire class is used to build a Binary Tree data structure.
* There is the Node Class and the Tree Class, both explained below.
* This entire class is used to build a Binary Tree data structure. There is the Node Class and the
* Tree Class, both explained below.
*/
/**
* 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.
* 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
*
*/
public class BinaryTree {
/**
* 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.
* 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 */
@ -48,13 +42,10 @@ public class BinaryTree {
}
}
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
/** Constructor */
public BinaryTree() {
root = null;
}
@ -69,12 +60,10 @@ public class BinaryTree {
Node current = root;
while (current != null) {
if (key < current.data) {
if (current.left == null)
return current; //The key isn't exist, returns the parent
if (current.left == null) return current; // The key isn't exist, returns the parent
current = current.left;
} else if (key > current.data) {
if (current.right == null)
return current;
if (current.right == null) return current;
current = current.right;
} else { // If you find the value return it
return current;
@ -90,8 +79,7 @@ public class BinaryTree {
*/
public void put(int value) {
Node newNode = new Node(value);
if (root == null)
root = newNode;
if (root == null) root = newNode;
else {
// This will return the soon to be parent of the value you're inserting
Node parent = find(value);
@ -120,19 +108,15 @@ public class BinaryTree {
Node temp = find(value);
// If the value doesn't exist
if (temp.data != value)
return false;
if (temp.data != value) return false;
// No children
if (temp.right == null && temp.left == null) {
if (temp == root)
root = 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;
else if (temp.parent.data < temp.data) temp.parent.right = null;
else temp.parent.left = null;
return true;
}
@ -169,10 +153,8 @@ public class BinaryTree {
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;
if (temp.parent.data < temp.data) temp.parent.right = successor;
else temp.parent.left = successor;
return true;
}
}
@ -188,10 +170,8 @@ public class BinaryTree {
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;
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
@ -204,25 +184,22 @@ public class BinaryTree {
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;
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
* 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;
if (n.right == null) return n;
Node current = n.right;
Node parent = n.right;
while (current != null) {

View File

@ -5,14 +5,12 @@ import java.util.LinkedList;
import java.util.Scanner;
/**
* 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.
* <p>
* 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.
* 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.
*
* <p>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 class GenericTree {
private class Node {
@ -48,9 +46,7 @@ public class GenericTree {
return node;
}
/**
* Function to display the generic tree
*/
/** Function to display the generic tree */
public void display() { // Helper function
display_1(root);
}
@ -95,8 +91,7 @@ public class GenericTree {
}
private int max(Node roott, int maxi) {
if (maxi < roott.data)
maxi = roott.data;
if (maxi < roott.data) maxi = roott.data;
for (int i = 0; i < roott.child.size(); i++) {
maxi = max(roott.child.get(i), maxi);
}
@ -117,8 +112,7 @@ public class GenericTree {
int h = 0;
for (int i = 0; i < node.child.size(); i++) {
int k = height(node.child.get(i));
if (k > h)
h = k;
if (k > h) h = k;
}
return h + 1;
}
@ -134,16 +128,13 @@ public class GenericTree {
}
private boolean find(Node node, int info) {
if (node.data == info)
return true;
if (node.data == info) return true;
for (int i = 0; i < node.child.size(); i++) {
if (find(node.child.get(i), info))
return true;
if (find(node.child.get(i), info)) return true;
}
return false;
}
/**
* Function to calculate depth of generic tree
*
@ -158,14 +149,11 @@ public class GenericTree {
System.out.println(node.data);
return;
}
for (int i = 0; i < node.child.size(); i++)
depth(node.child.get(i), dep - 1);
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
*/
/** Function to print generic tree in pre-order */
public void preordercall() {
preorder(root);
System.out.println(".");
@ -173,27 +161,21 @@ public class GenericTree {
private void preorder(Node node) {
System.out.print(node.data + " ");
for (int i = 0; i < node.child.size(); i++)
preorder(node.child.get(i));
for (int i = 0; i < node.child.size(); i++) preorder(node.child.get(i));
}
/**
* Function to print generic tree in post-order
*/
/** 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));
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
*/
/** Function to print generic tree in level-order */
public void levelorder() {
LinkedList<Node> q = new LinkedList<>();
q.addLast(root);
@ -209,9 +191,7 @@ public class GenericTree {
System.out.println(".");
}
/**
* Function to remove all leaves of generic tree
*/
/** Function to remove all leaves of generic tree */
public void removeleavescall() {
removeleaves(root);
}
@ -223,12 +203,10 @@ public class GenericTree {
arr.add(i);
// node.child.remove(i);
// i--;
} else
removeleaves(node.child.get(i));
} else removeleaves(node.child.get(i));
}
for (int i = arr.size() - 1; i >= 0; i--) {
node.child.remove(arr.get(i) + 0);
}
}
}

View File

@ -23,30 +23,24 @@ public class LevelOrderTraversal {
void printLevelOrder() {
int h = height(root);
int i;
for (i = 1; i <= h; i++)
printGivenLevel(root, i);
for (i = 1; i <= h; i++) printGivenLevel(root, i);
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node root) {
if (root == null)
return 0;
if (root == null) return 0;
else {
/**
* Return the height of larger subtree
*/
/** Return the height of larger subtree */
return Math.max(height(root.left), height(root.right)) + 1;
}
}
/* Print nodes at the given level */
void printGivenLevel(Node root, int level) {
if (root == null)
return;
if (level == 1)
System.out.print(root.data + " ");
if (root == null) return;
if (level == 1) System.out.print(root.data + " ");
else if (level > 1) {
printGivenLevel(root.left, level - 1);
printGivenLevel(root.right, level - 1);

View File

@ -1,8 +1,7 @@
package DataStructures.Trees;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Queue;
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {

View File

@ -72,10 +72,8 @@ class Tree {
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd + 1));
if (n.left != null) Q.add(new QItem(n.left, hd - 1));
if (n.right != null) Q.add(new QItem(n.right, hd + 1));
}
}
}

View File

@ -2,9 +2,7 @@ package DataStructures.Trees;
import java.util.Scanner;
/**
* @author jack870131
*/
/** @author jack870131 */
public class RedBlackBST {
private final int R = 0;
@ -28,7 +26,8 @@ public class RedBlackBST {
return;
}
printTree(node.left);
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
System.out.print(
((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
@ -36,7 +35,8 @@ public class RedBlackBST {
if (node == nil) {
return;
}
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
System.out.print(
((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.left);
printTree(node.right);
}
@ -187,8 +187,7 @@ public class RedBlackBST {
root = with;
} else if (target == target.p.left) {
target.p.left = with;
} else
target.p.right = with;
} else target.p.right = with;
with.p = target.p;
}
@ -200,8 +199,7 @@ public class RedBlackBST {
}
boolean delete(Node z) {
if ((z = findNode(z, root)) == null)
return false;
if ((z = findNode(z, root)) == null) return false;
Node x;
Node y = z;
int yorigcolor = y.color;
@ -216,8 +214,7 @@ public class RedBlackBST {
y = treeMinimum(z.right);
yorigcolor = y.color;
x = y.right;
if (y.p == z)
x.p = y;
if (y.p == z) x.p = y;
else {
transplant(y, y.right);
y.right = z.right;
@ -228,8 +225,7 @@ public class RedBlackBST {
y.left.p = y;
y.color = z.color;
}
if (yorigcolor == B)
deleteFixup(x);
if (yorigcolor == B) deleteFixup(x);
return true;
}

View File

@ -2,10 +2,7 @@ package DataStructures.Trees;
import java.util.LinkedList;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
// Driver Program
public class TreeTraversal {
@ -38,12 +35,10 @@ public class TreeTraversal {
}
/**
* The Node class which initializes a Node of a tree
* Consists of all 4 traversal methods: printInOrder, printPostOrder printPreOrder & printLevelOrder
* printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT
* printLevelOrder: Prints by level (starting at root), from left to right.
* The Node class which initializes a Node of a tree Consists of all 4 traversal methods:
* printInOrder, printPostOrder printPreOrder & printLevelOrder printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT printPostOrder: LEFT -> RIGHT -> ROOT printLevelOrder:
* Prints by level (starting at root), from left to right.
*/
class Node {
Node left, right;
@ -99,10 +94,7 @@ class Node {
System.out.print(data + " ");
}
/**
* O(n) time algorithm.
* Uses O(n) space to store nodes in a queue to aid in traversal.
*/
/** O(n) time algorithm. Uses O(n) space to store nodes in a queue to aid in traversal. */
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);

View File

@ -5,7 +5,6 @@ package DataStructures.Trees;
*
* @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
*/
import java.util.Scanner;
public class TrieImp {
@ -73,9 +72,7 @@ public class TrieImp {
System.out.println(print);
}
/**
* Regex to check if word contains only a-z character
*/
/** Regex to check if word contains only a-z character */
public static boolean isValid(String word) {
return word.matches("^[a-z]+$");
}
@ -93,30 +90,22 @@ public class TrieImp {
switch (t) {
case 1:
word = scan.next();
if (isValid(word))
obj.insert(word);
else
sop("Invalid string: allowed only a-z");
if (isValid(word)) obj.insert(word);
else sop("Invalid string: allowed only a-z");
break;
case 2:
word = scan.next();
boolean resS = false;
if (isValid(word))
resS = obj.search(word);
else
sop("Invalid string: allowed only a-z");
if (resS)
sop("word found");
else
sop("word not found");
if (isValid(word)) resS = obj.search(word);
else sop("Invalid string: allowed only a-z");
if (resS) sop("word found");
else sop("word not found");
break;
case 3:
word = scan.next();
boolean resD = false;
if (isValid(word))
resD = obj.delete(word);
else
sop("Invalid string: allowed only a-z");
if (isValid(word)) resD = obj.delete(word);
else sop("Invalid string: allowed only a-z");
if (resD) {
sop("word got deleted successfully");
} else {
@ -137,5 +126,4 @@ public class TrieImp {
}
}
}
}

View File

@ -20,25 +20,21 @@ public class ValidBSTOrNot {
/* returns true if given search tree is binary
search tree (efficient version) */
boolean isBST(Node root) {
return isBSTUtil(root, Integer.MIN_VALUE,
Integer.MAX_VALUE);
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
boolean isBSTUtil(Node node, int min, int max) {
/* an empty tree is BST */
if (node == null)
return true;
if (node == null) return true;
/* false if this node violates the min/max constraints */
if (node.data < min || node.data > max)
return false;
if (node.data < min || node.data > max) return false;
/* otherwise check the subtrees recursively
tightening the min/max constraints */
// Allow only distinct values
return (isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max));
return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
}
}

View File

@ -27,33 +27,32 @@ int n=10;
public class BoardPath {
public static long startTime;
public static long endTime;
public static void startAlgo() {
startTime = System.currentTimeMillis();
}
public static long endAlgo() {
endTime = System.currentTimeMillis();
return endTime - startTime;
}
public static int bpR(int start, int end) {
if (start == end) {
return 1;
}
else if(start>end)
return 0;
} else if (start > end) return 0;
int count = 0;
for (int dice = 1; dice <= 6; dice++) {
count += bpR(start + dice, end);
}
return count;
}
public static int bpRS(int curr, int end, int strg[]) {
if (curr == end) {
return 1;
}
else if(curr>end)
return 0;
if(strg[curr]!=0)
return strg[curr];
} else if (curr > end) return 0;
if (strg[curr] != 0) return strg[curr];
int count = 0;
for (int dice = 1; dice <= 6; dice++) {
count += bpRS(curr + dice, end, strg);
@ -61,6 +60,7 @@ public class BoardPath {
strg[curr] = count;
return count;
}
public static int bpIS(int curr, int end, int[] strg) {
strg[end] = 1;
for (int i = end - 1; i >= 0; i--) {
@ -72,6 +72,4 @@ public class BoardPath {
}
return strg[0];
}
}

View File

@ -1,8 +1,6 @@
package DynamicProgramming;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
public class CoinChange {
// Driver Program
@ -11,18 +9,23 @@ public class CoinChange {
int amount = 12;
int[] coins = {2, 4, 5};
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount));
System.out.println(
"Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
System.out.println(
"Minimum number of coins required for amount :"
+ amount
+ " is: "
+ minimumCoins(coins, amount));
}
/**
* This method finds the number of combinations of getting change for a given amount and change coins
* This method finds the number of combinations of getting change for a given amount and change
* coins
*
* @param coins The list of coins
* @param amount The amount for which we need to find the change
* Finds the number of combinations of change
**/
* @param amount The amount for which we need to find the change Finds the number of combinations
* of change
*/
public static int change(int[] coins, int amount) {
int[] combinations = new int[amount + 1];
@ -43,9 +46,9 @@ public class CoinChange {
* This method finds the minimum number of coins needed for a given amount.
*
* @param coins The list of coins
* @param amount The amount for which we need to find the minimum number of coins.
* Finds the the minimum number of coins that make a given value.
**/
* @param amount The amount for which we need to find the minimum number of coins. Finds the the
* minimum number of coins that make a given value.
*/
public static int minimumCoins(int[] coins, int amount) {
// minimumCoins[i] will store the minimum coins needed for amount i
int[] minimumCoins = new int[amount + 1];

View File

@ -1,23 +1,24 @@
package DynamicProgramming;
/**
* A DynamicProgramming based solution for Edit Distance problem In Java
* Description of Edit Distance with an Example:
* A DynamicProgramming based solution for Edit Distance problem In Java Description of Edit
* Distance with an Example:
*
* <p>Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one
* another, by counting the minimum number of operations required to transform one string into the
* other. The distance operations are the removal, insertion, or substitution of a character in the
* string.
*
* <p>
* Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
* by counting the minimum number of operations required to transform one string into the other. The
* distance operations are the removal, insertion, or substitution of a character in the string.
* <p>
* <p>
* The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
* <p>
* kitten → sitten (substitution of "s" for "k")
* sitten → sittin (substitution of "i" for "e")
*
* <p>The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the
* former into the latter is:
*
* <p>kitten → sitten (substitution of "s" for "k") sitten → sittin (substitution of "i" for "e")
* sittin → sitting (insertion of "g" at the end).
*
* @author SUBHAM SANGHAI
**/
*/
import java.util.Scanner;
public class EditDistance {
@ -63,7 +64,6 @@ public class EditDistance {
return dp[len1][len2];
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s1, s2;
@ -73,7 +73,8 @@ public class EditDistance {
s2 = input.nextLine();
// ans stores the final Edit Distance between the two strings
int ans = minDistance(s1, s2);
System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
System.out.println(
"The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
input.close();
}
}

View File

@ -1,8 +1,6 @@
package DynamicProgramming;
/**
* DynamicProgramming solution for the Egg Dropping Puzzle
*/
/** DynamicProgramming solution for the Egg Dropping Puzzle */
public class EggDropping {
// min trials with n eggs and m floors
@ -19,8 +17,7 @@ public class EggDropping {
// j trials for only 1 egg
for (int j = 1; j <= m; j++)
eggFloor[1][j] = j;
for (int j = 1; j <= m; j++) eggFloor[1][j] = j;
// Using bottom-up approach in DP
@ -31,8 +28,7 @@ public class EggDropping {
result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
// choose min of all values for particular x
if (result < eggFloor[i][j])
eggFloor[i][j] = result;
if (result < eggFloor[i][j]) eggFloor[i][j] = result;
}
}
}

View File

@ -4,15 +4,11 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
/** @author Varun Upadhyay (https://github.com/varunu28) */
public class Fibonacci {
private static Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
// Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
@ -28,9 +24,9 @@ public class Fibonacci {
/**
* 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
**/
* @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);
@ -50,9 +46,9 @@ public class Fibonacci {
/**
* 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
**/
* @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<Integer, Integer> fib = new HashMap<>();
@ -70,21 +66,16 @@ public class Fibonacci {
return fib.get(n);
}
/**
* 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
* <p>
* This is optimized version of Fibonacci Program. Without using Hashmap and recursion.
* It saves both memory and time.
* Space Complexity will be O(1)
* Time Complexity will be O(n)
* <p>
* Whereas , the above functions will take O(n) Space.
* @param n The input n for which we have to determine the fibonacci number Outputs the nth
* fibonacci number
* <p>This is optimized version of Fibonacci Program. Without using Hashmap and recursion. It
* saves both memory and time. Space Complexity will be O(1) Time Complexity will be O(n)
* <p>Whereas , the above functions will take O(n) Space.
* @author Shoaib Rayeen (https://github.com/shoaibrayeen)
**/
*/
public static int fibOptimized(int n) {
if (n == 0) {
return 0;

View File

@ -5,7 +5,7 @@ import java.util.Queue;
import java.util.Vector;
public class FordFulkerson {
final static int INF = 987654321;
static final int INF = 987654321;
// edges
static int V;
static int[][] capacity, flow;
@ -33,8 +33,7 @@ public class FordFulkerson {
int totalFlow = 0;
while (true) {
Vector<Integer> parent = new Vector<>(V);
for (int i = 0; i < V; i++)
parent.add(-1);
for (int i = 0; i < V; i++) parent.add(-1);
Queue<Integer> q = new LinkedList<>();
parent.set(source, source);
q.add(source);
@ -47,8 +46,7 @@ public class FordFulkerson {
parent.set(there, here);
}
}
if (parent.get(sink) == -1)
break;
if (parent.get(sink) == -1) break;
int amount = INF;
String printer = "path : ";

View File

@ -3,13 +3,11 @@ package DynamicProgramming;
import java.util.Scanner;
/**
* Program to implement Kadanes Algorithm to
* calculate maximum contiguous subarray sum of an array
* Program to implement Kadanes Algorithm to calculate maximum contiguous subarray sum of an array
* Time Complexity: O(n)
*
* @author Nishita Aggarwal
*/
public class KadaneAlgorithm {
/**
@ -51,5 +49,4 @@ public class KadaneAlgorithm {
System.out.println(maxContSum);
sc.close();
}
}

View File

@ -1,33 +1,26 @@
package DynamicProgramming;
/**
* A DynamicProgramming based solution for 0-1 Knapsack problem
*/
/** A DynamicProgramming based solution for 0-1 Knapsack problem */
public class Knapsack {
private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException {
if(wt == null || val == null)
throw new IllegalArgumentException();
if (wt == null || val == null) throw new IllegalArgumentException();
int i, w;
int rv[][] = new int[n + 1][W + 1]; // rv means return value
// Build table rv[][] in bottom up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
rv[i][w] = 0;
if (i == 0 || w == 0) rv[i][w] = 0;
else if (wt[i - 1] <= w)
rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]);
else
rv[i][w] = rv[i - 1][w];
else rv[i][w] = rv[i - 1][w];
}
}
return rv[n][W];
}
// Driver program to test above function
public static void main(String args[]) {
int val[] = new int[] {50, 100, 130};

View File

@ -1,10 +1,10 @@
package DynamicProgramming;
/**
* @author Kshitij VERMA (github.com/kv19971)
* LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
* @author Kshitij VERMA (github.com/kv19971) LEVENSHTEIN DISTANCE dyamic programming implementation
* to show the difference between two strings
* (https://en.wikipedia.org/wiki/Levenshtein_distance)
*/
public class LevenshteinDistance {
private static int minimum(int a, int b, int c) {
if (a < b && a < c) {
@ -34,14 +34,12 @@ public class LevenshteinDistance {
} else {
cost = 1;
}
distance_mat[i][j] = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + cost;
distance_mat[i][j] =
minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1])
+ cost;
}
}
return distance_mat[len_a - 1][len_b - 1];
}
public static void main(String[] args) {
@ -50,7 +48,5 @@ public class LevenshteinDistance {
System.out.print("Levenshtein distance between " + a + " and " + b + " is: ");
System.out.println(calculate_distance(a, b));
}
}

View File

@ -5,12 +5,10 @@ class LongestCommonSubsequence {
public static String getLCS(String str1, String str2) {
// At least one string is null
if (str1 == null || str2 == null)
return null;
if (str1 == null || str2 == null) return null;
// At least one string is empty
if (str1.length() == 0 || str2.length() == 0)
return "";
if (str1.length() == 0 || str2.length() == 0) return "";
String[] arr1 = str1.split("");
String[] arr2 = str2.split("");
@ -18,16 +16,15 @@ class LongestCommonSubsequence {
// lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2
int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1];
for (int i = 0; i < arr1.length + 1; i++)
lcsMatrix[i][0] = 0;
for (int j = 1; j < arr2.length + 1; j++)
lcsMatrix[0][j] = 0;
for (int i = 0; i < arr1.length + 1; i++) lcsMatrix[i][0] = 0;
for (int j = 1; j < arr2.length + 1; j++) lcsMatrix[0][j] = 0;
for (int i = 1; i < arr1.length + 1; i++) {
for (int j = 1; j < arr2.length + 1; j++) {
if (arr1[i - 1].equals(arr2[j - 1])) {
lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1;
} else {
lcsMatrix[i][j] = lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1];
lcsMatrix[i][j] =
lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1];
}
}
}
@ -36,8 +33,7 @@ class LongestCommonSubsequence {
public static String lcsString(String str1, String str2, int[][] lcsMatrix) {
StringBuilder lcs = new StringBuilder();
int i = str1.length(),
j = str2.length();
int i = str1.length(), j = str2.length();
while (i > 0 && j > 0) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
lcs.append(str1.charAt(i - 1));

View File

@ -2,9 +2,7 @@ package DynamicProgramming;
import java.util.Scanner;
/**
* @author Afrizal Fikri (https://github.com/icalF)
*/
/** @author Afrizal Fikri (https://github.com/icalF) */
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
@ -23,10 +21,8 @@ public class LongestIncreasingSubsequence {
private static int upperBound(int[] ar, int l, int r, int key) {
while (l < r - 1) {
int m = (l + r) >>> 1;
if (ar[m] >= key)
r = m;
else
l = m;
if (ar[m] >= key) r = m;
else l = m;
}
return r;
@ -34,8 +30,7 @@ public class LongestIncreasingSubsequence {
private static int LIS(int[] array) {
int N = array.length;
if (N == 0)
return 0;
if (N == 0) return 0;
int[] tail = new int[N];
@ -46,18 +41,17 @@ public class LongestIncreasingSubsequence {
for (int i = 1; i < N; i++) {
// new smallest value
if (array[i] < tail[0])
tail[0] = array[i];
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];
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];
// 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;

View File

@ -1,5 +1,5 @@
package test;
import java.lang.*;
import java.io.*;
import java.util.*;
@ -34,12 +34,17 @@ public class LongestPalindromicSubsequence {
// if the last chars match, then remove it from both strings and recur
if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1));
String bestSubResult =
recursiveLPS(
original.substring(0, original.length() - 1),
reverse.substring(0, reverse.length() - 1));
bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
} else {
//otherwise (1) ignore the last character of reverse, and recur on original and updated reverse again
//(2) ignore the last character of original and recur on the updated original and reverse again
// otherwise (1) ignore the last character of reverse, and recur on original and updated
// reverse again
// (2) ignore the last character of original and recur on the updated original and reverse
// again
// then select the best result from these two subproblems.
String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1));

View File

@ -3,13 +3,12 @@ package DynamicProgramming;
import java.util.Scanner;
/**
* Given a string containing just the characters '(' and ')', find the length of
* the longest valid (well-formed) parentheses substring.
* Given a string containing just the characters '(' and ')', find the length of the longest valid
* (well-formed) parentheses substring.
*
* @author Libin Yang (https://github.com/yanglbme)
* @since 2018/10/5
*/
public class LongestValidParentheses {
public static int getLongestValidParentheses(String s) {
@ -40,7 +39,6 @@ public class LongestValidParentheses {
}
return max;
}
public static void main(String[] args) {
@ -53,7 +51,6 @@ public class LongestValidParentheses {
}
int len = getLongestValidParentheses(str);
System.out.println(len);
}
sc.close();

View File

@ -108,7 +108,6 @@ public class MatrixChainMultiplication {
System.out.print(string);
return (scan.nextLine().split(" "));
}
}
class Matrix {

View File

@ -15,11 +15,10 @@ Subset1 = {7, 46} ; sum of Subset1 = 53
Subset2 = {36, 40} ; sum of Subset2 = 76
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class MinimumSumPartition
{
import java.util.*;
public class MinimumSumPartition {
public static int subSet(int[] arr) {
int n = arr.length;
int sum = getSum(arr);
@ -81,9 +80,7 @@ public class MinimumSumPartition
return min;
}
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
assert subSet(new int[] {1, 6, 11, 5}) == 1;
assert subSet(new int[] {36, 7, 46, 40}) == 23;

View File

@ -1,9 +1,8 @@
package DynamicProgramming;
/**
* A DynamicProgramming solution for Rod cutting problem
* Returns the best obtainable price for a rod of
* length n and price[] as prices of different pieces
* A DynamicProgramming solution for Rod cutting problem Returns the best obtainable price for a rod
* of length n and price[] as prices of different pieces
*/
public class RodCutting {
@ -13,8 +12,7 @@ public class RodCutting {
for (int i = 1; i <= n; i++) {
int max_val = Integer.MIN_VALUE;
for (int j = 0; j < i; j++)
max_val = Math.max(max_val, price[j] + val[i - j - 1]);
for (int j = 0; j < i; j++) max_val = Math.max(max_val, price[j] + val[i - j - 1]);
val[i] = max_val;
}
@ -27,7 +25,6 @@ public class RodCutting {
int[] arr = new int[] {2, 5, 13, 19, 20};
int size = arr.length;
int result = cutRod(arr, size);
System.out.println("Maximum Obtainable Value is " +
result);
System.out.println("Maximum Obtainable Value is " + result);
}
}

View File

@ -2,9 +2,7 @@ package DynamicProgramming;
public class SubsetSum {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
int[] arr = new int[] {50, 4, 10, 15, 34};
assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */

View File

@ -4,9 +4,8 @@ import java.util.Arrays;
/**
* description:
* <p>
* absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
* </p>
*
* <p>absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
*/
public class AbsoluteMax {
public static void main(String[] args) {

View File

@ -4,9 +4,8 @@ import java.util.Arrays;
/**
* description:
* <p>
* absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
* </p>
*
* <p>absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
*/
public class AbsoluteMin {
public static void main(String[] args) {

View File

@ -23,5 +23,4 @@ public class AbsoluteValue {
public static int absVal(int value) {
return value < 0 ? -value : value;
}
}

View File

@ -1,13 +1,10 @@
package Maths;
/**
* <p>
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n,
* that is, all divisors of n other than n itself.
* For example, the proper divisors of 15 (that is, the positive divisors of 15 that are not equal to 15)
* are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 3 + 5).
* </p>
* Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors
* of n, that is, all divisors of n other than n itself. For example, the proper divisors of 15
* (that is, the positive divisors of 15 that are not equal to 15) are 1, 3 and 5, so the aliquot
* sum of 15 is 9 i.e. (1 + 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
*/
public class AliquotSum {
public static void main(String[] args) {

View File

@ -1,21 +1,18 @@
package Maths;
/**
* Amicable numbers are two different numbers so related
* that the sum of the proper divisors of each is equal to the other number.
* (A proper divisor of a number is a positive factor of that number other than the number itself.
* For example, the proper divisors of 6 are 1, 2, and 3.)
* A pair of amicable numbers constitutes an aliquot sequence of period 2.
* It is unknown if there are infinitely many pairs of amicable numbers.
* *
* <p>
* * link: https://en.wikipedia.org/wiki/Amicable_numbers
* * </p>
* <p>
* Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284
* 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it 220
* Amicable numbers are two different numbers so related that the sum of the proper divisors of each
* is equal to the other number. (A proper divisor of a number is a positive factor of that number
* other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) A pair of
* amicable numbers constitutes an aliquot sequence of period 2. It is unknown if there are
* infinitely many pairs of amicable numbers. *
*
* <p>* link: https://en.wikipedia.org/wiki/Amicable_numbers *
*
* <p>Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284
* 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it
* 220
*/
public class AmicableNumber {
public static void main(String[] args) {
@ -47,7 +44,15 @@ public class AmicableNumber {
}
}
}
res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n ");
res.insert(
0,
"Int Range of "
+ startValue
+ " till "
+ stopValue
+ " there are "
+ countofRes
+ " Amicable_numbers.These are \n ");
System.out.println(res.toString());
}
@ -59,7 +64,8 @@ public class AmicableNumber {
*/
static boolean isAmicableNumber(int numberOne, int numberTwo) {
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
&& numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
}
/**
@ -78,10 +84,4 @@ public class AmicableNumber {
return recursiveCalcOfDividerSum(number, div);
}
}
}

View File

@ -1,8 +1,6 @@
package Maths;
/**
* Find the area of various geometric shapes
*/
/** Find the area of various geometric shapes */
public class Area {
public static void main(String[] args) {

View File

@ -1,9 +1,9 @@
package Maths;
/**
* An Armstrong number is equal to the sum of the cubes of its digits.
* For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
* An Armstrong number is often called Narcissistic number.
* An Armstrong number is equal to the sum of the cubes of its digits. For example, 370 is an
* Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An Armstrong number is often called
* Narcissistic number.
*/
public class Armstrong {
@ -34,7 +34,8 @@ public class Armstrong {
while (number > 0) {
int remainder = number % 10;
int power = 1;
for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) ;
for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
;
sum = sum + power;
number /= 10;
}

View File

@ -1,10 +1,9 @@
package Maths;
/**
* Calculate average of a list of numbers
*/
/** Calculate average of a list of numbers */
public class Average {
private static final double SMALL_VALUE = 0.00001f;
public static void main(String[] args) {
assert Math.abs(average(new double[] {3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE;
assert Math.abs(average(new double[] {5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE;
@ -30,8 +29,7 @@ public class Average {
/**
* find average value of int array
*
* @param array the array contains element and the sum does not
* excess long value limit
* @param array the array contains element and the sum does not excess long value limit
* @return average value
*/
public static int average(int[] array) {

View File

@ -1,8 +1,6 @@
package Maths;
/**
* @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a>
*/
/** @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a> */
public class Combinations {
public static void main(String[] args) {
assert combinations(1, 1) == 1;

View File

@ -21,7 +21,8 @@ public class Factorial {
throw new IllegalArgumentException("number is negative");
}
long factorial = 1;
for (int i = 1; i <= n; factorial *= i, ++i) ;
for (int i = 1; i <= n; factorial *= i, ++i)
;
return factorial;
}
}

View File

@ -1,8 +1,6 @@
package Maths;
/**
* Fibonacci: 0 1 1 2 3 5 8 13 21 ...
*/
/** Fibonacci: 0 1 1 2 3 5 8 13 21 ... */
public class FibonacciNumber {
public static void main(String[] args) {
assert isFibonacciNumber(1);
@ -24,8 +22,8 @@ public class FibonacciNumber {
}
/**
* Check if a number is fibonacci number
* This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square
* Check if a number is fibonacci number This is true if and only if at least one of 5x^2+4 or
* 5x^2-4 is a perfect square
*
* @param number the number
* @return <tt>true</tt> if {@code number} is fibonacci number, otherwise <tt>false</tt>

View File

@ -5,9 +5,7 @@ import java.util.Random;
public class FindMax {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
Random random = new Random();

View File

@ -5,9 +5,7 @@ import java.util.Random;
public class FindMin {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
Random random = new Random();

View File

@ -5,9 +5,7 @@ import java.util.Random;
public class FindMinRecursion {
/**
* Driver Code
*/
/** Driver Code */
public static void main(String[] args) {
Random rand = new Random();

View File

@ -1,8 +1,8 @@
package Maths;
/**
* This is Euclid's algorithm which is used to find the greatest common denominator
* Overide function name gcd
* This is Euclid's algorithm which is used to find the greatest common denominator Overide function
* name gcd
*
* @author Oskar Enmalm 3/10/17
*/

View File

@ -1,8 +1,6 @@
package Maths;
/**
* @author https://github.com/shellhub/
*/
/** @author https://github.com/shellhub/ */
public class GCDRecursion {
public static void main(String[] args) {
System.out.println(gcd(20, 15)); /* output: 5 */

View File

@ -1,8 +1,6 @@
package Maths;
/**
* https://en.wikipedia.org/wiki/Lucas_number
*/
/** https://en.wikipedia.org/wiki/Lucas_number */
public class LucasSeries {
public static void main(String[] args) {
assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
@ -12,11 +10,11 @@ public class LucasSeries {
assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
}
/**
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using recursion
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
* recursion
*
* @param n nth
* @return nth number of lucas series
@ -26,7 +24,8 @@ public class LucasSeries {
}
/**
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using iteration
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
* iteration
*
* @param n nth
* @return nth number of lucas series

Some files were not shown because too many files have changed in this diff Show More