Merge branch 'master' into master

This commit is contained in:
Abhijay Kumar
2019-05-29 17:07:24 +05:30
committed by GitHub
166 changed files with 4053 additions and 31229 deletions

39
.gitignore vendored
View File

@ -1,5 +1,36 @@
/bin/
.idea/*
.classpath*
.project*
/gradle/wrapper/gradle-wrapper.properties
##----------Android----------
# build
*.apk
*.ap_
*.dex
*.class
bin/
gen/
build/
out/
# gradle
.gradle/
gradle-app.setting
!gradle-wrapper.jar
build/
local.properties
##----------idea----------
*.iml
.idea/
*.ipr
*.iws
# Android Studio Navigation editor temp files
.navigation/
##----------Other----------
# osx
*~
.DS_Store
gradle.properties
.vscode

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,108 +0,0 @@
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
public class HEncoder {
public HashMap<Character, String> encoder = new HashMap<>(); // in order to encode
public HashMap<String, Character> decoder = new HashMap<>(); // in order to decode
private static class Node {
Character ch;
Integer freq;
Node left;
Node right;
public static final Nodecomparator Ctor = new Nodecomparator();
public static class Nodecomparator implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2) {
return o2.freq - o1.freq;
}
}
}
public HEncoder(String feeder) {
// 1. freq map
HashMap<Character, Integer> freqmap = new HashMap<>();
for (int i = 0; i < feeder.length(); ++i) {
char ch = feeder.charAt(i);
if (freqmap.containsKey(ch)) {
freqmap.put(ch, freqmap.get(ch) + 1);
} else {
freqmap.put(ch, 1);
}
}
// 2. prepare the heap from keyset
genericheap<Node> heap = new genericheap<Node>(Node.Ctor);
ArrayList<Character> k = new ArrayList<>(freqmap.keySet());
for (Character c : k) {
Node n = new Node();
n.ch = c;
n.left = null;
n.right = null;
n.freq = freqmap.get(c);
heap.add(n);
}
// 3.Prepare tree, remove two , merge, add it back
Node fn = new Node();
while (heap.size() != 1) {
Node n1 = heap.removeHP();
Node n2 = heap.removeHP();
fn = new Node();
fn.freq = n1.freq + n2.freq;
fn.left = n1;
fn.right = n2;
heap.add(fn);
}
// 4. traverse
traverse(heap.removeHP(), "");
}
private void traverse(Node node, String osf) {
if (node.left == null && node.right == null) {
encoder.put(node.ch, osf);
decoder.put(osf, node.ch);
return;
}
traverse(node.left, osf + "0");
traverse(node.right, osf + "1");
}
// compression work done here
public String compress(String str) {
String rv = "";
for (int i = 0; i < str.length(); ++i) {
rv += encoder.get(str.charAt(i));
}
return rv;
}
//in order to decompress
public String decompress(String str) {
String s = "";
String code = "";
for (int i = 0; i < str.length(); ++i) {
code += str.charAt(i);
if (decoder.containsKey(code)) {
s += decoder.get(code);
code = "";
}
}
return s;
}
}

View File

@ -1,11 +0,0 @@
public class compressclient {
public static void main(String[] args) {
HEncoder h= new HEncoder("aaaabbbcccccccccccdddd");
System.out.println(h.compress("aabccd"));
System.out.println(h.decompress("101011000111"));
}
}

View File

@ -1,93 +0,0 @@
import java.util.ArrayList;
import java.util.Comparator;
public class genericheap<T> { // create a generic heap class <T> , where T can be of any type.
private ArrayList<T> data = new ArrayList<>();
private Comparator<T> ctor;
public genericheap(Comparator<T> ctor) { // constructor to initialize the generic comparator
this.ctor=ctor;
}
public int size() { // returns the size of the arraylist data
return data.size();
}
public boolean isEmpty() { // checks whether the list is empty or not :: return true or false for the same
return data.isEmpty();
}
public void display() { //displays the list
System.out.println(this.data);
}
public void add(T integer) { // in this function we have added the <t> type object into the arraylist and called upheapify
data.add(integer);
upheapify(data.size() - 1);
}
private void upheapify(int ci) {
if (ci == 0) {
return;
}
int pi = (ci - 1) / 2;
if (isLarger(ci,pi) == true) {
swap(ci, pi);
upheapify(pi);
}
}
private boolean isLarger(int i, int j) {
T ith = data.get(i);
T jth = data.get(j);
if(ctor.compare(ith,jth)>0)
{
return true;
}
else
{
return false;
}
}
private void swap(int ci, int pi) { // swap function written like this because of the generic property
T ith = data.get(ci);
T jth=data.get(pi);
data.set(ci, jth);
data.set(pi, ith);
}
public T getHP() {
return data.get(0);
}
public T removeHP() {
swap(0, data.size() - 1);
T rv=data.remove(data.size()-1);
downheapify(0);
return rv;
}
private void downheapify(int pi) {
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
int max = pi;
if (lci < data.size() && isLarger(lci, max) == true) {
max = lci;
}
if (rci < data.size() && isLarger(rci, max) == true) {
max = rci;
}
if (max != pi) {
swap(pi, max);
downheapify(max);
}
}
}

View File

@ -1,3 +1,5 @@
package Conversions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
@ -10,24 +12,24 @@ import java.util.Scanner;
*
* @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;
// Driver
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String n;
int b1=0,b2=0;
int b1, b2;
while (true) {
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!");
@ -37,7 +39,7 @@ 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!");
@ -63,8 +65,8 @@ public class AnyBaseToAnyBase {
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++)
HashSet<Character> digitsList = new HashSet<>();
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.
@ -78,6 +80,7 @@ public class AnyBaseToAnyBase {
/**
* Method to convert any integer from base b1 to base b2. Works by converting from b1 to decimal,
* then decimal to b2.
*
* @param n The integer to be converted.
* @param b1 Beginning base.
* @param b2 End base.
@ -89,9 +92,9 @@ public class AnyBaseToAnyBase {
// and the string that will be returned.
int decimalValue = 0, charB2;
char charB1;
String output="";
String output = "";
// Go through every character of n
for (int i=0; i<n.length(); i++) {
for (int i = 0; i < n.length(); i++) {
// 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
@ -121,7 +124,7 @@ public class AnyBaseToAnyBase {
// 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;
output = (char) ((decimalValue % b2) + 55) + output;
// Divide by the new base again
decimalValue /= b2;
}

View File

@ -1,3 +1,5 @@
package Conversions;
import java.io.BufferedReader;
import java.io.InputStreamReader;

View File

@ -1,4 +1,4 @@
package Java.Conversions;
package Conversions;
import java.util.Scanner;
//given a source number , source base, destination base, this code can give you the destination number.

View File

@ -1,33 +1,30 @@
package Conversions;
import java.util.Scanner;
/**
* This class converts a Binary number to a Decimal number
*
* @author Unknown
*
*/
class BinaryToDecimal
{
class BinaryToDecimal {
/**
* Main Method
*
* @param args Command line arguments
*/
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,k,d,s=0,c=0;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n, k, d, s = 0, c = 0;
System.out.print("Binary number: ");
n=sc.nextInt();
k=n;
while(k!=0)
{
d=k%10;
s+=d*(int)Math.pow(2,c++);
k/=10;
n = sc.nextInt();
k = n;
while (k != 0) {
d = k % 10;
s += d * (int) Math.pow(2, c++);
k /= 10;
}
System.out.println("Decimal equivalent:"+s);
System.out.println("Decimal equivalent:" + s);
sc.close();
}
}

View File

@ -1,9 +1,11 @@
package Conversions;
import java.util.*;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*
*/
public class BinaryToHexadecimal {
@ -14,29 +16,25 @@ public class BinaryToHexadecimal {
* @param binary The binary number
* @return The hexadecimal number
*/
static String binToHex(int binary)
{
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
HashMap<Integer,String> hm=new HashMap<>();
HashMap<Integer, String> hm = new HashMap<>();
//String to store hexadecimal code
String hex="";
String hex = "";
int i;
for(i=0 ; i<10 ; i++)
{
for (i = 0; i < 10; i++) {
hm.put(i, String.valueOf(i));
}
for(i=10 ; i<16 ; i++) hm.put(i,String.valueOf((char)('A'+i-10)));
for (i = 10; i < 16; i++) hm.put(i, String.valueOf((char) ('A' + i - 10)));
int currbit;
while(binary != 0)
{
while (binary != 0) {
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
for(i=0 ; i<4 ; i++)
{
for (i = 0; i < 4; i++) {
currbit = binary % 10;
binary = binary / 10;
code4 += currbit * Math.pow(2, i);
}
hex= hm.get(code4) + hex;
hex = hm.get(code4) + hex;
}
return hex;
}

View File

@ -1,10 +1,11 @@
package Conversions;
import java.util.Scanner;
/**
* Converts any Binary number to an Octal Number
*
* @author Zachary Jones
*
*/
public class BinaryToOctal {
@ -29,9 +30,8 @@ public class BinaryToOctal {
* @return The octal number
*/
public static int convertBinaryToOctal(int b) {
int o = 0, r=0, j =1 ;
while(b!=0)
{
int o = 0, r = 0, j = 1;
while (b != 0) {
r = b % 10;
o = o + r * j;
j = j * 2;

View File

@ -1,3 +1,5 @@
package Conversions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

View File

@ -1,10 +1,11 @@
package Conversions;
import java.util.Scanner;
/**
* This class converts a Decimal number to a Binary number
*
* @author Unknown
*
*/
class DecimalToBinary {

View File

@ -1,3 +1,4 @@
package Conversions;
class DecimalToHexaDecimal {
private static final int sizeOfIntInHalfBytes = 8;

View File

@ -1,33 +1,31 @@
package Conversions;
import java.util.Scanner;
/**
* This class converts Decimal numbers to Octal Numbers
*
* @author Unknown
*
*/
class Decimal_Octal
{
public class DecimalToOctal {
/**
* Main Method
*
* @param args Command line Arguments
*/
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n,k,d,s=0,c=0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k, d, s = 0, c = 0;
System.out.print("Decimal number: ");
n=sc.nextInt();
k=n;
while(k!=0)
{
d=k%8;
s+=d*(int)Math.pow(10,c++);
k/=8;
n = sc.nextInt();
k = n;
while (k != 0) {
d = k % 8;
s += d * (int) Math.pow(10, c++);
k /= 8;
}
System.out.println("Octal equivalent:"+s);
System.out.println("Octal equivalent:" + s);
sc.close();
}
}

View File

@ -1,73 +1,69 @@
/**
+ * Converts any Hexadecimal Number to Octal
+ *
+ * @author Tanmay Joshi
+ *
+ */
package Conversions;
import java.util.Scanner;
public class HexToOct
{
/**
* Converts any Hexadecimal Number to Octal
*
* @author Tanmay Joshi
*/
public class HexToOct {
/**
+ * This method converts a Hexadecimal number to
+ * a decimal number
+ *
+ * @param The Hexadecimal Number
+ * @return The Decimal number
+ */
public static int hex2decimal(String s)
{
* This method converts a Hexadecimal number to a decimal number
*
* @param s The Hexadecimal Number
* @return The Decimal number
*/
public static int hex2decimal(String s) {
String str = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
int n = str.indexOf(a);
val = 16*val + n;
val = 16 * val + n;
}
return val;
}
/**
+ * This method converts a Decimal number to
+ * a octal number
+ *
+ * @param The Decimal Number
+ * @return The Octal number
+ */
public static int decimal2octal(int q)
{
* This method converts a Decimal number to a octal number
*
* @param q The Decimal Number
* @return The Octal number
*/
public static int decimal2octal(int q) {
int now;
int i=1;
int octnum=0;
while(q>0)
{
now=q%8;
octnum=(now*(int)(Math.pow(10,i)))+octnum;
q/=8;
int i = 1;
int octnum = 0;
while (q > 0) {
now = q % 8;
octnum = (now * (int) (Math.pow(10, i))) + octnum;
q /= 8;
i++;
}
octnum/=10;
octnum /= 10;
return octnum;
}
// Main method that gets the hex input from user and converts it into octal.
public static void main(String args[])
{
/**
* Main method that gets the hex input from user and converts it into octal.
* @param args arguments
*/
public static void main(String args[]) {
String hexadecnum;
int decnum,octalnum;
int decnum, octalnum;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
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
// convert decimal to octal
octalnum=decimal2octal(decnum);
System.out.println("Number in octal: "+octalnum);
octalnum = decimal2octal(decnum);
System.out.println("Number in octal: " + octalnum);
}

View File

@ -1,3 +1,5 @@
package Conversions;
public class HexaDecimalToBinary {
private final int LONG_BITS = 8;

View File

@ -5,22 +5,20 @@ import java.util.Scanner;
public class HexaDecimalToDecimal {
// convert hexadecimal to decimal
public static int getHexaToDec(String hex){
String digits = "012345678910ABCDEFF";
public static int getHexaToDec(String hex) {
String digits = "0123456789ABCDEF";
hex = hex.toUpperCase();
int val = 0;
for (int i = 0; i < hex.length(); i++)
{
for (int i = 0; i < hex.length(); i++) {
int d = digits.indexOf(hex.charAt(i));
val = 16*val + d;
val = 16 * val + d;
}
return val;
}
// Main method gets the hexadecimal input from user and converts it into Decimal output.
public static void main(String args[])
{
public static void main(String args[]) {
String hexa_Input;
int dec_output;
Scanner scan = new Scanner(System.in);
@ -35,7 +33,7 @@ public class HexaDecimalToDecimal {
Pass the string to the getHexaToDec function
and it returns the decimal form in the variable dec_output.
*/
System.out.println("Number in Decimal: "+dec_output);
System.out.println("Number in Decimal: " + dec_output);
}

View File

@ -1,49 +0,0 @@
import java.util.Scanner;
/**
* Converts any Octal number to a Binary number
*
* @author Zachary Jones
*
*/
public class OctalToBinary {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int o = sc.nextInt();
System.out.println("Binary equivalent: " + convertOctalToBinary(o));
sc.close();
}
/**
* This method converts an octal number
* to a binary number.
*
* @param o The octal number
* @return The binary number
*/
public static int convertOctalToBinary(int o) {
Scanner scan;
int num;
void getVal() {
System.out.println("Octal to Binary");
scan = new Scanner(System.in);
// Entering the needed number
System.out.println("\nEnter the number : ");
num = Integer.parseInt(scan.nextLine(), 8);
}
void convert() {
String binary = Integer.toBinaryString(num);
System.out.println("Binary Value is : " + binary);
}
}
}

View File

@ -1,3 +1,5 @@
package Conversions;
import java.util.Scanner;
/**

View File

@ -1,42 +1,38 @@
/**
+ + * Converts any Octal Number to HexaDecimal
+ + *
+ + * @author Tanmay Joshi
+ + *
+ + *
**/
package Conversions;
import java.util.Scanner;
/**
* Converts any Octal Number to HexaDecimal
*
* @author Tanmay Joshi
*/
public class OctalToHexadecimal {
/**
+ + * This method converts a Octal number to
+ + * a decimal number
+ + *
+ + * @param The Octal Number
+ + * @return The Decimal number
+ + */
public static int OctToDec(String s)
{
int i =0;
for(int j =0;j<s.length();j++)
{
* This method converts a Octal number to a decimal number
*
* @param s The Octal Number
* @return The Decimal number
*/
public static int OctToDec(String s) {
int i = 0;
for (int j = 0; j < s.length(); j++) {
char num = s.charAt(j);
num-='0';
i*=8;
i+=num;
num -= '0';
i *= 8;
i += num;
}
return i;
}
}
/**
+ + * This method converts a Decimal number to
+ + * a Hexadecimal number
+ + *
+ + * @param The Decimal Number
+ + * @return The Hexadecimal number
+ + */
public static String DecimalToHex(int d) {
/**
* This method converts a Decimal number to a Hexadecimal number
*
* @param d The Decimal Number
* @return The Hexadecimal number
*/
public static String DecimalToHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0)
return "0";
@ -47,17 +43,22 @@ public static String DecimalToHex(int d) {
d = d / 16;
}
return hex;
}
}
//Driver Program
public static void main ( String args[]) {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Octal number: ");
String oct = input.next(); //Take octal number as input from user in a string
int decimal = OctToDec(oct); //Pass the octal number to function and get converted deciaml form
String hex = DecimalToHex(decimal); //Pass the decimla number to function and get converted Hex form of the number
System.out.println("The Hexadecimal equivalant is: "+hex);
// Take octal number as input from user in a string
String oct = input.next();
// Pass the octal number to function and get converted deciaml form
int decimal = OctToDec(oct);
// Pass the decimla number to function and get converted Hex form of the number
String hex = DecimalToHex(decimal);
System.out.println("The Hexadecimal equivalant is: " + hex);
}
}

View File

@ -1,8 +1,10 @@
package Conversions;
import java.util.*;
public class RomanToInteger {
private static Map<Character, Integer> map = new HashMap<>() {{
private static Map<Character, Integer> map = new HashMap<Character, Integer>() {{
put('I', 1);
put('V', 5);
put('X', 10);

View File

@ -1,4 +1,4 @@
package Bags;
package DataStructures.Bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -59,7 +59,7 @@ public class Bag<Element> implements Iterable<Element> {
*/
public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator();
while(iterator.hasNext()) {
while (iterator.hasNext()) {
if (iterator.next().equals(element)) {
return true;
}

View File

@ -1,3 +1,5 @@
package DataStructures.Buffers;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@ -9,7 +11,7 @@ public class CircularBuffer {
private AtomicInteger _readable_data = new AtomicInteger(0);
public CircularBuffer(int buffer_size) {
if(!IsPowerOfTwo(buffer_size)) {
if (!IsPowerOfTwo(buffer_size)) {
throw new IllegalArgumentException();
}
this._buffer_size = buffer_size;
@ -28,7 +30,7 @@ public class CircularBuffer {
Character result = null;
//if we have data to read
if(_readable_data.get() > 0) {
if (_readable_data.get() > 0) {
result = new Character(_buffer[getTrueIndex(_read_index)]);
_readable_data.decrementAndGet();
_read_index++;
@ -41,7 +43,7 @@ public class CircularBuffer {
boolean result = false;
//if we can write to the buffer
if(_readable_data.get() < _buffer_size) {
if (_readable_data.get() < _buffer_size) {
//write to buffer
_buffer[getTrueIndex(_write_index)] = c;
_readable_data.incrementAndGet();
@ -56,6 +58,7 @@ public class CircularBuffer {
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
Random _random = new Random();
CircularBuffer _buffer;
public TestWriteWorker(CircularBuffer cb) {
this._buffer = cb;
}
@ -65,10 +68,10 @@ public class CircularBuffer {
}
public void run() {
while(!Thread.interrupted()) {
if(!_buffer.writeToCharBuffer(getRandomChar())){
while (!Thread.interrupted()) {
if (!_buffer.writeToCharBuffer(getRandomChar())) {
Thread.yield();
try{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return;
@ -80,15 +83,17 @@ public class CircularBuffer {
private static class TestReadWorker implements Runnable {
CircularBuffer _buffer;
public TestReadWorker(CircularBuffer cb) {
this._buffer = cb;
}
@Override
public void run() {
System.out.println("Printing Buffer:");
while(!Thread.interrupted()) {
while (!Thread.interrupted()) {
Character c = _buffer.readOutChar();
if(c != null) {
if (c != null) {
System.out.print(c.charValue());
} else {
Thread.yield();

View File

@ -1,692 +0,0 @@
/*
* author: Christian Bender
* class: CSVFile
*
* This class implements a data structure for handling of
* CSV-files.
*
* Overview
*
* CSVFile(path : string, seperator : char)
* compiles the CSV-file in the inner data structure.
*
* CSVFile (file : File, seperator : char)
* CSVFile (seperator : char)
*
* compile (row : string, seperator : char) : string
* compiles row in its columns.
*
* isPunctuation (ch : char) : boolean
* check whether ch is a punctuation character.
*
* getElementString(row : int, column : int) : string
* returns the specified element.
*
* getElementDouble(row : int, column : int) : double
* returns the specified element as double.
*
* addRow(row : string) : void
* adds a row to the inner data structure.
* without writing into the CSV-file.
*
* set (row : int, column : int, item : string) : void
* replaces the specified item with a newer.
*
* commit() : void
* writes the added data into CSV-file.
*
* commit(path : String) : void
* commit(file : File ) : void
*
* findRow(key : string) : ArrayList<String>
* returns the searched row otherwise null.
*
* contains(key : string) : boolean
* returns true if a row contains 'key' otherwise false.
*
* getColumn(column : int) : ArrayList<String>
* returns the specified column as ArrayList.
*
* getColumn(key : string) : ArrayList<String>
*
* removeRow(key : string) : void
* purpose removes the specified row at the inner data structure.
*
* removeRow(column : int) : void
*
* updateFile() : void
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*
* updateFile(file : File) : void
*
* getNumberOfRows() : int
* returns the number of rows in CSV-File
* it counts only rows that in the table.
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;
public class CSVFile {
// the actual CSV-content
private ArrayList<ArrayList<String>> table;
// to tracking added rows.
private ArrayList<Integer> trackList;
// notice the seperator
private char seperator;
// notice the path of the CSV-File.
private String pathCSVFile;
/**
* Constructor
*
* @param path
* @param seperator
* @purpose loads the CSV-file and fills the inner table with the data
*/
public CSVFile(String path, char seperator) {
this(new File(path),seperator);
}
/**
*
* @param file
* same constructor different arguments.
*/
public CSVFile(File file, char seperator) {
table = new ArrayList<ArrayList<String>>();
trackList = new ArrayList<Integer>();
pathCSVFile = file.getPath();
this.seperator = seperator;
ArrayList<String> colums = new ArrayList<String>();
if (!file.canRead() || !file.isFile()) {
System.out.println("unable to open file");
System.exit(1);
}
try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))) {
br.lines().forEach(line -> table.add(compile(line, seperator)));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param separator
* @purpose Constructor for empty CSV-File.
*/
public CSVFile(char separator) {
table = new ArrayList<ArrayList<String>>();
trackList = new ArrayList<Integer>();
pathCSVFile = "";
this.seperator = separator;
}
/**
*
* @param row
* @param sep
* the seperator
* @return ArrayList<String> that contains each column of row.
* @purpose compiles row in its columns.
*
*/
public static ArrayList<String> compile(String row, char sep) {
ArrayList<String> columns = new ArrayList<String>();
int state = 0;
char ch = ' ';
String column = "";
int countQuotes = 0;
for (int i = 0; i < row.length(); i++) {
// fetch next character
ch = row.charAt(i);
switch (state) {
// state 0
case 0:
if (Character.isLetter(ch) || Character.isDigit(ch)) {
state = 1;
column += ch;
} else if (ch == '"') { // catch "
state = 2;
column += ch;
} else if (Character.isWhitespace(ch)) {
state = 0;
}
break;
// state 1
case 1:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| isPunctuation(ch) || Character.isWhitespace(ch))
&& (ch != sep)) {
state = 1;
column += ch;
} else if (ch == sep || ch == '\n') {
state = 0;
column = column.trim();
columns.add(column);
column = "";
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
break;
// state 2
case 2:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| Character.isWhitespace(ch) || isPunctuation(ch))
&& (ch != '"')) {
state = 2;
column += ch;
} else if (ch == '"') {
state = 3;
column += ch;
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
break;
// state 3
case 3:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| Character.isWhitespace(ch) || isPunctuation(ch))
&& (ch != '"') && (ch != sep)) {
state = 2;
column += ch;
} else if (ch == ',') {
state = 0;
column = column.trim();
columns.add(column);
column = "";
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
}
}
// for adding the remaining column
columns.add(column);
column = "";
return columns;
}
private static Pattern PATTERN_PUNCTUATION = Pattern.compile("\\p{Punct}");
/**
*
* @param ch
* @returns true if ch is punctuation character otherwise false.
*/
public static boolean isPunctuation(char ch) {
return PATTERN_PUNCTUATION.matcher("" + ch).matches();
}
/**
*
* @param row
* @param column
* @return the specific element as string
*/
public String getElementString(int row, int column) {
// check arguments
if (row < table.size() && column < table.get(0).size()) {
return table.get(row).get(column);
} else { // error case
throw new RuntimeException("getElementString: "
+ " arguments out of bound.");
}
}
/**
*
* @param row
* @param column
* @return the specific element as double
* @throws NumberFormatException
*/
public double getElementDouble(int row, int column)
throws NumberFormatException {
// check arguments
if (row < table.size() && column < table.get(0).size()) {
return Double.parseDouble(table.get(row).get(column));
} else { // error case
throw new RuntimeException("getElementString: "
+ " arguments out of bound.");
}
}
/**
*
* @param row
* @purpose adds a row to the inner data structure.
* without writing into the CSV-file.
*/
public void addRow(String row) {
table.add(compile(row, seperator));
// tracking the last item.
trackList.add(table.size() - 1);
}
/**
* @purpose: writes the added data into CSV-file.
*/
public void commit() {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row for the next one
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
* @param path
* @purpose: writes the added data into CSV-file (given path).
*/
public void commit(String path) {
String row = "";
pathCSVFile = path;
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param file
* @purpose: writes the added data into CSV-file (given path).
*/
public void commit(File file) {
String row = "";
pathCSVFile = file.getPath();
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
file, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param key
* @returns the searched row otherwise null.
*/
public ArrayList<String> findRow(String key) {
ArrayList<String> ans = null;
key = key.trim();
for (int i = 0; i < table.size(); i++) {
for (String item : table.get(i)) {
item = item.trim();
if (item.equals(key)) {
ans = table.get(i);
break;
}
}
}
return ans;
}
/**
*
* @param key
* @returns true if a row contains 'key' otherwise false.
*/
public boolean contains(String key) {
key = key.trim();
for (int i = 0; i < table.size(); i++) {
for (String item : table.get(i)) {
item = item.trim();
if (item.equals(key)) {
return true;
}
}
}
return false;
}
/**
*
* @param n of type integer
* @returns the specified column as ArrayList.
*/
public ArrayList<String> getColumn(int column) {
ArrayList<String> ans = new ArrayList<String>();
if (column < table.get(0).size()) {
for (int i = 0; i < table.size(); i++) {
ans.add(table.get(i).get(column));
}
} else { // error case
throw new RuntimeException("getColumn: column is too large");
}
return ans;
}
/**
*
* @param label of type string
* @returns the specified column at label.
*/
public ArrayList<String> getColumn(String label) {
ArrayList<String> ans = new ArrayList<String>();
int n = table.get(0).indexOf(label);
// check whether label exists.
if (n != -1) {
for (int i = 1; i < table.size(); i++) {
ans.add(table.get(i).get(n));
}
} else { // error case
throw new RuntimeException("getColumn: label " + label
+ " don't exists.");
}
return ans;
}
/**
*
* @param key of type string
* @purpose removes the specified row at the inner data structure.
*/
public void removeRow(String key) {
for (int i = 0; i < table.size(); i++) {
if (table.get(i) != null) {
for (String item : table.get(i)) {
if (item.equals(key)) {
table.set(i,null);
// updates the track list
if (trackList.indexOf(i) != -1) {
trackList.remove(i);
}
}
}
}
}
// removes all null-elements
table.removeAll(Collections.singleton(null));
}
/**
*
* @param n of type integer
* @purpose removes the specified row at the inner data structure.
*/
public void removeRow(int column) {
if (column < table.size()) {
table.set(column, null);
// removes all null-elements
table.removeAll(Collections.singleton(null));
// updates the track list
if (trackList.indexOf(column) != -1) {
trackList.remove(column);
}
} else {
throw new RuntimeException("removeRow: column is too large");
}
}
/**
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*/
public void updateFile() {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile)));
// writes the table rows into CSV-file.
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table.get(i).size(); j++) {
if (j != 0) {
row += ",";
row += table.get(i).get(j);
} else {
row += table.get(i).get(j);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row for the next one
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param file
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*/
public void updateFile(File file) {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
file)));
// writes the table rows into CSV-file.
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table.get(i).size(); j++) {
if (j != 0) {
row += ",";
row += table.get(i).get(j);
} else {
row += table.get(i).get(j);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @returns the number of rows in CSV-File
* it counts only rows that in the table.
*/
public int getNumberOfRows() {
return table.size();
}
/**
*
* @param row
* @param column
* @param item
* @purpose replaces the specified item with a newer.
*/
public void set(int row, int column, String item) {
if (row < table.size()) {
if (column < table.get(row).size()) {
table.get(row).set(column, item);
} else {
throw new RuntimeException("set: column is too large!");
}
} else {
throw new RuntimeException("set: row is too large!");
}
}
}

View File

@ -1,133 +0,0 @@
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
public class TestCSVFile {
@Test
public void testConstructor1() {
CSVFile testObj = new CSVFile("testData.csv",',');
assertEquals(testObj.getElementDouble(1, 1),65.78331, 0.001);
assertEquals(testObj.getElementString(1, 1),"65.78331");
assertEquals(testObj.getElementString(0, 1),"\"Height(Inches)\"");
assertEquals(testObj.getNumberOfRows(),25029);
}
@Test
public void testConstructor2() {
CSVFile testObj = new CSVFile(',');
testObj.addRow("1, 65.78331, 112.9925");
testObj.addRow("12, 67.62333, 114.143");
testObj.addRow("6, 68.69784, 123.3024");
// testObj.commit("testData2.csv");
// testObj.commit(new File("testData2.csv"));
}
@Test
public void testConstructor3() {
CSVFile testObj = new CSVFile(new File("testData.csv"),',');
assertEquals(testObj.getElementDouble(1, 1),65.78331, 0.001);
assertEquals(testObj.getElementString(1, 1),"65.78331");
assertEquals(testObj.getElementString(0, 1),"\"Height(Inches)\"");
}
@Test
public void testIsPunctuation() {
assertTrue(CSVFile.isPunctuation(':'));
}
@Test
public void testCompile() {
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertEquals(CSVFile.compile("2, 71.51521, 136.4873", ','),columns);
columns.clear();
// test successful
columns.add("\"Index\"");
columns.add("\"Height(Inches)\"");
columns.add("\"Weight(Pounds)\"");
assertEquals(CSVFile.compile("\"Index\", \"Height(Inches)\", "
+ "\"Weight(Pounds)\"", ','),columns);
}
@Test
public void testAddRowCommit() {
// CSVFile testObj = new CSVFile("testData.csv",',');
// testObj.addRow("1,1,1");
// testObj.addRow("1,2,3");
// testObj.commit();
// test successful
}
@Test
public void testFindRow() {
CSVFile testObj = new CSVFile("testData.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertEquals(testObj.findRow("71.51521"),columns);
}
@Test
public void testContains() {
CSVFile testObj = new CSVFile("testData.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertTrue(testObj.contains("71.51521"));
assertFalse(testObj.contains("9889678"));
}
@Test
public void testGetColumn() {
CSVFile testObj = new CSVFile("testData2.csv",',');
CSVFile testObj2 = new CSVFile("testData3.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("height");
columns.add("65.78331");
columns.add("67.62333");
assertEquals(testObj.getColumn(1),columns);
columns.clear();
columns.add("65.78331");
columns.add("67.62333");
assertEquals(testObj.getColumn("height"),columns);
columns.clear();
assertEquals(testObj2.getColumn("height"),columns);
}
@Test
public void testRemoving() {
CSVFile testObj = new CSVFile("testData4.csv",',');
//testObj.removeRow("68.69784");
// testObj.removeRow(0);
// testObj.updateFile(new File("testData4.csv"));
// test successful
}
@Test
public void testSet() {
// CSVFile testObj = new CSVFile("testData4.csv",',');
// testObj.set(6, 2, "80");
// testObj.updateFile();
// test succesfull
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
id, height, width
1, 65.78331, 112.9925
12, 67.62333, 114.143
1 id height width
2 1 65.78331 112.9925
3 12 67.62333 114.143

View File

@ -1 +0,0 @@
id, height, width
1 id height width

View File

@ -1,7 +0,0 @@
1,65.78331,112.9925
2,71.51521,136.4873
3,69.39874,153.0269
4,68.2166,142.3354
5,67.78781,144.2971
7,69.80204,141.4947
8,70.01472,80
1 1 65.78331 112.9925
2 2 71.51521 136.4873
3 3 69.39874 153.0269
4 4 68.2166 142.3354
5 5 67.78781 144.2971
6 7 69.80204 141.4947
7 8 70.01472 80

View File

@ -1,62 +0,0 @@
import java.util.*;
/**
* Implementation of a Breadth First Search
*
* @author Unknown
*
*/
public class BFS{
/**
* The BFS implemented in code to use.
*
* @param a Structure to perform the search on a graph, adjacency matrix etc.
* @param vertices The vertices to use
* @param source The Source
*/
public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Stack st = new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.peek();
b[pop]=(byte)1; //assigning processed status
st.pop(); //removing head of the queue
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
/**
* The main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
bfsImplement(a,vertices,source); //function call
in.close();
}
}

View File

@ -1,3 +1,5 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
@ -6,7 +8,6 @@ import java.util.Set;
* A class that counts the number of different connected components in a graph
*
* @author Lukas Keul, Florian Mercks
*
*/
class Graph<E extends Comparable<E>> {
@ -39,19 +40,15 @@ 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.
*
* @param startNode
* the starting Node from the edge
*
* @param endNode
* the ending Node from the edge
* @param startNode the starting Node from the edge
* @param endNode the ending Node from the edge
*/
public void addEdge(E startNode, E endNode) {
Node start = null, end = null;
for (Node node : nodeList) {
if (startNode.compareTo(node.name) == 0) {
start = node;
}
else if (endNode.compareTo(node.name) == 0) {
} else if (endNode.compareTo(node.name) == 0) {
end = node;
}
}
@ -74,7 +71,6 @@ class Graph<E extends Comparable<E>> {
* markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*
*/
public int countGraphs() {
int count = 0;
@ -94,14 +90,9 @@ class Graph<E extends Comparable<E>> {
/**
* Implementation of depth first search.
*
* @param n
* the actual visiting node
*
* @param visited
* A list of already visited nodes in the depth first search
*
* @param n the actual visiting node
* @param visited A list of already visited nodes in the depth first search
* @return returns a set of visited nodes
*
*/
public ArrayList<Node> depthFirstSearch(Node n, ArrayList<Node> visited) {
visited.add(n);

View File

@ -1,3 +1,5 @@
package DataStructures.Graphs;
import java.util.Scanner;
import java.util.ArrayList;
@ -5,10 +7,10 @@ import java.util.ArrayList;
class Cycle {
private int nodes, edges;
private int [][] adjacencyMatrix;
private boolean [] visited;
private int[][] adjacencyMatrix;
private boolean[] visited;
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
private boolean [] finalCycles;
private boolean[] finalCycles;
public Cycle() {
Scanner in = new Scanner(System.in);
@ -17,8 +19,8 @@ class Cycle {
System.out.print("Enter the no. of Edges: ");
edges = in.nextInt();
adjacencyMatrix = new int [nodes][nodes];
visited = new boolean [nodes];
adjacencyMatrix = new int[nodes][nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) {
visited[i] = false;
@ -26,7 +28,7 @@ class Cycle {
System.out.println("Enter the details of each edges <Start Node> <End Node>");
for(int i = 0; i < edges; i++) {
for (int i = 0; i < edges; i++) {
int start, end;
start = in.nextInt();
end = in.nextInt();
@ -50,7 +52,7 @@ class Cycle {
temp.add(curr);
visited[curr] = true;
for (int i = 0; i < nodes; i++) {
if(adjacencyMatrix[curr][i] == 1) {
if (adjacencyMatrix[curr][i] == 1) {
if (i == start) {
cycles.add(new ArrayList<Integer>(temp));
} else {
@ -61,7 +63,7 @@ class Cycle {
}
}
if(temp.size() > 0) {
if (temp.size() > 0) {
temp.remove(temp.size() - 1);
}
visited[curr] = false;

View File

@ -1,63 +0,0 @@
import java.util.*;
/**
* Implementation of a Depth First Search
*
* @author Unknown
*
*/
public class DFS{
/**
* Implementation in code of a DFS
*
* @param a structure to be DFS'ed
* @param vertices The vertices
* @param source The source
*/
public static void dfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Stack st=new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.pop();
b[pop]=(byte)1; //assigning processed status
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
/**
* The main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
dfsImplement(a,vertices,source); //function call
in.close();
}
}

View File

@ -1,78 +1,73 @@
import java.util.Scanner;
public class FloydWarshall
{
package DataStructures.Graphs;
import java.util.Arrays;
import java.util.Scanner;
public class FloydWarshall {
private int DistanceMatrix[][];
private int numberofvertices;//number of vertices in the graph
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices)
{
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
Arrays.fill(DistanceMatrix, 0);
this.numberofvertices = numberofvertices;
}
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++)
{
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
}
}
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++)
{
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination]
< DistanceMatrix[source][destination])//if the new distance calculated is less then the earlier shortest calculated distance it get replaced as new shortest distance
< DistanceMatrix[source][destination])
// 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];
}
}
}
}
for (int source = 1; source <= numberofvertices; source++)
System.out.print("\t" + source);
System.out.println();
for (int source = 1; source <= numberofvertices; source++)
{
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
for (int destination = 1; destination <= numberofvertices; destination++)
{
for (int destination = 1; destination <= numberofvertices; destination++) {
System.out.print(DistanceMatrix[source][destination] + "\t");
}
System.out.println();
}
}
public static void main(String... arg)
{
int Adjacency_Matrix[][];
int numberofvertices;
public static void main(String... arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
numberofvertices = scan.nextInt();
Adjacency_Matrix = new int[numberofvertices + 1][numberofvertices + 1];
int numberOfVertices = scan.nextInt();
int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
Adjacency_Matrix[source][destination] = scan.nextInt();
if (source == destination)
{
Adjacency_Matrix[source][destination] = 0;
for (int source = 1; source <= numberOfVertices; source++) {
for (int destination = 1; destination <= numberOfVertices; destination++) {
adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) {
adjacencyMatrix[source][destination] = 0;
continue;
}
if (Adjacency_Matrix[source][destination] == 0)
{
Adjacency_Matrix[source][destination] = INFINITY;
if (adjacencyMatrix[source][destination] == 0) {
adjacencyMatrix[source][destination] = INFINITY;
}
}
}
System.out.println("The Transitive Closure of the Graph");
FloydWarshall floydwarshall = new FloydWarshall(numberofvertices);
floydwarshall.floydwarshall(adjacency_matrix);
FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices);
floydwarshall.floydwarshall(adjacencyMatrix);
scan.close();
}
}
}

View File

@ -1,3 +1,5 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.lang.StringBuilder;
@ -19,7 +21,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
public boolean addAdjacentVertex(Vertex to) {
for (Vertex v: adjacentVerticies) {
for (Vertex v : adjacentVerticies) {
if (v.data.compareTo(to.data) == 0) {
return false; // the edge already exists
}
@ -51,7 +53,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
*/
public boolean removeEdge(E from, E to) {
Vertex fromV = null;
for (Vertex v: verticies) {
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) {
fromV = v;
break;
@ -60,6 +62,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
if (fromV == null) return false;
return fromV.removeAdjacentVertex(to);
}
/**
* this method adds an edge to the graph between two specified
* verticies
@ -70,7 +73,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
*/
public boolean addEdge(E from, E to) {
Vertex fromV = null, toV = null;
for (Vertex v: verticies) {
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
fromV = v;
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
@ -94,14 +97,15 @@ class AdjacencyListGraph<E extends Comparable<E>> {
*
* @return returns a string describing this graph
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Vertex v: verticies) {
for (Vertex v : verticies) {
sb.append("Vertex: ");
sb.append(v.data);
sb.append("\n");
sb.append("Adjacent verticies: ");
for (Vertex v2: v.adjacentVerticies) {
for (Vertex v2 : v.adjacentVerticies) {
sb.append(v2.data);
sb.append(" ");
}

View File

@ -1,174 +0,0 @@
// Java program for Kruskal's algorithm to find Minimum Spanning Tree
// of a given connected, undirected and weighted graph
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph
{
// A class to represent a graph edge
class Edge implements Comparable<Edge>
{
int src, dest, weight;
// Comparator function used for sorting edges based on
// their weight
public int compareTo(Edge compareEdge)
{
return this.weight-compareEdge.weight;
}
};
// A class to represent a subset for union-find
class subset
{
int parent, rank;
};
int V, E; // V-> no. of vertices & E->no.of edges
Edge edge[]; // collection of all edges
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[E];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}
// A utility function to find set of an element i
// (uses path compression technique)
int find(subset subsets[], int i)
{
// find root and make root as parent of i (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and increment
// its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// The main function to construct MST using Kruskal's algorithm
void KruskalMST()
{
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges
for (i=0; i<V; ++i)
result[i] = new Edge();
// Step 1: Sort all the edges in non-decreasing order of their
// weight. If we are not allowed to change the given graph, we
// can create a copy of array of edges
Arrays.sort(edge);
// Allocate memory for creating V ssubsets
subset subsets[] = new subset[V];
for(i=0; i<V; ++i)
subsets[i]=new subset();
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
i = 0; // Index used to pick next edge
// Number of edges to be taken is equal to V-1
while (e < V - 1)
{
// Step 2: Pick the smallest edge. And increment the index
// for next iteration
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does't cause cycle, include it
// in result and increment the index of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display the built MST
System.out.println("Following are the edges in the constructed MST");
for (i = 0; i < e; ++i)
System.out.println(result[i].src+" -- "+result[i].dest+" == "+
result[i].weight);
}
// Driver Program
public static void main (String[] args)
{
/* Let us create following weighted graph
10
0--------1
| \ |
6| 5\ |15
| \ |
2--------3
4 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
// add edge 0-2
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
// add edge 0-3
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
// add edge 1-3
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
// add edge 2-3
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
}
}

View File

@ -1,3 +1,5 @@
package DataStructures.Graphs;
public class MatrixGraphs {
public static void main(String args[]) {
@ -108,7 +110,7 @@ class AdjacencyMatrixGraph {
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;

View File

@ -1,23 +1,23 @@
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
//adjacency matrix representation of the graph
package DataStructures.Graphs;
import java.lang.*;
class PrimMST
{
/**
* 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
private static final int V=5;
private static final int V = 5;
// A utility function to find the vertex with minimum key
// value, from the set of vertices not yet included in MST
int minKey(int key[], Boolean mstSet[])
{
int minKey(int key[], Boolean mstSet[]) {
// Initialize min value
int min = Integer.MAX_VALUE, min_index=-1;
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
{
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
@ -27,30 +27,27 @@ class PrimMST
// A utility function to print the constructed MST stored in
// parent[]
void printMST(int parent[], int n, int graph[][])
{
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+" "+
System.out.println(parent[i] + " - " + i + " " +
graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented
// using adjacency matrix representation
void primMST(int graph[][])
{
void primMST(int graph[][]) {
// Array to store constructed MST
int parent[] = new int[V];
// Key values used to pick minimum weight edge in cut
int key[] = new int [V];
int key[] = new int[V];
// To represent set of vertices not yet included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
{
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
@ -61,8 +58,7 @@ class PrimMST
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V-1; count++)
{
for (int count = 0; count < V - 1; count++) {
// Pick thd minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);
@ -78,9 +74,8 @@ 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];
}
@ -90,8 +85,7 @@ class PrimMST
printMST(parent, V, graph);
}
public static void main (String[] args)
{
public static void main(String[] args) {
/* Let us create the following graph
2 3
(0)--(1)--(2)
@ -101,7 +95,7 @@ class PrimMST
(3)-------(4)
9 */
PrimMST t = new PrimMST();
int graph[][] = new int[][] {{0, 2, 0, 6, 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},

View File

@ -1,10 +1,13 @@
package DataStructures.HashMap.Hashing;
class HashMap {
private int hsize;
private LinkedList[] buckets;
public HashMap(int hsize) {
buckets = new LinkedList[hsize];
for (int i = 0; i < hsize ; i++ ) {
for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList();
// Java requires explicit initialisaton of each object
}
@ -13,7 +16,7 @@ class HashMap {
public int hashing(int key) {
int hash = key % hsize;
if(hash < 0)
if (hash < 0)
hash += hsize;
return hash;
}
@ -29,9 +32,10 @@ class HashMap {
buckets[hash].delete(key);
}
public void displayHashtable() {
for (int i = 0;i < hsize ; i++) {
System.out.printf("Bucket %d :",i);
for (int i = 0; i < hsize; i++) {
System.out.printf("Bucket %d :", i);
buckets[i].display();
}
}

View File

@ -1,3 +1,5 @@
package DataStructures.HashMap.Hashing;
class LinkedList {
private Node Head;

View File

@ -1,3 +1,5 @@
package DataStructures.HashMap.Hashing;
import java.util.Scanner;
public class Main {

View File

@ -1,3 +1,5 @@
package DataStructures.HashMap.Hashing;
class Node {
int data;
Node next;

View File

@ -1,6 +1,3 @@
/**
*
*/
package DataStructures.Heaps;
/**

View File

@ -1,6 +1,3 @@
/**
*
*/
package DataStructures.Heaps;
import java.lang.Double;

View File

@ -1,6 +1,3 @@
/**
*
*/
package DataStructures.Heaps;
import java.util.ArrayList;

View File

@ -1,5 +1,7 @@
package DataStructures.Heaps;
/* Minimum 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.
@ -7,10 +9,10 @@ package DataStructures.Heaps;
* 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
*/
// Functions: insert, delete, peek, isEmpty, print, heapSort, sink
public class MinPriorityQueue {
private int[] heap;
private int capacity;

View File

@ -1,47 +1,58 @@
public class CircleLinkedList<E>{
private static class Node<E>{
package DataStructures.Lists;
public class CircleLinkedList<E> {
private static class Node<E> {
Node<E> next;
E value;
private Node(E value, Node<E> next){
private Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
//For better O.O design this should be private allows for better black box design
private int size;
//this will point to dummy node;
private Node<E> head;
//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(){
public CircleLinkedList() {
//creation of the dummy node
head = new Node<E>(null,head);
head = new Node<E>(null, head);
size = 0;
}
// getter for the size... needed because size is private.
public int getSize(){ return size;}
public int getSize() {
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.
public void append(E value){
if(value == null){
public void append(E value) {
if (value == null) {
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//head.next points to the last element;
head.next = new Node<E>(value,head);
size++;}
public E remove(int pos){
if(pos>size || pos< 0){
head.next = new Node<E>(value, head);
size++;
}
public E remove(int pos) {
if (pos > size || pos < 0) {
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//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++){
for (int i = 1; i <= pos; i++) {
iterator = iterator.next;
before = before.next;
}
E saved = iterator.value;
// assigning the next referance 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 = iterator.next;
// scrubbing
iterator.next = null;
@ -50,5 +61,5 @@ public class CircleLinkedList<E>{
}
}
}

View File

@ -1,3 +1,7 @@
package DataStructures.Lists;
import java.util.Objects;
public class CursorLinkedList<T> {
private static class Node<T> {
@ -93,7 +97,7 @@ public class CursorLinkedList<T> {
while (start != -1) {
T element = cursorSpace[start].element;
if (counter == position){
if (counter == position) {
return element;
}
@ -107,9 +111,9 @@ public class CursorLinkedList<T> {
}
public void removeByIndex(int index){
public void removeByIndex(int index) {
if(index >= 0 && index < count){
if (index >= 0 && index < count) {
T element = get(index);
remove(element);
@ -133,10 +137,10 @@ public class CursorLinkedList<T> {
int prev_index = head;
int current_index = cursorSpace[prev_index].next;
while (current_index != -1 ) {
while (current_index != -1) {
T current_element = cursorSpace[current_index].element;
if(current_element.equals(element)){
if (current_element.equals(element)) {
cursorSpace[prev_index].next = cursorSpace[current_index].next;
free(current_index);
break;

View File

@ -1,3 +1,4 @@
package DataStructures.Lists;
/**
* This class implements a DoublyLinkedList. This is done using the classes
@ -13,7 +14,7 @@
* @author Unknown
*/
class DoublyLinkedList {
public class DoublyLinkedList {
/**
* Head refers to the front of the list
*/

View File

@ -1,3 +1,5 @@
package DataStructures.Lists;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

View File

@ -1,3 +1,5 @@
package DataStructures.Lists;
/**
* This class implements a SinglyLinked List. This is done
* using SinglyLinkedList class and a LinkForLinkedList Class.
@ -8,10 +10,8 @@
* 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.
*
* @author yanglbme
*/
class SinglyLinkedList {
public class SinglyLinkedList {
/**
* Head refer to the front of the list
*/
@ -38,8 +38,7 @@ class SinglyLinkedList {
public void insertNth(int data, int position) {
if (position < 0 || position > getSize()) {
throw new RuntimeException("position less than zero or position more than the count of list");
}
else if (position == 0)
} else if (position == 0)
insertHead(data);
else {
Node cur = head;
@ -155,8 +154,6 @@ class SinglyLinkedList {
* This class is the nodes of the SinglyLinked List.
* They consist of a value and a pointer to the node
* after them.
*
* @author yanglbme
*/
class Node {
/**

View File

@ -1,267 +0,0 @@
/**
* Matrix data-type.
*
* @author Kyler Smith, 2017
*/
public class Matrix {
public static void main(String[] args) {
int[][] data1 = new int[0][0];
int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
Matrix m1 = new Matrix(data1);
Matrix m2 = new Matrix(data2);
Matrix m3 = new Matrix(data3);
System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns());
System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns());
System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns());
//check for reference issues
System.out.println("m2 -->\n" + m2);
data2[1][1] = 101;
System.out.println("m2 -->\n" + m2);
//test equals
System.out.println("m2==null: " + m2.equals(null)); //false
System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false
System.out.println("m2==m1: " + m2.equals(m1)); //false
System.out.println("m2==m2: " + m2.equals(m2)); //true
System.out.println("m2==m3: " + m2.equals(m3)); //false
//test operations (valid)
System.out.println("2 * m2:\n" + m2.scale(2));
System.out.println("m2 / 2:\n" + m2.divide(2));
System.out.println("m2 + m3:\n" + m2.plus(m3));
System.out.println("m2 - m3:\n" + m2.minus(m3));
System.out.println("m2 * m3: \n"+m2.multiply(m3));
}
/**
* Data needs to be a deep copy as not to change the original state.
*/
private int[][] data;
/**
* Constructor for the matrix takes in a 2D array
*
* @param pData
*/
public Matrix(int[][] pData) {
/** Make a deep copy of the data */
if(pData.length != 0) {
int[][] newData = new int[pData.length][pData[0].length];
for(int i = 0; i < pData.length; i++)
for(int j = 0; j < pData[0].length; j++)
newData[i][j] = pData[i][j];
this.data = newData;
} else {
this.data = null;
}
}
/**
* Returns the element specified by the given location
*
* @param x : x cooridinate
* @param y : y cooridinate
* @return int : value at location
*/
public int getElement(int x, int y) {
return data[x][y];
}
/**
* Returns the number of rows in the Matrix
*
* @return rows
*/
public int getRows() {
if(this.data == null)
return 0;
return data.length;
}
/**
* Returns the number of rows in the Matrix
*
* @return columns
*/
public int getColumns() {
if(this.data == null)
return 0;
return data[0].length;
}
/**
* Returns this matrix scaled by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to scale by
* @return A new matrix scaled by the scalar value
*/
public Matrix scale(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] * scalar;
return new Matrix(newData);
}
/**
* Returns this matrix divided by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to divide by
* @return A new matrix scaled by the scalar value
*/
public Matrix divide(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] / scalar;
return new Matrix(newData);
}
/**
* Adds this matrix to another matrix.
*
* @param other : Matrix to be added
* @return addend
*/
public Matrix plus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] + other.getElement(i, j);
return new Matrix(newData);
}
/**
* Subtracts this matrix from another matrix.
*
* @param other : Matrix to be subtracted
* @return difference
*/
public Matrix minus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] - other.getElement(i, j);
return new Matrix(newData);
}
/**
* Multiplies this matrix with another matrix.
*
* @param other : Matrix to be multiplied with
* @return product
*/
public Matrix multiply(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][other.getColumns()];
if(this.getColumns() !=other.getRows())
throw new RuntimeException("The two matrices cannot be multiplied.");
int sum;
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < other.getColumns(); ++j){
sum = 0;
for(int k=0;k<this.getColumns();++k){
sum += this.data[i][k] * other.getElement(k, j);
}
newData[i][j] = sum;
}
return new Matrix(newData);
}
/**
* Checks if the matrix passed is equal to this matrix
*
* @param other : the other matrix
* @return boolean
*/
public boolean equals(Matrix other) {
if (this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
return false;
for (int i = 0; i < this.data.length; i++)
for (int j = 0; j < this.data[0].length; j++)
if (this.data[i][j] != other.data[i][j])
return false;
return true;
}
/**
* Returns the Matrix as a String in the following format
*
* [ a b c ] ...
* [ x y z ] ...
* [ i j k ] ...
* ...
*
* @return Matrix as String
* TODO: Work formatting for different digit sizes
*/
public String toString() {
String str = "";
for(int i = 0; i < this.data.length; i++) {
str += "[ ";
for(int j = 0; j < this.data[0].length; j++) {
str += data[i][j];
str += " ";
}
str += "]";
str += "\n";
}
return str;
}
/**
* Returns transposed matrix of this matrix.
*
* @return transposed Matrix.
*/
public Matrix transpose() {
int[][] newData = new int[this.data[0].length][this.data.length];
for (int i = 0; i < this.getColumns(); ++i)
for(int j = 0; j < this.getRows(); ++j)
newData[i][j] = this.data[j][i];
return new Matrix(newData);
}
}

View File

@ -1,191 +0,0 @@
/**
*
* Java implementation of Matrix fast power
* It can calculate the high power of constant Matrix with O( log(K) )
* where K is the power of the Matrix
*
* In order to do that, Matrix must be square Matrix ( columns equals rows)
*
* Notice : large power of Matrix may cause overflow
*
*
* other Matrix basic operator is based on @author Kyler Smith, 2017
*
* @author DDullahan, 2018
*
*/
class MatrixFastPower {
/**
* Matrix Fast Power
*
* @param matrix : square Matrix
* @param k : power of Matrix
* @return product
*/
public static Matrix FastPower(Matrix matrix, int k) throws RuntimeException {
if(matrix.getColumns() != matrix.getRows())
throw new RuntimeException("Matrix is not square Matrix.");
int[][] newData = new int[matrix.getColumns()][matrix.getRows()];
for(int i = 0; i < matrix.getColumns(); i++)
newData[i][i] = 1;
Matrix newMatrix = new Matrix(newData),
coMatrix = new Matrix(matrix.data);
while(k != 0) {
if((k & 1) != 0)
newMatrix = newMatrix.multiply(coMatrix);
k >>= 1;
coMatrix = coMatrix.multiply(coMatrix);
}
return newMatrix;
}
public static void main(String[] argv) {
int[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Matrix matrix = new Matrix(data);
System.out.println("original matrix : ");
System.out.println(matrix.toString());
matrix = MatrixFastPower.FastPower(matrix, 5);
System.out.println("after power : ");
System.out.println(matrix.toString());
matrix = MatrixFastPower.FastPower(matrix, 1000000);
System.out.println("notice, large power may cause overflow : ");
System.out.print(matrix.toString());
System.out.println("you can use mod to fix that :-) ");
}
}
class Matrix {
public int[][] data;
/**
* Constructor for the matrix takes in a 2D array
*
* @param pData
*/
public Matrix(int[][] pData) {
/** Make a deep copy of the data */
if(pData.length != 0) {
int[][] newData = new int[pData.length][pData[0].length];
for(int i = 0; i < pData.length; i++)
for(int j = 0; j < pData[0].length; j++)
newData[i][j] = pData[i][j];
this.data = newData;
} else {
this.data = null;
}
}
/**
* Returns the element specified by the given location
*
* @param x : x cooridinate
* @param y : y cooridinate
* @return int : value at location
*/
public int getElement(int x, int y) {
return data[x][y];
}
/**
* Returns the number of rows in the Matrix
*
* @return rows
*/
public int getRows() {
if(this.data == null)
return 0;
return data.length;
}
/**
* Returns the number of rows in the Matrix
*
* @return columns
*/
public int getColumns() {
if(this.data == null)
return 0;
return data[0].length;
}
/**
* Multiplies this matrix with another matrix.
*
* @param other : Matrix to be multiplied with
* @return product
*/
public Matrix multiply(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][other.getColumns()];
if(this.getColumns() != other.getRows())
throw new RuntimeException("The two matrices cannot be multiplied.");
int sum;
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < other.getColumns(); ++j) {
sum = 0;
for(int k = 0; k < this.getColumns(); ++k) {
sum += this.data[i][k] * other.getElement(k, j);
}
newData[i][j] = sum;
}
return new Matrix(newData);
}
/**
* Returns the Matrix as a String in the following format
*
* [ a b c ] ...
* [ x y z ] ...
* [ i j k ] ...
* ...
*
* @return Matrix as String
* TODO: Work formatting for different digit sizes
*/
public String toString() {
String str = "";
for(int i = 0; i < this.data.length; i++) {
str += "[ ";
for(int j = 0; j < this.data[0].length; j++) {
str += data[i][j];
str += " ";
}
str += "]";
str += "\n";
}
return str;
}
}

View File

@ -1,28 +1,69 @@
package DataStructures.Queues;
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.
*
*/
public class GenericArrayListQueue<T> {
/**
* The generic ArrayList for the queue
* T is the generic element
*/
ArrayList<T> _queue = new ArrayList<T>();
/**
* Checks if the queue has elements (not empty)
*
* @return True if the queue has elements. False otherwise.
*/
private boolean hasElements() {
return !_queue.isEmpty();
}
/**
* Checks what's at the front of the queue
*
* @return If queue is not empty, element at the front of the queue. Otherwise, null
*/
public T peek() {
T result = null;
if(this.hasElements()) { result = _queue.get(0); }
return result;
}
/**
* Inserts an element of type T to the queue.
*
* @param element of type T to be added
* @return True if the element was added successfully
*/
public boolean add(T element) {
return _queue.add(element);
}
/**
* Retrieve what's at the front of the queue
*
* @return If queue is not empty, element retrieved. Otherwise, null
*/
public T poll() {
T result = null;
if(this.hasElements()) { result = _queue.remove(0); }
return result;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
System.out.println("Running...");

View File

@ -1,3 +1,5 @@
package DataStructures.Queues;
/**
* This class implements a PriorityQueue.
* <p>
@ -6,7 +8,6 @@
* 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 {
/**

View File

@ -1,3 +1,5 @@
package DataStructures.Queues;
/**
* This implements Queues by using the class Queue.
* <p>

View File

@ -1,3 +1,5 @@
package DataStructures.Stacks;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/

View File

@ -1,3 +1,5 @@
package DataStructures.Trees;
public class AVLTree {
private Node root;
@ -43,26 +45,26 @@ public class AVLTree {
return true;
}
private void delete(Node node){
if(node.left == null && node.right == null){
if(node.parent == null) root = null;
else{
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) root = null;
else {
Node parent = node.parent;
if(parent.left == node){
if (parent.left == node) {
parent.left = null;
}else parent.right = null;
} else parent.right = null;
rebalance(parent);
}
return;
}
if(node.left!=null){
if (node.left != null) {
Node child = node.left;
while (child.right!=null) child = child.right;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
}else{
} else {
Node child = node.right;
while (child.left!=null) child = child.left;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
@ -194,9 +196,9 @@ public class AVLTree {
}
}
private void reheight(Node node){
if(node!=null){
node.height=1 + Math.max(height(node.left), height(node.right));
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}

View File

@ -1,21 +1,31 @@
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.
*
* @author Unknown
*
*/
* 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 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{
* 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.
*
* @author Unknown
*
*/
class Node {
/** Data for the node */
public int data;
/** The Node to the left of this one */
@ -30,32 +40,22 @@ class Node{
*
* @param value Value to put in the node
*/
public Node(int value){
public Node(int value) {
data = value;
left = null;
right = null;
parent = null;
}
}
}
/**
* A binary tree is a data structure in which an element
* has two successors(children). The left child is usually
* smaller than the parent, and the right child is usually
* bigger.
*
* @author Unknown
*
*/
class Tree{
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
public Tree(){
public BinaryTree() {
root = null;
}
@ -68,12 +68,12 @@ class Tree{
public Node find(int key) {
Node current = root;
while (current != null) {
if(key < current.data) {
if(current.left == null)
if (key < current.data) {
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)
} else if (key > current.data) {
if (current.right == null)
return current;
current = current.right;
} else { // If you find the value return it
@ -88,21 +88,20 @@ class Tree{
*
* @param value Value to be inserted
*/
public void put(int value){
public void put(int value) {
Node newNode = new Node(value);
if(root == null)
if (root == null)
root = newNode;
else{
else {
//This will return the soon to be parent of the value you're inserting
Node parent = find(value);
//This if/else assigns the new node to be either the left or right child of the parent
if(value < parent.data){
if (value < parent.data) {
parent.left = newNode;
parent.left.parent = parent;
return;
}
else{
} else {
parent.right = newNode;
parent.right.parent = parent;
return;
@ -116,21 +115,21 @@ class Tree{
* @param value Value to be deleted
* @return If the value was deleted
*/
public boolean remove(int value){
public boolean remove(int value) {
//temp is the node to be deleted
Node temp = find(value);
//If the value doesn't exist
if(temp.data != value)
if (temp.data != value)
return false;
//No children
if(temp.right == null && temp.left == null){
if(temp == root)
if (temp.right == null && temp.left == null) {
if (temp == root)
root = null;
//This if/else assigns the new node to be either the left or right child of the parent
else if(temp.parent.data < temp.data)
else if (temp.parent.data < temp.data)
temp.parent.right = null;
else
temp.parent.left = null;
@ -138,7 +137,7 @@ class Tree{
}
//Two children
else if(temp.left != null && temp.right != null){
else if (temp.left != null && temp.right != null) {
Node successor = findSuccessor(temp);
//The left tree of temp is made the left tree of the successor
@ -146,24 +145,24 @@ class Tree{
successor.left.parent = successor;
//If the successor has a right child, the child's grandparent is it's new parent
if(successor.right != null && successor.parent != temp){
if (successor.right != null && successor.parent != temp) {
successor.right.parent = successor.parent;
successor.parent.left = successor.right;
successor.right = temp.right;
successor.right.parent = successor;
}
if(temp == root){
if (temp == root) {
successor.parent = null;
root = successor;
return true;
}
//If you're not deleting the root
else{
else {
successor.parent = temp.parent;
//This if/else assigns the new node to be either the left or right child of the parent
if(temp.parent.data < temp.data)
if (temp.parent.data < temp.data)
temp.parent.right = successor;
else
temp.parent.left = successor;
@ -171,30 +170,34 @@ class Tree{
}
}
//One child
else{
else {
//If it has a right child
if(temp.right != null){
if(temp == root){
root = temp.right; return true;}
if (temp.right != null) {
if (temp == root) {
root = temp.right;
return true;
}
temp.right.parent = temp.parent;
//Assigns temp to left or right child
if(temp.data < temp.parent.data)
if (temp.data < temp.parent.data)
temp.parent.left = temp.right;
else
temp.parent.right = temp.right;
return true;
}
//If it has a left child
else{
if(temp == root){
root = temp.left; return true;}
else {
if (temp == root) {
root = temp.left;
return true;
}
temp.left.parent = temp.parent;
//Assigns temp to left or right side
if(temp.data < temp.parent.data)
if (temp.data < temp.parent.data)
temp.parent.left = temp.left;
else
temp.parent.right = temp.left;
@ -210,12 +213,12 @@ class Tree{
* @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)
public Node findSuccessor(Node n) {
if (n.right == null)
return n;
Node current = n.right;
Node parent = n.right;
while(current != null){
while (current != null) {
parent = current;
current = current.left;
}
@ -227,7 +230,7 @@ class Tree{
*
* @return the root of the Binary Tree
*/
public Node getRoot(){
public Node getRoot() {
return root;
}
@ -236,8 +239,8 @@ class Tree{
*
* @param localRoot The local root of the binary tree
*/
public void inOrder(Node localRoot){
if(localRoot != null){
public void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.data + " ");
inOrder(localRoot.right);
@ -249,8 +252,8 @@ class Tree{
*
* @param localRoot The local root of the binary tree
*/
public void preOrder(Node localRoot){
if(localRoot != null){
public void preOrder(Node localRoot) {
if (localRoot != null) {
System.out.print(localRoot.data + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
@ -262,11 +265,11 @@ class Tree{
*
* @param localRoot The local root of the binary tree
*/
public void postOrder(Node localRoot){
if(localRoot != null){
public void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data + " ");
}
}
}
}

View File

@ -1,100 +0,0 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
import java.util.LinkedList;
public class FindHeightOfTree {
// Driver Program
public static void main(String[] args) {
Node tree = new Node(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(-1);
tree.insert(29);
tree.insert(93);
tree.insert(6);
tree.insert(0);
tree.insert(-5);
tree.insert(-6);
tree.insert(-8);
tree.insert(-1);
// A level order representation of the tree
tree.printLevelOrder();
System.out.println();
System.out.println("Height of the tree is: " + tree.findHeight());
}
}
/**
* The Node class which initializes a Node of a tree
* printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
* findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf
*/
class Node {
Node left, right;
int data;
public Node(int data) {
this.data = data;
}
public void insert (int value) {
if (value < data) {
if (left == null) {
left = new Node(value);
}
else {
left.insert(value);
}
}
else {
if (right == null) {
right = new Node(value);
}
else {
right.insert(value);
}
}
}
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);
while(!queue.isEmpty()) {
Node n = queue.poll();
System.out.print(n.data + " ");
if (n.left != null) {
queue.add(n.left);
}
if (n.right != null) {
queue.add(n.right);
}
}
}
public int findHeight() {
return findHeight(this);
}
private int findHeight(Node root) {
if (root.left == null && root.right == null) {
return 0;
}
else if (root.left != null && root.right != null) {
return 1 + Math.max(findHeight(root.left), findHeight(root.right));
}
else if (root.left == null && root.right != null) {
return 1 + findHeight(root.right);
}
else {
return 1 + findHeight(root.left);
}
}
}

View File

@ -1,7 +1,19 @@
package DataStructures.Trees;
import java.util.ArrayList;
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.
*/
public class GenericTree {
private class Node {
int data;
@ -11,17 +23,6 @@ public class GenericTree {
private Node root;
private int size;
/*
A generic tree is a tree which can have as many children as it can be
It might be possible that every node present is directly connected to
root node.
In this code
Every function has two copies: one function is helper function which can be called from
main and from that function a private function is called which will do the actual work.
I have done this, while calling from main one have to give minimum parameters.
*/
public GenericTree() { //Constructor
Scanner scn = new Scanner(System.in);
root = create_treeG(null, 0, scn);
@ -40,19 +41,18 @@ public class GenericTree {
System.out.println("number of children");
int number = scn.nextInt();
for (int i = 0; i < number; i++) {
Node childd = create_treeG(node, i, scn);
Node child = create_treeG(node, i, scn);
size++;
node.child.add(childd);
node.child.add(child);
}
return node;
}
/*
Function to display the generic tree
/**
* Function to display the generic tree
*/
public void display() { //Helper function
display_1(root);
return;
}
private void display_1(Node parent) {
@ -64,14 +64,14 @@ public class GenericTree {
for (int i = 0; i < parent.child.size(); i++) {
display_1(parent.child.get(i));
}
return;
}
/*
One call store the size directly but if you are asked compute size this function to calcuate
size goes as follows
/**
* One call store the size directly but if you are asked compute size this function to calculate
* size goes as follows
*
* @return size
*/
public int size2call() {
return size2(root);
}
@ -84,8 +84,10 @@ public class GenericTree {
return sz + 1;
}
/*
Function to compute maximum value in the generic tree
/**
* Function to compute maximum value in the generic tree
*
* @return maximum value
*/
public int maxcall() {
int maxi = root.data;
@ -102,10 +104,11 @@ public class GenericTree {
return maxi;
}
/*
Function to compute HEIGHT of the generic tree
/**
* Function to compute HEIGHT of the generic tree
*
* @return height
*/
public int heightcall() {
return height(root) - 1;
}
@ -120,10 +123,12 @@ public class GenericTree {
return h + 1;
}
/*
Function to find whether a number is present in the generic tree or not
/**
* Function to find whether a number is present in the generic tree or not
*
* @param info number
* @return present or not
*/
public boolean findcall(int info) {
return find(root, info);
}
@ -138,8 +143,11 @@ public class GenericTree {
return false;
}
/*
Function to calculate depth of generic tree
/**
* Function to calculate depth of generic tree
*
* @param dep depth
*/
public void depthcaller(int dep) {
depth(root, dep);
@ -155,8 +163,8 @@ public class GenericTree {
return;
}
/*
Function to print generic tree in pre-order
/**
* Function to print generic tree in pre-order
*/
public void preordercall() {
preorder(root);
@ -169,8 +177,8 @@ public class GenericTree {
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);
@ -183,10 +191,9 @@ public class GenericTree {
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);
@ -202,8 +209,8 @@ 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);
@ -224,3 +231,4 @@ public class GenericTree {
}
}
}

View File

@ -1,74 +1,55 @@
class Node
{
package DataStructures.Trees;
public class LevelOrderTraversal {
class Node {
int data;
Node left, right;
public Node(int item)
{
public Node(int item) {
data = item;
left = right = null;
}
}
}
public class LevelOrderTraversal
{
// Root of the Binary Tree
Node root;
public LevelOrderTraversal()
{
public LevelOrderTraversal() {
root = null;
}
/* function to print level order traversal of tree*/
void printLevelOrder()
{
void printLevelOrder() {
int h = height(root);
int i;
for (i=1; i<=h; 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)
{
int height(Node root) {
if (root == null)
return 0;
else
{
else {
/**
* Return the height of larger subtree
*/
return Math.max(height(root.left),height(root.right)) + 1;
return Math.max(height(root.left), height(root.right)) + 1;
}
}
/* Print nodes at the given level */
void printGivenLevel (Node root ,int level)
{
void printGivenLevel(Node root, int level) {
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);
else if (level > 1) {
printGivenLevel(root.left, level - 1);
printGivenLevel(root.right, level - 1);
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
LevelOrderTraversal tree = new LevelOrderTraversal();
tree.root= new Node(1);
tree.root.left= new Node(2);
tree.root.right= new Node(3);
tree.root.left.left= new Node(4);
tree.root.left.right= new Node(5);
System.out.println("Level order traversal of binary tree is ");
tree.printLevelOrder();
}
}

View File

@ -1,8 +1,14 @@
package DataStructures.Trees;
import java.util.Queue;
import java.util.LinkedList;
/* Class to represent Tree node */
class Node {
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {
/* Class to represent Tree node */
class Node {
int data;
Node left, right;
@ -11,21 +17,16 @@ class Node {
left = null;
right = null;
}
}
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {
}
Node root;
/* Given a binary tree. Print its nodes in level order
using array for implementing queue */
void printLevelOrder()
{
void printLevelOrder() {
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while (!queue.isEmpty())
{
while (!queue.isEmpty()) {
/* poll() removes the present head.
For more information on poll() visit
@ -44,19 +45,4 @@ public class LevelOrderTraversalQueue {
}
}
}
public static void main(String args[])
{
/* creating a binary tree and entering
the nodes */
LevelOrderTraversalQueue tree_level = new LevelOrderTraversalQueue();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
System.out.println("Level order traversal of binary tree is - ");
tree_level.printLevelOrder();
}
}

View File

@ -1,16 +1,17 @@
// Java program to print top view of Binary tree
import java.util.*;
package DataStructures.Trees;// Java program to print top view of Binary tree
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
// Class for a tree node
class TreeNode
{
class TreeNode {
// Members
int key;
TreeNode left, right;
// Constructor
public TreeNode(int key)
{
public TreeNode(int key) {
this.key = key;
left = right = null;
}
@ -19,31 +20,35 @@ class TreeNode
// A class to represent a queue item. The queue is used to do Level
// order traversal. Every Queue item contains node and horizontal
// distance of node from root
class QItem
{
class QItem {
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
public QItem(TreeNode n, int h) {
node = n;
hd = h;
}
}
// Class for a Binary Tree
class Tree
{
class Tree {
TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
public Tree() {
root = null;
}
public Tree(TreeNode n) {
root = n;
}
// This method prints nodes in top view of binary tree
public void printTopView()
{
public void printTopView() {
// base case
if (root == null) { return; }
if (root == null) {
return;
}
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
@ -53,8 +58,7 @@ class Tree
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
// Standard BFS or level order traversal loop
while (!Q.isEmpty())
{
while (!Q.isEmpty()) {
// Remove the front item and get its details
QItem qi = Q.remove();
int hd = qi.hd;
@ -62,26 +66,23 @@ class Tree
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd))
{
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd-1));
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd+1));
Q.add(new QItem(n.right, hd + 1));
}
}
}
// Driver class to test above methods
public class PrintTopViewofTree
{
public static void main(String[] args)
{
public class PrintTopViewofTree {
public static void main(String[] args) {
/* Create following Binary Tree
1
/ \

View File

@ -1,5 +1,8 @@
package DataStructures.Trees;
import java.util.Scanner;
/**
*
* @author jack870131
*/
public class RedBlackBST {

View File

@ -1,10 +1,10 @@
package DataStructures.Trees;
import java.util.LinkedList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
* @author Varun Upadhyay (https://github.com/varunu28)
*/
// Driver Program
@ -38,13 +38,13 @@ 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;
int data;
@ -53,20 +53,17 @@ class Node {
this.data = data;
}
public void insert (int value) {
public void insert(int value) {
if (value < data) {
if (left == null) {
left = new Node(value);
}
else {
} else {
left.insert(value);
}
}
else {
} else {
if (right == null) {
right = new Node(value);
}
else {
} else {
right.insert(value);
}
}

View File

@ -1,10 +1,11 @@
//Trie Data structure implementation without any libraries */
package DataStructures.Trees;
/**
* Trie Data structure implementation without any libraries
*
* @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
*
*/
import java.util.Scanner;
public class TrieImp {
@ -13,34 +14,37 @@ public class TrieImp {
TrieNode[] child;
boolean end;
public TrieNode(){
public TrieNode() {
child = new TrieNode[26];
end = false;
}
}
private final TrieNode root;
public TrieImp(){
public TrieImp() {
root = new TrieNode();
}
public void insert(String word){
public void insert(String word) {
TrieNode currentNode = root;
for(int i=0; i < word.length();i++){
TrieNode node = currentNode.child[word.charAt(i)-'a'];
if(node == null){
for (int i = 0; i < word.length(); i++) {
TrieNode node = currentNode.child[word.charAt(i) - 'a'];
if (node == null) {
node = new TrieNode();
currentNode.child[word.charAt(i)-'a']=node;
currentNode.child[word.charAt(i) - 'a'] = node;
}
currentNode = node;
}
currentNode.end = true;
}
public boolean search(String word){
public boolean search(String word) {
TrieNode currentNode = root;
for(int i=0;i<word.length();i++){
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = currentNode.child[ch-'a'];
if(node == null){
TrieNode node = currentNode.child[ch - 'a'];
if (node == null) {
return false;
}
currentNode = node;
@ -48,29 +52,31 @@ public class TrieImp {
return currentNode.end;
}
public boolean delete(String word){
public boolean delete(String word) {
TrieNode currentNode = root;
for(int i=0;i<word.length();i++){
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = currentNode.child[ch-'a'];
if(node == null){
TrieNode node = currentNode.child[ch - 'a'];
if (node == null) {
return false;
}
currentNode = node;
}
if(currentNode.end == true){
if (currentNode.end == true) {
currentNode.end = false;
return true;
}
return false;
}
public static void sop(String print){
public static void sop(String print) {
System.out.println(print);
}
//Regex to check if word contains only a-z character
public static boolean isValid(String word){
/**
* Regex to check if word contains only a-z character
*/
public static boolean isValid(String word) {
return word.matches("^[a-z]+$");
}
@ -80,40 +86,40 @@ public class TrieImp {
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
sop("string should contain only a-z character for all operation");
while(true){
while (true) {
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
try{
try {
int t = scan.nextInt();
switch (t) {
case 1:
word = scan.next();
if(isValid(word))
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))
boolean resS = false;
if (isValid(word))
resS = obj.search(word);
else
sop("Invalid string: allowed only a-z");
if(resS)
if (resS)
sop("word found");
else
sop("word not found");
break;
case 3:
word = scan.next();
boolean resD=false;
if(isValid(word))
boolean resD = false;
if (isValid(word))
resD = obj.delete(word);
else
sop("Invalid string: allowed only a-z");
if(resD){
if (resD) {
sop("word got deleted successfully");
}else{
} else {
sop("word not found");
}
break;
@ -125,7 +131,7 @@ public class TrieImp {
sop("Input int from 1-4");
break;
}
}catch(Exception e){
} catch (Exception e) {
String badInput = scan.next();
sop("This is bad input: " + badInput);
}

View File

@ -1,17 +1,17 @@
class Node
{
package DataStructures.Trees;
public class ValidBSTOrNot {
class Node {
int data;
Node left, right;
public Node(int item)
{
public Node(int item) {
data = item;
left = right = null;
}
}
}
public class ValidBSTOrNot
{
//Root of the Binary Tree
Node root;
@ -27,8 +27,7 @@ public class ValidBSTOrNot
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
boolean isBSTUtil(Node node, int min, int max)
{
boolean isBSTUtil(Node node, int min, int max) {
/* an empty tree is BST */
if (node == null)
return true;
@ -40,23 +39,7 @@ public class ValidBSTOrNot
/* 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));
}
/* Driver program to test above functions */
public static void main(String args[])
{
ValidBSTOrNot tree = new ValidBSTOrNot();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
return (isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max));
}
}

View File

@ -1,89 +0,0 @@
/**
Author : SUBHAM SANGHAI
A Dynamic Programming based solution for Edit Distance problem In Java
**/
/**Description of Edit Distance with an Example:
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.
The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
kitten → sitten (substitution of "s" for "k")
sitten → sittin (substitution of "i" for "e")
sittin → sitting (insertion of "g" at the end).**/
import java.util.Scanner;
public class Edit_Distance
{
public static int minDistance(String word1, String word2)
{
int len1 = word1.length();
int len2 = word2.length();
// len1+1, len2+1, because finally return dp[len1][len2]
int[][] dp = new int[len1 + 1][len2 + 1];
/* If second string is empty, the only option is to
insert all characters of first string into second*/
for (int i = 0; i <= len1; i++)
{
dp[i][0] = i;
}
/* If first string is empty, the only option is to
insert all characters of second string into first*/
for (int j = 0; j <= len2; j++)
{
dp[0][j] = j;
}
//iterate though, and check last char
for (int i = 0; i < len1; i++)
{
char c1 = word1.charAt(i);
for (int j = 0; j < len2; j++)
{
char c2 = word2.charAt(j);
//if last two chars equal
if (c1 == c2)
{
//update dp value for +1 length
dp[i + 1][j + 1] = dp[i][j];
}
else
{
/* if two characters are different ,
then take the minimum of the various operations(i.e insertion,removal,substitution)*/
int replace = dp[i][j] + 1;
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
int min = replace > insert ? insert : replace;
min = delete > min ? min : delete;
dp[i + 1][j + 1] = min;
}
}
}
/* return the final answer , after traversing through both the strings*/
return dp[len1][len2];
}
// Driver program to test above function
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String s1,s2;
System.out.println("Enter the First String");
s1 = input.nextLine();
System.out.println("Enter the Second String");
s2 = input.nextLine();
//ans stores the final Edit Distance between the two strings
int ans=0;
ans=minDistance(s1,s2);
System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 +"\" is "+ans);
}
}

View File

@ -1,71 +0,0 @@
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Vector;
public class Ford_Fulkerson {
Scanner scan = new Scanner(System.in);
final static int INF = 987654321;
static int V; // edges
static int[][] capacity, flow;
public static void main(String[] args) {
System.out.println("V : 6");
V = 6;
capacity = new int[V][V];
capacity[0][1] = 12;
capacity[0][3] = 13;
capacity[1][2] = 10;
capacity[2][3] = 13;
capacity[2][4] = 3;
capacity[2][5] = 15;
capacity[3][2] = 7;
capacity[3][4] = 15;
capacity[4][5] = 17;
System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
}
private static int networkFlow(int source, int sink) {
flow = new int[V][V];
int totalFlow = 0;
while (true) {
Vector<Integer> parent = new Vector<>(V);
for (int i = 0; i < V; i++)
parent.add(-1);
Queue<Integer> q = new LinkedList<>();
parent.set(source, source);
q.add(source);
while (!q.isEmpty() && parent.get(sink) == -1) {
int here = q.peek();
q.poll();
for (int there = 0; there < V; ++there)
if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
q.add(there);
parent.set(there, here);
}
}
if (parent.get(sink) == -1)
break;
int amount = INF;
String printer = "path : ";
StringBuilder sb = new StringBuilder();
for (int p = sink; p != source; p = parent.get(p)) {
amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
sb.append(p + "-");
}
sb.append(source);
for (int p = sink; p != source; p = parent.get(p)) {
flow[parent.get(p)][p] += amount;
flow[p][parent.get(p)] -= amount;
}
totalFlow += amount;
printer += sb.reverse() + " / max flow : " + totalFlow;
System.out.println(printer);
}
return totalFlow;
}
}

View File

@ -1,55 +0,0 @@
import java.util.Scanner;
/**
* Program to implement Kadanes Algorithm to
* calculate maximum contiguous subarray sum of an array
* Time Complexity: O(n)
*
* @author Nishita Aggarwal
*
*/
public class KadaneAlgorithm {
/**
* This method implements Kadane's Algorithm
*
* @param arr The input array
* @return The maximum contiguous subarray sum of the array
*
*/
static int largestContiguousSum(int arr[]){
int i,len=arr.length,cursum=0,maxsum=Integer.MIN_VALUE;
if(len==0) //empty array
return 0;
for(i=0;i<len;i++){
cursum+=arr[i];
if(cursum>maxsum){
maxsum=cursum;
}
if(cursum<=0){
cursum=0;
}
}
return maxsum;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n,arr[],i;
n=sc.nextInt();
arr=new int[n];
for(i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int maxContSum=largestContiguousSum(arr);
System.out.println(maxContSum);
sc.close();
}
}

View File

@ -1,38 +0,0 @@
// A Dynamic Programming based solution for 0-1 Knapsack problem
public class Knapsack
{
private static int knapSack(int W, int wt[], int val[], int n)
{
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;
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];
}
}
return rv[n][W];
}
// Driver program to test above function
public static void main(String args[])
{
int val[] = new int[]{50, 100, 130};
int wt[] = new int[]{10, 20, 40};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}

View File

@ -1,66 +0,0 @@
class LongestCommonSubsequence {
public static String getLCS(String str1, String str2) {
//At least one string is null
if(str1 == null || str2 == null)
return null;
//At least one string is empty
if(str1.length() == 0 || str2.length() == 0)
return "";
String[] arr1 = str1.split("");
String[] arr2 = str2.split("");
//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 = 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];
}
}
}
return lcsString(str1, str2, lcsMatrix);
}
public static String lcsString (String str1, String str2, int[][] lcsMatrix) {
StringBuilder lcs = new StringBuilder();
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));
i--;
j--;
} else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) {
i--;
} else {
j--;
}
}
return lcs.reverse().toString();
}
public static void main(String[] args) {
String str1 = "DSGSHSRGSRHTRD";
String str2 = "DATRGAGTSHS";
String lcs = getLCS(str1, str2);
//Print LCS
if(lcs != null) {
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
System.out.println("LCS: " + lcs);
System.out.println("LCS length: " + lcs.length());
}
}
}

View File

@ -1,9 +1,8 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
package DynamicProgramming;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
public class CoinChange {
// Driver Program
@ -26,12 +25,12 @@ public class CoinChange {
**/
public static int change(int[] coins, int amount) {
int[] combinations = new int[amount+1];
int[] combinations = new int[amount + 1];
combinations[0] = 1;
for (int coin : coins) {
for (int i=coin; i<amount+1; i++) {
combinations[i] += combinations[i-coin];
for (int i = coin; i < amount + 1; i++) {
combinations[i] += combinations[i - coin];
}
// Uncomment the below line to see the state of combinations for each coin
// printAmount(combinations);
@ -39,6 +38,7 @@ public class CoinChange {
return combinations[amount];
}
/**
* This method finds the minimum number of coins needed for a given amount.
*
@ -48,17 +48,17 @@ public class CoinChange {
**/
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];
int[] minimumCoins = new int[amount + 1];
minimumCoins[0] = 0;
for(int i=1;i<=amount;i++){
minimumCoins[i]=Integer.MAX_VALUE;
for (int i = 1; i <= amount; i++) {
minimumCoins[i] = Integer.MAX_VALUE;
}
for(int i=1;i<=amount;i++){
for (int coin :coins){
if(coin <=i){
int sub_res = minimumCoins[i-coin];
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
int sub_res = minimumCoins[i - coin];
if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i])
minimumCoins[i] = sub_res + 1;
}
@ -71,7 +71,7 @@ public class CoinChange {
// A basic print method which prints all the contents of the array
public static void printAmount(int[] arr) {
for (int i=0; i<arr.length; i++) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();

View File

@ -0,0 +1,78 @@
package DynamicProgramming;
/**
* 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>
* <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 {
public static int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
// len1+1, len2+1, because finally return dp[len1][len2]
int[][] dp = new int[len1 + 1][len2 + 1];
/* If second string is empty, the only option is to
insert all characters of first string into second*/
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
/* If first string is empty, the only option is to
insert all characters of second string into first*/
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
//iterate though, and check last char
for (int i = 0; i < len1; i++) {
char c1 = word1.charAt(i);
for (int j = 0; j < len2; j++) {
char c2 = word2.charAt(j);
//if last two chars equal
if (c1 == c2) {
//update dp value for +1 length
dp[i + 1][j + 1] = dp[i][j];
} else {
/* if two characters are different ,
then take the minimum of the various operations(i.e insertion,removal,substitution)*/
int replace = dp[i][j] + 1;
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
int min = replace > insert ? insert : replace;
min = delete > min ? min : delete;
dp[i + 1][j + 1] = min;
}
}
}
/* return the final answer , after traversing through both the strings*/
return dp[len1][len2];
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s1, s2;
System.out.println("Enter the First String");
s1 = input.nextLine();
System.out.println("Enter the Second String");
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);
}
}

View File

@ -1,5 +1,7 @@
package DynamicProgramming;
/**
* Dynamic Programming solution for the Egg Dropping Puzzle
* DynamicProgramming solution for the Egg Dropping Puzzle
*/
public class EggDropping {

View File

@ -1,3 +1,5 @@
package DynamicProgramming;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
@ -5,7 +7,6 @@ import java.util.Map;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
* @author yanglbme (https://github.com/yanglbme)
*/
public class Fibonacci {

View File

@ -0,0 +1,72 @@
package DynamicProgramming;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
public class FordFulkerson {
final static int INF = 987654321;
// edges
static int V;
static int[][] capacity, flow;
public static void main(String[] args) {
System.out.println("V : 6");
V = 6;
capacity = new int[V][V];
capacity[0][1] = 12;
capacity[0][3] = 13;
capacity[1][2] = 10;
capacity[2][3] = 13;
capacity[2][4] = 3;
capacity[2][5] = 15;
capacity[3][2] = 7;
capacity[3][4] = 15;
capacity[4][5] = 17;
System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
}
private static int networkFlow(int source, int sink) {
flow = new int[V][V];
int totalFlow = 0;
while (true) {
Vector<Integer> parent = new Vector<>(V);
for (int i = 0; i < V; i++)
parent.add(-1);
Queue<Integer> q = new LinkedList<>();
parent.set(source, source);
q.add(source);
while (!q.isEmpty() && parent.get(sink) == -1) {
int here = q.peek();
q.poll();
for (int there = 0; there < V; ++there)
if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
q.add(there);
parent.set(there, here);
}
}
if (parent.get(sink) == -1)
break;
int amount = INF;
String printer = "path : ";
StringBuilder sb = new StringBuilder();
for (int p = sink; p != source; p = parent.get(p)) {
amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
sb.append(p + "-");
}
sb.append(source);
for (int p = sink; p != source; p = parent.get(p)) {
flow[parent.get(p)][p] += amount;
flow[p][parent.get(p)] -= amount;
}
totalFlow += amount;
printer += sb.reverse() + " / max flow : " + totalFlow;
System.out.println(printer);
}
return totalFlow;
}
}

View File

@ -0,0 +1,55 @@
package DynamicProgramming;
import java.util.Scanner;
/**
* Program to implement Kadanes Algorithm to
* calculate maximum contiguous subarray sum of an array
* Time Complexity: O(n)
*
* @author Nishita Aggarwal
*/
public class KadaneAlgorithm {
/**
* This method implements Kadane's Algorithm
*
* @param arr The input array
* @return The maximum contiguous subarray sum of the array
*/
static int largestContiguousSum(int arr[]) {
int i, len = arr.length, cursum = 0, maxsum = Integer.MIN_VALUE;
if (len == 0) //empty array
return 0;
for (i = 0; i < len; i++) {
cursum += arr[i];
if (cursum > maxsum) {
maxsum = cursum;
}
if (cursum <= 0) {
cursum = 0;
}
}
return maxsum;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, arr[], i;
n = sc.nextInt();
arr = new int[n];
for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int maxContSum = largestContiguousSum(arr);
System.out.println(maxContSum);
sc.close();
}
}

View File

@ -0,0 +1,37 @@
package DynamicProgramming;
/**
* A DynamicProgramming based solution for 0-1 Knapsack problem
*/
public class Knapsack {
private static int knapSack(int W, int wt[], int val[], int n) {
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;
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];
}
}
return rv[n][W];
}
// Driver program to test above function
public static void main(String args[]) {
int val[] = new int[]{50, 100, 130};
int wt[] = new int[]{10, 20, 40};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}

View File

@ -1,3 +1,5 @@
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)

View File

@ -0,0 +1,68 @@
package DynamicProgramming;
class LongestCommonSubsequence {
public static String getLCS(String str1, String str2) {
//At least one string is null
if (str1 == null || str2 == null)
return null;
//At least one string is empty
if (str1.length() == 0 || str2.length() == 0)
return "";
String[] arr1 = str1.split("");
String[] arr2 = str2.split("");
//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 = 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];
}
}
}
return lcsString(str1, str2, lcsMatrix);
}
public static String lcsString(String str1, String str2, int[][] lcsMatrix) {
StringBuilder lcs = new StringBuilder();
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));
i--;
j--;
} else if (lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]) {
i--;
} else {
j--;
}
}
return lcs.reverse().toString();
}
public static void main(String[] args) {
String str1 = "DSGSHSRGSRHTRD";
String str2 = "DATRGAGTSHS";
String lcs = getLCS(str1, str2);
//Print LCS
if (lcs != null) {
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
System.out.println("LCS: " + lcs);
System.out.println("LCS length: " + lcs.length());
}
}
}

View File

@ -1,8 +1,9 @@
package DynamicProgramming;
import java.util.Scanner;
/**
* @author Afrizal Fikri (https://github.com/icalF)
* @author Libin Yang (https://github.com/yanglbme)
*/
public class LongestIncreasingSubsequence {
public static void main(String[] args) {

View File

@ -1,3 +1,5 @@
package DynamicProgramming;
import java.util.Scanner;
/**

View File

@ -1,3 +1,5 @@
package DynamicProgramming;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

View File

@ -1,8 +1,9 @@
package DynamicProgramming;
/**
* A Dynamic Programming solution for Rod cutting problem
* 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 {

View File

@ -1,5 +1,10 @@
import java.io.*;
import java.util.*;
package MinimizingLateness;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class MinimizingLateness {
@ -16,23 +21,23 @@ public class MinimizingLateness {
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
StringTokenizer token;
String ch;
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
int indexCount; // size of array index
ch = in.readLine();
indexCount = Integer.parseInt(ch); // The first line specifies the size of the operation (= the size of the array)
BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
String ch = in.readLine();
if (ch == null || ch.isEmpty()) {
return;
}
int indexCount = Integer.parseInt(ch);
System.out.println("Input Data : ");
System.out.println(indexCount); // number of operations
Schedule array[] = new Schedule[indexCount]; // Create an array to hold the operation
Schedule[] array = new Schedule[indexCount]; // Create an array to hold the operation
int i = 0;
while ((ch = in.readLine()) != null) {
token = new StringTokenizer(ch, " ");
// Include the time required for the operation to be performed in the array and the time it should be completed.
array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
i++; // 다음 인덱스
i++;
System.out.println(array[i - 1].t + " " + array[i - 1].d);
}

View File

@ -1,10 +1,12 @@
package Misc;
import java.util.Collections;
import java.util.PriorityQueue;
/**********************
author: shrutisheoran
***********************/
/**
* @author shrutisheoran
*/
public class MedianOfRunningArray {
private PriorityQueue<Integer> p1;
private PriorityQueue<Integer> p2;
@ -21,7 +23,7 @@ public class MedianOfRunningArray {
*/
public void insert(Integer e) {
p2.add(e);
if(p2.size() - p1.size() > 1)
if (p2.size() - p1.size() > 1)
p1.add(p2.remove());
}
@ -29,9 +31,9 @@ public class MedianOfRunningArray {
Returns median at any given point
*/
public Integer median() {
if(p1.size()==p2.size())
return (p1.peek() + p2.peek())/2;
return p1.size()>p2.size() ? p1.peek() : p2.peek();
if (p1.size() == p2.size())
return (p1.peek() + p2.peek()) / 2;
return p1.size() > p2.size() ? p1.peek() : p2.peek();
}
public static void main(String[] args) {
@ -41,7 +43,7 @@ public class MedianOfRunningArray {
MedianOfRunningArray p = new MedianOfRunningArray();
int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
for(int i = 0 ; i < 9 ; i++) {
for (int i = 0; i < 9; i++) {
p.insert(arr[i]);
System.out.print(p.median() + " ");
}

View File

@ -1,3 +1,5 @@
package Misc;
import java.util.Scanner;
public class PalindromePrime {
@ -20,9 +22,9 @@ public class PalindromePrime {
public static int reverse(int n) { // Returns the reverse of the number
int reverse = 0;
while(n != 0) {
while (n != 0) {
reverse *= 10;
reverse += n%10;
reverse += n % 10;
n /= 10;
}
return reverse;
@ -33,8 +35,8 @@ public class PalindromePrime {
System.out.print(2 + "\n"); // print the first Palindromic Prime
int count = 1;
int num = 3;
while(count < y) {
if(num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
while (count < y) {
if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
count++; // counts check when to terminate while loop
System.out.print(num + "\n"); // print the Palindromic Prime
}

View File

@ -1,7 +1,7 @@
public class heap_sort
{
public void sort(int arr[])
{
package Misc;
public class heap_sort {
public void sort(int[] arr) {
int n = arr.length;
// Build heap (rearrange array)
@ -9,8 +9,7 @@ public class heap_sort
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
@ -23,11 +22,10 @@ public class heap_sort
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
void heapify(int[] arr, int n, int i) {
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
@ -38,8 +36,7 @@ public class heap_sort
largest = r;
// If largest is not root
if (largest != i)
{
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
@ -50,17 +47,15 @@ public class heap_sort
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
static void printArray(int[] arr) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = arr.length;

View File

@ -1,16 +1,23 @@
//Oskar Enmalm 29/9/17
//An Abecadrian is a word where each letter is in alphabetical order
package Others;
class Abecedarian{
/**
* An Abecadrian is a word where each letter is in alphabetical order
*
* @author Oskar Enmalm
*/
class Abecedarian {
public static boolean isAbecedarian(String s){
public static boolean isAbecedarian(String s) {
int index = s.length() - 1;
for(int i =0; i <index; i++){
for (int i = 0; i < index; i++) {
if(s.charAt(i)<=s.charAt(i + 1)){} //Need to check if each letter for the whole word is less than the one before it
if (s.charAt(i) <= s.charAt(i + 1)) {
} //Need to check if each letter for the whole word is less than the one before it
else{return false;}
else {
return false;
}
}
return true;
}

View File

@ -1,3 +1,5 @@
package Others;
import java.util.Scanner;
/**
@ -6,10 +8,10 @@ import java.util.Scanner;
* 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3
*
* @author mani manasa mylavarapu
*
*/
public class Armstrong {
static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
int n = inputInt("please enter the number");
@ -43,6 +45,7 @@ public class Armstrong {
return false;
}
}
private static int inputInt(String string) {
System.out.print(string);
return Integer.parseInt(scan.nextLine());

View File

@ -1,22 +1,22 @@
package Others;
import java.util.Scanner;
/**
*
* @author Nishita Aggarwal
*
* <p>
* Brian Kernighans Algorithm
*
* <p>
* algorithm to count the number of set bits in a given number
*
* <p>
* Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the
* rightmost set bit).
* So if we subtract a number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit.
*
* <p>
* If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
*
*
* <p>
* <p>
* Time Complexity: O(logn)
*
*/
@ -24,15 +24,12 @@ public class BrianKernighanAlgorithm {
/**
* @param num: number in which we count the set bits
*
* @return int: Number of set bits
* */
static int countSetBits(int num)
{
*/
static int countSetBits(int num) {
int cnt = 0;
while(num != 0)
{
num = num & (num-1);
while (num != 0) {
num = num & (num - 1);
cnt++;
}
return cnt;
@ -40,12 +37,9 @@ public class BrianKernighanAlgorithm {
/**
*
* @param args : command line arguments
*
*/
public static void main(String args[])
{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int setBitCount = countSetBits(num);

View File

@ -1,3 +1,5 @@
package Others;
import java.util.BitSet;
/**

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