docs: update the whole repository

* fix some bugs
* delete duplicate files
* format code
This commit is contained in:
yanglbme
2019-05-09 19:32:54 +08:00
parent 163db8521a
commit 29948363da
368 changed files with 4372 additions and 30841 deletions

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,7 +12,6 @@ import java.util.Scanner;
*
* @author Michael Rolland
* @version 2017.10.10
*
*/
public class AnyBaseToAnyBase {
@ -78,6 +79,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.

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,28 +1,25 @@
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[])
{
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)
{
while (k != 0) {
d = k % 10;
s += d * (int) Math.pow(2, c++);
k /= 10;

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,24 +16,20 @@ 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<>();
//String to store hexadecimal code
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)));
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);

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 {
@ -30,8 +31,7 @@ public class BinaryToOctal {
*/
public static int convertBinaryToOctal(int b) {
int o = 0, r = 0, j = 1;
while(b!=0)
{
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,27 +1,25 @@
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)
{
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)
{
while (k != 0) {
d = k % 8;
s += d * (int) Math.pow(10, c++);
k /= 8;

View File

@ -1,27 +1,24 @@
/**
+ * Converts any Hexadecimal Number to Octal
+ *
+ * @author Tanmay Joshi
+ *
+ */
package Conversions;
import java.util.Scanner;
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)
{
* Converts any Hexadecimal Number to Octal
*
* @author Tanmay Joshi
*/
public class HexToOct {
/**
* 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;
@ -30,19 +27,16 @@ public class HexToOct
}
/**
+ * 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)
{
while (q > 0) {
now = q % 8;
octnum = (now * (int) (Math.pow(10, i))) + octnum;
q /= 8;
@ -51,9 +45,12 @@ public class HexToOct
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;
Scanner scan = new Scanner(System.in);
@ -62,7 +59,6 @@ public class HexToOct
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
// convert decimal to octal

View File

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

View File

@ -9,8 +9,7 @@ public class HexaDecimalToDecimal {
String digits = "012345678910ABCDEFF";
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;
}
@ -19,8 +18,7 @@ public class HexaDecimalToDecimal {
// 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);

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,26 +1,23 @@
/**
+ + * 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)
{
* 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++)
{
for (int j = 0; j < s.length(); j++) {
char num = s.charAt(j);
num -= '0';
i *= 8;
@ -30,12 +27,11 @@ public class OctalToHexadecimal {
}
/**
+ + * This method converts a Decimal number to
+ + * a Hexadecimal number
+ + *
+ + * @param The Decimal Number
+ + * @return The Hexadecimal number
+ + */
* 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)
@ -49,14 +45,19 @@ public static String DecimalToHex(int d) {
return hex;
}
//Driver Program
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
// 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;

View File

@ -1,3 +1,5 @@
package DataStructures.Buffers;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@ -56,6 +58,7 @@ public class CircularBuffer {
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
Random _random = new Random();
CircularBuffer _buffer;
public TestWriteWorker(CircularBuffer cb) {
this._buffer = cb;
}
@ -80,10 +83,12 @@ 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()) {

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;

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 @@
package DataStructures.Graphs;
import java.util.Arrays;
import java.util.Scanner;
public class FloydWarshall
{
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;
@ -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
@ -94,6 +97,7 @@ 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) {

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[]) {

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;
// 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;
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,8 +27,7 @@ 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 + " " +
@ -37,8 +36,7 @@ class PrimMST
// 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];
@ -49,8 +47,7 @@ class PrimMST
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);
@ -79,8 +75,7 @@ class PrimMST
// 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])
{
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)

View File

@ -1,3 +1,6 @@
package DataStructures.HashMap.Hashing;
class HashMap {
private int hsize;
private LinkedList[] buckets;
@ -29,6 +32,7 @@ class HashMap {
buckets[hash].delete(key);
}
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
System.out.printf("Bucket %d :", i);

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,24 +1,33 @@
package DataStructures.Lists;
public class CircleLinkedList<E> {
private static class Node<E> {
Node<E> next;
E value;
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() {
//creation of the dummy node
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) {
@ -27,7 +36,9 @@ public class CircleLinkedList<E>{
}
//head.next points to the last element;
head.next = new Node<E>(value, head);
size++;}
size++;
}
public E remove(int pos) {
if (pos > size || pos < 0) {
//catching errors

View File

@ -1,3 +1,7 @@
package DataStructures.Lists;
import java.util.Objects;
public class CursorLinkedList<T> {
private static class Node<T> {

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;
@ -71,8 +70,7 @@ class SinglyLinkedList {
public void deleteNth(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)
deleteHead();
else {
Node cur = head;
@ -156,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,3 +1,5 @@
package DataStructures.Matrix;
/**
* Matrix data-type.
*
@ -224,7 +226,7 @@ public class Matrix {
/**
* Returns the Matrix as a String in the following format
*
* <p>
* [ a b c ] ...
* [ x y z ] ...
* [ i j k ] ...

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,3 +1,5 @@
package DataStructures.Queues;
import java.util.ArrayList;
public class GenericArrayListQueue<T> {

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;

View File

@ -1,11 +1,21 @@
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.
*/
/**
* 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.
@ -39,23 +49,13 @@ 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
*
*/
class Tree{
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
public Tree(){
public BinaryTree() {
root = null;
}
@ -101,8 +101,7 @@ class Tree{
parent.left = newNode;
parent.left.parent = parent;
return;
}
else{
} else {
parent.right = newNode;
parent.right.parent = parent;
return;
@ -175,7 +174,9 @@ class Tree{
//If it has a right child
if (temp.right != null) {
if (temp == root) {
root = temp.right; return true;}
root = temp.right;
return true;
}
temp.right.parent = temp.parent;
@ -189,7 +190,9 @@ class Tree{
//If it has a left child
else {
if (temp == root) {
root = temp.left; return true;}
root = temp.left;
return true;
}
temp.left.parent = temp.parent;

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,3 +1,5 @@
package DataStructures.Trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
@ -224,3 +226,4 @@ public class GenericTree {
}
}
}

View File

@ -1,27 +1,26 @@
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++)
@ -31,12 +30,10 @@ public class LevelOrderTraversal
/* 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
*/
@ -45,30 +42,14 @@ public class LevelOrderTraversal
}
/* 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)
{
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,6 +1,12 @@
package DataStructures.Trees;
import java.util.Queue;
import java.util.LinkedList;
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {
/* Class to represent Tree node */
class Node {
int data;
@ -13,19 +19,14 @@ class Node {
}
}
/* 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,8 +66,7 @@ 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 + " ");
}
@ -78,10 +81,8 @@ class Tree
}
// 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,9 +1,9 @@
package DataStructures.Trees;
import java.util.LinkedList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
@ -57,16 +57,13 @@ class Node {
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 {
@ -18,7 +19,9 @@ public class TrieImp {
end = false;
}
}
private final TrieNode root;
public TrieImp() {
root = new TrieNode();
}
@ -35,6 +38,7 @@ public class TrieImp {
}
currentNode.end = true;
}
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
@ -69,7 +73,9 @@ public class TrieImp {
System.out.println(print);
}
//Regex to check if word contains only a-z character
/**
* Regex to check if word contains only a-z character
*/
public static boolean isValid(String word) {
return word.matches("^[a-z]+$");
}

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;
@ -43,20 +42,4 @@ public class ValidBSTOrNot
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");
}
}

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
@ -39,6 +38,7 @@ public class CoinChange {
return combinations[amount];
}
/**
* This method finds the minimum number of coins needed for a given amount.
*

View File

@ -0,0 +1,103 @@
package DynamicProgramming; /**
* Author : SUBHAM SANGHAI
* 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).
* 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).
**/
/**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,3 +1,5 @@
package DynamicProgramming;
/**
* DynamicProgramming solution for the Egg Dropping Puzzle
*/

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,73 @@
package DynamicProgramming;
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

@ -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 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,3 +1,5 @@
package MinimizingLateness;
import java.io.*;
import java.util.*;

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;

View File

@ -1,3 +1,5 @@
package Misc;
import java.util.Scanner;
public class PalindromePrime {

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,8 +22,7 @@ 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
@ -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,8 +47,7 @@ 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] + " ");
@ -59,8 +55,7 @@ public class heap_sort
}
// 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,6 +1,10 @@
//Oskar Enmalm 29/9/17
//An Abecadrian is a word where each letter is in alphabetical order
package Others;
/**
* An Abecadrian is a word where each letter is in alphabetical order
*
* @author Oskar Enmalm
*/
class Abecedarian {
public static boolean isAbecedarian(String s) {
@ -8,9 +12,12 @@ class Abecedarian{
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,14 +24,11 @@ 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)
{
while (num != 0) {
num = num & (num - 1);
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;
/**

View File

@ -1,12 +1,14 @@
package Others;
import java.util.Scanner;
/**
* @author Kyler Smith, 2017
*
* <p>
* Implementation of a character count.
* (Slow, could be improved upon, effectively O(n).
* */
*/
public class CountChar {
@ -20,23 +22,22 @@ public class CountChar {
/**
* @param str: String to count the characters
*
* @return int: Number of characters in the passed string
* */
*/
private static int CountCharacters(String str) {
int count = 0;
if(str == "" || str == null) //Exceptions
{
if (str == "" || str == null) {
return 0;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isWhitespace(str.charAt(i))) {
count++;
}}
}
}
return count;
}

28
Others/CountWords.java Normal file
View File

@ -0,0 +1,28 @@
package Others;
import java.util.Scanner;
/**
* You enter a string into this program, and it will return how many words were
* in that particular string
*
* @author Marcus
*/
public class CountWords {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your text: ");
String str = input.nextLine();
System.out.println("Your text has " + wordCount(str) + " word(s)");
input.close();
}
private static int wordCount(String s) {
if (s == null || s.isEmpty())
return 0;
return s.trim().split("[\\s]+").length;
}
}

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