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

View File

@ -1,126 +1,126 @@
package Bags;
package DataStructures.Bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Collection which does not allow removing elements (only collect and iterate)
*
*
* @param <Element> - the generic type of an element in this bag
*/
public class Bag<Element> implements Iterable<Element> {
private Node<Element> firstElement; // first element of the bag
private int size; // size of bag
private Node<Element> firstElement; // first element of the bag
private int size; // size of bag
private static class Node<Element> {
private Element content;
private Node<Element> nextElement;
}
private static class Node<Element> {
private Element content;
private Node<Element> nextElement;
}
/**
* Create an empty bag
*/
public Bag() {
firstElement = null;
size = 0;
}
/**
* Create an empty bag
*/
public Bag() {
firstElement = null;
size = 0;
}
/**
* @return true if this bag is empty, false otherwise
*/
public boolean isEmpty() {
return firstElement == null;
}
/**
* @return true if this bag is empty, false otherwise
*/
public boolean isEmpty() {
return firstElement == null;
}
/**
* @return the number of elements
*/
public int size() {
return size;
}
/**
* @return the number of elements
*/
public int size() {
return size;
}
/**
* @param element - the element to add
*/
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
firstElement.content = element;
firstElement.nextElement = oldfirst;
size++;
}
/**
* Checks if the bag contains a specific element
*
* @param element which you want to look for
* @return true if bag contains element, otherwise false
*/
public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator();
while(iterator.hasNext()) {
if (iterator.next().equals(element)) {
return true;
}
}
return false;
}
/**
* @param element - the element to add
*/
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
firstElement.content = element;
firstElement.nextElement = oldfirst;
size++;
}
/**
* @return an iterator that iterates over the elements in this bag in arbitrary order
*/
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
/**
* Checks if the bag contains a specific element
*
* @param element which you want to look for
* @return true if bag contains element, otherwise false
*/
public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals(element)) {
return true;
}
}
return false;
}
@SuppressWarnings("hiding")
private class ListIterator<Element> implements Iterator<Element> {
private Node<Element> currentElement;
/**
* @return an iterator that iterates over the elements in this bag in arbitrary order
*/
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
public ListIterator(Node<Element> firstElement) {
currentElement = firstElement;
}
@SuppressWarnings("hiding")
private class ListIterator<Element> implements Iterator<Element> {
private Node<Element> currentElement;
public boolean hasNext() {
return currentElement != null;
}
public ListIterator(Node<Element> firstElement) {
currentElement = firstElement;
}
/**
* remove is not allowed in a bag
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return currentElement != null;
}
public Element next() {
if (!hasNext())
throw new NoSuchElementException();
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
/**
* remove is not allowed in a bag
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/**
* main-method for testing
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
public Element next() {
if (!hasNext())
throw new NoSuchElementException();
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
bag.add("1");
bag.add("1");
bag.add("2");
/**
* main-method for testing
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
System.out.println("size of bag = " + bag.size());
for (String s : bag) {
System.out.println(s);
}
System.out.println(bag.contains(null));
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
bag.add("1");
bag.add("1");
bag.add("2");
System.out.println("size of bag = " + bag.size());
for (String s : bag) {
System.out.println(s);
}
System.out.println(bag.contains(null));
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
}

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

@ -1,150 +1,141 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* A class that counts the number of different connected components in a graph
*
* @author Lukas Keul, Florian Mercks
*
* @author Lukas Keul, Florian Mercks
*/
class Graph<E extends Comparable<E>> {
class Node {
E name;
class Node {
E name;
public Node(E name) {
this.name = name;
}
}
public Node(E name) {
this.name = name;
}
}
class Edge {
Node startNode, endNode;
class Edge {
Node startNode, endNode;
public Edge(Node startNode, Node endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
}
public Edge(Node startNode, Node endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
}
ArrayList<Edge> edgeList;
ArrayList<Node> nodeList;
ArrayList<Edge> edgeList;
ArrayList<Node> nodeList;
public Graph() {
edgeList = new ArrayList<Edge>();
nodeList = new ArrayList<Node>();
}
public Graph() {
edgeList = new ArrayList<Edge>();
nodeList = new ArrayList<Node>();
}
/**
* 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
*/
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) {
end = node;
}
}
if (start == null) {
start = new Node(startNode);
nodeList.add(start);
}
if (end == null) {
end = new Node(endNode);
nodeList.add(end);
}
/**
* 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
*/
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) {
end = node;
}
}
if (start == null) {
start = new Node(startNode);
nodeList.add(start);
}
if (end == null) {
end = new Node(endNode);
nodeList.add(end);
}
edgeList.add(new Edge(start, end));
}
edgeList.add(new Edge(start, end));
}
/**
* Main method used for counting the connected components. Iterates through
* the array of nodes to do a depth first search to get all nodes of the
* graph from the actual node. These nodes are added to the array
* markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*
*/
public int countGraphs() {
int count = 0;
Set<Node> markedNodes = new HashSet<Node>();
/**
* Main method used for counting the connected components. Iterates through
* the array of nodes to do a depth first search to get all nodes of the
* graph from the actual node. These nodes are added to the array
* markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*/
public int countGraphs() {
int count = 0;
Set<Node> markedNodes = new HashSet<Node>();
for (Node n : nodeList) {
if (!markedNodes.contains(n)) {
markedNodes.add(n);
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
count++;
}
}
for (Node n : nodeList) {
if (!markedNodes.contains(n)) {
markedNodes.add(n);
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
count++;
}
}
return count;
}
return count;
}
/**
* Implementation of 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);
for (Edge e : edgeList) {
if (e.startNode.equals(n) && !visited.contains(e.endNode)) {
depthFirstSearch(e.endNode, visited);
}
}
return visited;
}
/**
* Implementation of 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);
for (Edge e : edgeList) {
if (e.startNode.equals(n) && !visited.contains(e.endNode)) {
depthFirstSearch(e.endNode, visited);
}
}
return visited;
}
}
public class ConnectedComponent {
public static void main(String[] args) {
Graph graphChars = new Graph();
public static void main(String[] args) {
Graph graphChars = new Graph();
// Graph 1
graphChars.addEdge('a', 'b');
graphChars.addEdge('a', 'e');
graphChars.addEdge('b', 'e');
graphChars.addEdge('b', 'c');
graphChars.addEdge('c', 'd');
graphChars.addEdge('d', 'a');
graphChars.addEdge('x', 'y');
graphChars.addEdge('x', 'z');
graphChars.addEdge('w', 'w');
// Graph 1
graphChars.addEdge('a', 'b');
graphChars.addEdge('a', 'e');
graphChars.addEdge('b', 'e');
graphChars.addEdge('b', 'c');
graphChars.addEdge('c', 'd');
graphChars.addEdge('d', 'a');
Graph graphInts = new Graph();
// Graph 2
graphInts.addEdge(1, 2);
graphInts.addEdge(2, 3);
graphInts.addEdge(2, 4);
graphInts.addEdge(3, 5);
graphInts.addEdge(7, 8);
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
graphChars.addEdge('x', 'y');
graphChars.addEdge('x', 'z');
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
graphChars.addEdge('w', 'w');
Graph graphInts = new Graph();
// Graph 2
graphInts.addEdge(1, 2);
graphInts.addEdge(2, 3);
graphInts.addEdge(2, 4);
graphInts.addEdge(3, 5);
graphInts.addEdge(7, 8);
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
}

View File

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

View File

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

View File

@ -1,78 +1,73 @@
import java.util.Scanner;
public class FloydWarshall
package DataStructures.Graphs;
import java.util.Arrays;
import java.util.Scanner;
public class FloydWarshall {
private int DistanceMatrix[][];
private int numberofvertices;//number of vertices in the graph
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
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
{
private int DistanceMatrix[][];
private int numberofvertices;//number of vertices in the graph
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices)
{
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1];//stores the value of distance from all the possible path form the source vertex to destination vertex
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++)
{
DistanceMatrix[source][destination] = AdjacencyMatrix[source][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
{
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] = DistanceMatrix[source][intermediate]
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++)
{
System.out.print(source + "\t");
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;
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];
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;
continue;
}
if (Adjacency_Matrix[source][destination] == 0)
{
Adjacency_Matrix[source][destination] = INFINITY;
}
}
for (int source = 1; source <= numberofvertices; source++)
System.out.print("\t" + source);
System.out.println();
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
for (int destination = 1; destination <= numberofvertices; destination++) {
System.out.print(DistanceMatrix[source][destination] + "\t");
}
System.out.println("The Transitive Closure of the Graph");
FloydWarshall floydwarshall = new FloydWarshall(numberofvertices);
floydwarshall.floydwarshall(adjacency_matrix);
scan.close();
System.out.println();
}
}
public static void main(String... arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
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++) {
adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) {
adjacencyMatrix[source][destination] = 0;
continue;
}
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(adjacencyMatrix);
scan.close();
}
}

View File

@ -1,8 +1,10 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.lang.StringBuilder;
class AdjacencyListGraph<E extends Comparable<E>> {
ArrayList<Vertex> verticies;
public AdjacencyListGraph() {
@ -19,7 +21,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
public boolean addAdjacentVertex(Vertex to) {
for (Vertex v: adjacentVerticies) {
for (Vertex v : adjacentVerticies) {
if (v.data.compareTo(to.data) == 0) {
return false; // the edge already exists
}
@ -46,12 +48,12 @@ class AdjacencyListGraph<E extends Comparable<E>> {
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(E from, E to) {
Vertex fromV = null;
for (Vertex v: verticies) {
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) {
fromV = v;
break;
@ -60,17 +62,18 @@ 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
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(E from, E to) {
Vertex fromV = null, toV = null;
for (Vertex v: verticies) {
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
fromV = v;
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
@ -91,17 +94,18 @@ class AdjacencyListGraph<E extends Comparable<E>> {
/**
* this gives a list of verticies in the graph and their adjacencies
*
*
* @return returns a string describing this graph
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Vertex v: verticies) {
for (Vertex v : verticies) {
sb.append("Vertex: ");
sb.append(v.data);
sb.append("\n");
sb.append("Adjacent verticies: ");
for (Vertex v2: v.adjacentVerticies) {
for (Vertex v2 : v.adjacentVerticies) {
sb.append(v2.data);
sb.append(" ");
}
@ -112,18 +116,18 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
public class Graphs {
public static void main(String args[]) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
public static void main(String args[]) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
assert graph.addEdge(1, 2);
assert graph.addEdge(1, 5);
assert graph.addEdge(2, 5);
assert !graph.addEdge(1, 2);
assert !graph.addEdge(1, 2);
assert graph.addEdge(2, 3);
assert graph.addEdge(3, 4);
assert graph.addEdge(4, 1);
assert !graph.addEdge(2, 3);
System.out.println(graph);
}
}

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,145 +1,147 @@
package DataStructures.Graphs;
public class MatrixGraphs {
public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}
public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}
}
class AdjacencyMatrixGraph {
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;
static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;
static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}
private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}
private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}
public int numberOfVertices() {
return this._numberOfVertices;
}
public int numberOfVertices() {
return this._numberOfVertices;
}
private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}
private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}
public int numberOfEdges() {
return this._numberOfEdges;
}
public int numberOfEdges() {
return this._numberOfEdges;
}
private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}
private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}
private int[][] adjacency() {
return this._adjacency;
}
private int[][] adjacency() {
return this._adjacency;
}
private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}
private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}
public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}
public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}
public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}
public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}
return false;
}
return false;
}
/**
/**
* This method adds an edge to the graph between two specified
* vertices
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}
return false;
}
return false;
}
/**
/**
* this method removes an edge from the graph between two specified
* vertices
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() - 1);
return true;
}
}
return false;
}
public boolean removeEdge(int from, int to) {
if (!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() - 1);
return true;
}
}
return false;
}
/**
* this gives a list of vertices in the graph and their adjacencies
*
*
* @return returns a string describing this graph
*/
public String toString() {
String s = new String();
s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
s = s + " \n";
public String toString() {
String s = new String();
s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
s = s + " \n";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + " ";
}
s = s + "\n";
}
return s;
}
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + " ";
}
s = s + "\n";
}
return s;
}
}

View File

@ -1,97 +1,91 @@
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
//adjacency matrix representation of the graph
package DataStructures.Graphs;
import java.lang.*;
class PrimMST
{
/**
* A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
* adjacency matrix representation of the graph
*/
class PrimMST {
// Number of vertices in the graph
private static final int V=5;
private static final int V = 5;
// A utility function to find the vertex with minimum key
// value, from the set of vertices not yet included in MST
int minKey(int key[], Boolean mstSet[])
{
int minKey(int key[], Boolean mstSet[]) {
// Initialize min value
int min = Integer.MAX_VALUE, min_index=-1;
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
{
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
// 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+" "+
graph[i][parent[i]]);
System.out.println(parent[i] + " - " + i + " " +
graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented
// using adjacency matrix representation
void primMST(int graph[][])
{
void primMST(int graph[][]) {
// Array to store constructed MST
int parent[] = new int[V];
// Key values used to pick minimum weight edge in cut
int key[] = new int [V];
int key[] = new int[V];
// To represent set of vertices not yet included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
{
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is
// picked as first vertex
// picked as first vertex
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);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
for (int v = 0; v < V; v++)
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v]!=0 && mstSet[v] == false &&
graph[u][v] < key[v])
{
parent[v] = u;
if (graph[u][v] != 0 && mstSet[v] == false &&
graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
// print the constructed MST
printMST(parent, V, graph);
}
public static void main (String[] args)
{
public static void main(String[] args) {
/* Let us create the following graph
2 3
(0)--(1)--(2)
@ -101,13 +95,13 @@ class PrimMST
(3)-------(4)
9 */
PrimMST t = new PrimMST();
int graph[][] = new int[][] {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
int graph[][] = new int[][]{{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
// Print the solution
t.primMST(graph);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
package DataStructures.Heaps;
/* Minimum Priority Queue
/**
* Minimum Priority Queue
* It is a part of heap data structure
* A heap is a specific tree based data structure
* in which all the nodes of tree are in a specific order.
@ -7,10 +9,10 @@ package DataStructures.Heaps;
* respect of their parents, can either be greater
* or less than the parent. This makes it a min priority queue
* or max priority queue.
* <p>
* <p>
* Functions: insert, delete, peek, isEmpty, print, heapSort, sink
*/
// Functions: insert, delete, peek, isEmpty, print, heapSort, sink
public class MinPriorityQueue {
private int[] heap;
private int capacity;

View File

@ -1,54 +1,65 @@
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;}
// for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
public void append(E value){
if(value == null){
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//head.next points to the last element;
head.next = new Node<E>(value,head);
size++;}
public E remove(int pos){
if(pos>size || pos< 0){
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//we need to keep track of the element before the element we want to remove we can see why bellow.
Node<E> before = head;
for(int i = 1; i<=pos; i++){
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;
}
// for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
public void append(E value) {
if (value == null) {
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//head.next points to the last element;
head.next = new Node<E>(value, head);
size++;
}
public E remove(int pos) {
if (pos > size || pos < 0) {
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//we need to keep track of the element before the element we want to remove we can see why bellow.
Node<E> before = head;
for (int i = 1; i <= pos; i++) {
iterator = iterator.next;
before = before.next;
}
E saved = iterator.value;
// assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
before.next = iterator.next;
// scrubbing
iterator.next = null;
iterator.value = null;
return saved;
before = before.next;
}
E saved = iterator.value;
// assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
before.next = iterator.next;
// scrubbing
iterator.next = null;
iterator.value = null;
return saved;
}
}
}
}

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
package DataStructures.Lists;
/**
* This class implements a SinglyLinked List. This is done
* using SinglyLinkedList class and a LinkForLinkedList Class.
@ -8,10 +10,8 @@
* it grows and shrinks as it is edited. This is an example of
* a singly linked list. Elements can only be added/removed
* at the head/front of the list.
*
* @author yanglbme
*/
class SinglyLinkedList {
public class SinglyLinkedList {
/**
* Head refer to the front of the list
*/
@ -38,8 +38,7 @@ class SinglyLinkedList {
public void insertNth(int data, int position) {
if (position < 0 || position > getSize()) {
throw new RuntimeException("position less than zero or position more than the count of list");
}
else if (position == 0)
} else if (position == 0)
insertHead(data);
else {
Node cur = head;
@ -66,13 +65,12 @@ class SinglyLinkedList {
}
/**
* This method deletes an element at Nth position
*/
* This method deletes an element at Nth position
*/
public void deleteNth(int position) {
if (position < 0 || position > getSize()) {
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;
@ -105,8 +103,8 @@ class SinglyLinkedList {
}
/**
* Returns the size of the linked list
*/
* Returns the size of the linked list
*/
public int getSize() {
if (head == null)
return 0;
@ -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,15 +1,17 @@
package DataStructures.Matrix;
/**
* Matrix data-type.
*
* @author Kyler Smith, 2017
*/
* Matrix data-type.
*
* @author Kyler Smith, 2017
*/
public class Matrix {
public static void main(String[] args) {
public static void main(String[] args) {
int[][] data1 = new int[0][0];
int[][] data1 = new int[0][0];
int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
@ -38,28 +40,28 @@ public class Matrix {
System.out.println("m2 / 2:\n" + m2.divide(2));
System.out.println("m2 + m3:\n" + m2.plus(m3));
System.out.println("m2 - m3:\n" + m2.minus(m3));
System.out.println("m2 * m3: \n"+m2.multiply(m3));
}
System.out.println("m2 * m3: \n" + m2.multiply(m3));
}
/**
* Data needs to be a deep copy as not to change the original state.
* Data needs to be a deep copy as not to change the original state.
*/
private int[][] data;
/**
* Constructor for the matrix takes in a 2D array
*
* @param pData
*/
* 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) {
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++)
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;
@ -69,178 +71,178 @@ public class Matrix {
}
/**
* Returns the element specified by the given location
*
* @param x : x cooridinate
* @param y : y cooridinate
* @return int : value at location
*/
* 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
*/
* Returns the number of rows in the Matrix
*
* @return rows
*/
public int getRows() {
if(this.data == null)
return 0;
if (this.data == null)
return 0;
return data.length;
}
/**
* Returns the number of rows in the Matrix
*
* @return columns
*/
* Returns the number of rows in the Matrix
*
* @return columns
*/
public int getColumns() {
if(this.data == null)
return 0;
if (this.data == null)
return 0;
return data[0].length;
}
/**
* Returns this matrix scaled by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to scale by
* @return A new matrix scaled by the scalar value
*/
* Returns this matrix scaled by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to scale by
* @return A new matrix scaled by the scalar value
*/
public Matrix scale(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] * scalar;
for (int i = 0; i < this.getRows(); ++i)
for (int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] * scalar;
return new Matrix(newData);
return new Matrix(newData);
}
/**
* Returns this matrix divided by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to divide by
* @return A new matrix scaled by the scalar value
*/
* Returns this matrix divided by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to divide by
* @return A new matrix scaled by the scalar value
*/
public Matrix divide(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] / scalar;
for (int i = 0; i < this.getRows(); ++i)
for (int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] / scalar;
return new Matrix(newData);
return new Matrix(newData);
}
/**
* Adds this matrix to another matrix.
*
* @param other : Matrix to be added
* @return addend
*/
* Adds this matrix to another matrix.
*
* @param other : Matrix to be added
* @return addend
*/
public Matrix plus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
if (this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] + other.getElement(i, j);
for (int i = 0; i < this.getRows(); ++i)
for (int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] + other.getElement(i, j);
return new Matrix(newData);
}
/**
* Subtracts this matrix from another matrix.
*
* @param other : Matrix to be subtracted
* @return difference
*/
* Subtracts this matrix from another matrix.
*
* @param other : Matrix to be subtracted
* @return difference
*/
public Matrix minus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
if (this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] - other.getElement(i, j);
for (int i = 0; i < this.getRows(); ++i)
for (int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] - other.getElement(i, j);
return new Matrix(newData);
}
/**
* Multiplies this matrix with another matrix.
*
* @param other : Matrix to be multiplied with
* @return product
*/
public Matrix multiply(Matrix other) throws RuntimeException {
public Matrix multiply(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][other.getColumns()];
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;
}
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);
}
return new Matrix(newData);
}
/**
* Checks if the matrix passed is equal to this matrix
*
* @param other : the other matrix
* @return boolean
*/
* Checks if the matrix passed is equal to this matrix
*
* @param other : the other matrix
* @return boolean
*/
public boolean equals(Matrix other) {
if (this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
return false;
for (int i = 0; i < this.data.length; i++)
for (int j = 0; j < this.data[0].length; j++)
if (this.data[i][j] != other.data[i][j])
return false;
return true;
}
/**
* Returns the Matrix as a String in the following format
*
* [ a b c ] ...
* [ x y z ] ...
* [ i j k ] ...
* ...
*
* @return Matrix as String
* TODO: Work formatting for different digit sizes
*/
* Returns the Matrix as a String in the following format
* <p>
* [ 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 += " ";
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";
@ -248,20 +250,20 @@ public class Matrix {
return str;
}
/**
* Returns transposed matrix of this matrix.
*
* @return transposed Matrix.
*/
public Matrix transpose() {
int[][] newData = new int[this.data[0].length][this.data.length];
for (int i = 0; i < this.getColumns(); ++i)
for(int j = 0; j < this.getRows(); ++j)
newData[i][j] = this.data[j][i];
/**
* Returns transposed matrix of this matrix.
*
* @return transposed Matrix.
*/
public Matrix transpose() {
return new Matrix(newData);
}
int[][] newData = new int[this.data[0].length][this.data.length];
for (int i = 0; i < this.getColumns(); ++i)
for (int j = 0; j < this.getRows(); ++j)
newData[i][j] = this.data[j][i];
return new Matrix(newData);
}
}

View File

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

View File

@ -1,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,19 +1,21 @@
package DataStructures.Trees;
public class AVLTree {
private Node root;
private class Node {
private int key;
private int balance;
private int height;
private Node left, right, parent;
Node(int k, Node p) {
key = k;
parent = p;
}
}
public boolean insert(int key) {
if (root == null)
root = new Node(key, null);
@ -23,12 +25,12 @@ public class AVLTree {
while (true) {
if (n.key == key)
return false;
parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
@ -42,38 +44,38 @@ public class AVLTree {
}
return true;
}
private void delete(Node node){
if(node.left == null && node.right == null){
if(node.parent == null) root = null;
else{
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) root = null;
else {
Node parent = node.parent;
if(parent.left == node){
if (parent.left == node) {
parent.left = null;
}else parent.right = null;
} else parent.right = null;
rebalance(parent);
}
return;
}
if(node.left!=null){
if (node.left != null) {
Node child = node.left;
while (child.right!=null) child = child.right;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
}else{
} else {
Node child = node.right;
while (child.left!=null) child = child.left;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node node = root;
Node child = root;
while (child != null) {
node = child;
child = delKey >= node.key ? node.right : node.left;
@ -83,43 +85,43 @@ public class AVLTree {
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
@ -127,25 +129,25 @@ public class AVLTree {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
@ -153,39 +155,39 @@ public class AVLTree {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
}
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
@ -193,20 +195,20 @@ public class AVLTree {
printBalance(n.right);
}
}
private void reheight(Node node){
if(node!=null){
node.height=1 + Math.max(height(node.left), height(node.right));
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}

View File

@ -1,272 +1,275 @@
package DataStructures.Trees;
/**
* This entire class is used to build a Binary Tree data structure.
* There is the Node Class and the Tree Class, both explained below.
*
* @author Unknown
*
*/
* This entire class is used to build a Binary Tree data structure.
* There is the Node Class and the Tree Class, both explained below.
*/
/**
* This class implements the nodes that will go on the Binary Tree.
* They consist of the data in them, the node to the left, the node
* to the right, and the parent from which they came from.
*
* @author Unknown
*
*/
class Node{
/** Data for the node */
public int data;
/** The Node to the left of this one */
public Node left;
/** The Node to the right of this one */
public Node right;
/** The parent of this node */
public Node parent;
* 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 {
/**
* Constructor of Node
*
* @param value Value to put in the node
*/
public Node(int value){
data = value;
left = null;
right = null;
parent = null;
}
/**
* This class implements the nodes that will go on the Binary Tree.
* They consist of the data in them, the node to the left, the node
* to the right, and the parent from which they came from.
*
* @author Unknown
*
*/
class Node {
/** Data for the node */
public int data;
/** The Node to the left of this one */
public Node left;
/** The Node to the right of this one */
public Node right;
/** The parent of this node */
public Node parent;
/**
* Constructor of Node
*
* @param value Value to put in the node
*/
public Node(int value) {
data = value;
left = null;
right = null;
parent = null;
}
}
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
public BinaryTree() {
root = null;
}
/**
* Method to find a Node with a certain value
*
* @param key Value being looked for
* @return The node if it finds it, otherwise returns the parent
*/
public Node find(int key) {
Node current = root;
while (current != null) {
if (key < current.data) {
if (current.left == null)
return current; //The key isn't exist, returns the parent
current = current.left;
} else if (key > current.data) {
if (current.right == null)
return current;
current = current.right;
} else { // If you find the value return it
return current;
}
}
return null;
}
/**
* Inserts certain value into the Binary Tree
*
* @param value Value to be inserted
*/
public void put(int value) {
Node newNode = new Node(value);
if (root == null)
root = newNode;
else {
//This will return the soon to be parent of the value you're inserting
Node parent = find(value);
//This if/else assigns the new node to be either the left or right child of the parent
if (value < parent.data) {
parent.left = newNode;
parent.left.parent = parent;
return;
} else {
parent.right = newNode;
parent.right.parent = parent;
return;
}
}
}
/**
* Deletes a given value from the Binary Tree
*
* @param value Value to be deleted
* @return If the value was deleted
*/
public boolean remove(int value) {
//temp is the node to be deleted
Node temp = find(value);
//If the value doesn't exist
if (temp.data != value)
return false;
//No children
if (temp.right == null && temp.left == null) {
if (temp == root)
root = null;
//This if/else assigns the new node to be either the left or right child of the parent
else if (temp.parent.data < temp.data)
temp.parent.right = null;
else
temp.parent.left = null;
return true;
}
//Two children
else if (temp.left != null && temp.right != null) {
Node successor = findSuccessor(temp);
//The left tree of temp is made the left tree of the successor
successor.left = temp.left;
successor.left.parent = successor;
//If the successor has a right child, the child's grandparent is it's new parent
if (successor.right != null && successor.parent != temp) {
successor.right.parent = successor.parent;
successor.parent.left = successor.right;
successor.right = temp.right;
successor.right.parent = successor;
}
if (temp == root) {
successor.parent = null;
root = successor;
return true;
}
//If you're not deleting the root
else {
successor.parent = temp.parent;
//This if/else assigns the new node to be either the left or right child of the parent
if (temp.parent.data < temp.data)
temp.parent.right = successor;
else
temp.parent.left = successor;
return true;
}
}
//One child
else {
//If it has a right child
if (temp.right != null) {
if (temp == root) {
root = temp.right;
return true;
}
temp.right.parent = temp.parent;
//Assigns temp to left or right child
if (temp.data < temp.parent.data)
temp.parent.left = temp.right;
else
temp.parent.right = temp.right;
return true;
}
//If it has a left child
else {
if (temp == root) {
root = temp.left;
return true;
}
temp.left.parent = temp.parent;
//Assigns temp to left or right side
if (temp.data < temp.parent.data)
temp.parent.left = temp.left;
else
temp.parent.right = temp.left;
return true;
}
}
}
/**
* This method finds the Successor to the Node given.
* Move right once and go left down the tree as far as you can
*
* @param n Node that you want to find the Successor of
* @return The Successor of the node
*/
public Node findSuccessor(Node n) {
if (n.right == null)
return n;
Node current = n.right;
Node parent = n.right;
while (current != null) {
parent = current;
current = current.left;
}
return parent;
}
/**
* Returns the root of the Binary Tree
*
* @return the root of the Binary Tree
*/
public Node getRoot() {
return root;
}
/**
* Prints leftChild - root - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.data + " ");
inOrder(localRoot.right);
}
}
/**
* Prints root - leftChild - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void preOrder(Node localRoot) {
if (localRoot != null) {
System.out.print(localRoot.data + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
/**
* Prints rightChild - leftChild - root
*
* @param localRoot The local root of the binary tree
*/
public void postOrder(Node localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data + " ");
}
}
}
/**
* A binary tree is a data structure in which an element
* has two successors(children). The left child is usually
* smaller than the parent, and the right child is usually
* bigger.
*
* @author Unknown
*
*/
class Tree{
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
public Tree(){
root = null;
}
/**
* Method to find a Node with a certain value
*
* @param key Value being looked for
* @return The node if it finds it, otherwise returns the parent
*/
public Node find(int key) {
Node current = root;
while (current != null) {
if(key < current.data) {
if(current.left == null)
return current; //The key isn't exist, returns the parent
current = current.left;
} else if(key > current.data) {
if(current.right == null)
return current;
current = current.right;
} else { // If you find the value return it
return current;
}
}
return null;
}
/**
* Inserts certain value into the Binary Tree
*
* @param value Value to be inserted
*/
public void put(int value){
Node newNode = new Node(value);
if(root == null)
root = newNode;
else{
//This will return the soon to be parent of the value you're inserting
Node parent = find(value);
//This if/else assigns the new node to be either the left or right child of the parent
if(value < parent.data){
parent.left = newNode;
parent.left.parent = parent;
return;
}
else{
parent.right = newNode;
parent.right.parent = parent;
return;
}
}
}
/**
* Deletes a given value from the Binary Tree
*
* @param value Value to be deleted
* @return If the value was deleted
*/
public boolean remove(int value){
//temp is the node to be deleted
Node temp = find(value);
//If the value doesn't exist
if(temp.data != value)
return false;
//No children
if(temp.right == null && temp.left == null){
if(temp == root)
root = null;
//This if/else assigns the new node to be either the left or right child of the parent
else if(temp.parent.data < temp.data)
temp.parent.right = null;
else
temp.parent.left = null;
return true;
}
//Two children
else if(temp.left != null && temp.right != null){
Node successor = findSuccessor(temp);
//The left tree of temp is made the left tree of the successor
successor.left = temp.left;
successor.left.parent = successor;
//If the successor has a right child, the child's grandparent is it's new parent
if(successor.right != null && successor.parent != temp){
successor.right.parent = successor.parent;
successor.parent.left = successor.right;
successor.right = temp.right;
successor.right.parent = successor;
}
if(temp == root){
successor.parent = null;
root = successor;
return true;
}
//If you're not deleting the root
else{
successor.parent = temp.parent;
//This if/else assigns the new node to be either the left or right child of the parent
if(temp.parent.data < temp.data)
temp.parent.right = successor;
else
temp.parent.left = successor;
return true;
}
}
//One child
else{
//If it has a right child
if(temp.right != null){
if(temp == root){
root = temp.right; return true;}
temp.right.parent = temp.parent;
//Assigns temp to left or right child
if(temp.data < temp.parent.data)
temp.parent.left = temp.right;
else
temp.parent.right = temp.right;
return true;
}
//If it has a left child
else{
if(temp == root){
root = temp.left; return true;}
temp.left.parent = temp.parent;
//Assigns temp to left or right side
if(temp.data < temp.parent.data)
temp.parent.left = temp.left;
else
temp.parent.right = temp.left;
return true;
}
}
}
/**
* This method finds the Successor to the Node given.
* Move right once and go left down the tree as far as you can
*
* @param n Node that you want to find the Successor of
* @return The Successor of the node
*/
public Node findSuccessor(Node n){
if(n.right == null)
return n;
Node current = n.right;
Node parent = n.right;
while(current != null){
parent = current;
current = current.left;
}
return parent;
}
/**
* Returns the root of the Binary Tree
*
* @return the root of the Binary Tree
*/
public Node getRoot(){
return root;
}
/**
* Prints leftChild - root - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void inOrder(Node localRoot){
if(localRoot != null){
inOrder(localRoot.left);
System.out.print(localRoot.data + " ");
inOrder(localRoot.right);
}
}
/**
* Prints root - leftChild - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void preOrder(Node localRoot){
if(localRoot != null){
System.out.print(localRoot.data + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
/**
* Prints rightChild - leftChild - root
*
* @param localRoot The local root of the binary tree
*/
public void postOrder(Node localRoot){
if(localRoot != null){
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data + " ");
}
}
}

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

View File

@ -1,62 +1,48 @@
package DataStructures.Trees;
import java.util.Queue;
import java.util.LinkedList;
/* Class to represent Tree node */
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {
/* Class to represent Tree node */
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
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
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
Node tempNode = queue.poll();
System.out.print(tempNode.data + " ");
/*Enqueue left child */
if (tempNode.left != null) {
queue.add(tempNode.left);
}
/*Enqueue right child */
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
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,87 +1,88 @@
// 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;
}
}
// 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
{
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
class QItem {
TreeNode node;
int hd;
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<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
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;
TreeNode n = qi.node;
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd))
{
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd-1));
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd+1));
Q.add(new QItem(n.right, hd + 1));
}
}
}
// Driver class to test above methods
public class PrintTopViewofTree
{
public static void main(String[] args)
{
public class PrintTopViewofTree {
public static void main(String[] args) {
/* Create following Binary Tree
1
/ \

View File

@ -1,330 +1,333 @@
package DataStructures.Trees;
import java.util.Scanner;
/**
*
* @author jack870131
*/
public class RedBlackBST {
private final int R = 0;
private final int B = 1;
private final int R = 0;
private final int B = 1;
private class Node {
private class Node {
int key = -1, color = B;
Node left = nil, right = nil, p = nil;
int key = -1, color = B;
Node left = nil, right = nil, p = nil;
Node(int key) {
this.key = key;
}
}
Node(int key) {
this.key = key;
}
}
private final Node nil = new Node(-1);
private Node root = nil;
private final Node nil = new Node(-1);
private Node root = nil;
public void printTree(Node node) {
if (node == nil) {
return;
}
printTree(node.left);
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
public void printTree(Node node) {
if (node == nil) {
return;
}
printTree(node.left);
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
public void printTreepre(Node node) {
if (node == nil) {
return;
}
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.left);
printTree(node.right);
}
public void printTreepre(Node node) {
if (node == nil) {
return;
}
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.left);
printTree(node.right);
}
private Node findNode(Node findNode, Node node) {
if (root == nil) {
return null;
}
if (findNode.key < node.key) {
if (node.left != nil) {
return findNode(findNode, node.left);
}
} else if (findNode.key > node.key) {
if (node.right != nil) {
return findNode(findNode, node.right);
}
} else if (findNode.key == node.key) {
return node;
}
return null;
}
private Node findNode(Node findNode, Node node) {
if (root == nil) {
return null;
}
if (findNode.key < node.key) {
if (node.left != nil) {
return findNode(findNode, node.left);
}
} else if (findNode.key > node.key) {
if (node.right != nil) {
return findNode(findNode, node.right);
}
} else if (findNode.key == node.key) {
return node;
}
return null;
}
private void insert(Node node) {
Node temp = root;
if (root == nil) {
root = node;
node.color = B;
node.p = nil;
} else {
node.color = R;
while (true) {
if (node.key < temp.key) {
if (temp.left == nil) {
temp.left = node;
node.p = temp;
break;
} else {
temp = temp.left;
}
} else if (node.key >= temp.key) {
if (temp.right == nil) {
temp.right = node;
node.p = temp;
break;
} else {
temp = temp.right;
}
}
}
fixTree(node);
}
}
private void insert(Node node) {
Node temp = root;
if (root == nil) {
root = node;
node.color = B;
node.p = nil;
} else {
node.color = R;
while (true) {
if (node.key < temp.key) {
if (temp.left == nil) {
temp.left = node;
node.p = temp;
break;
} else {
temp = temp.left;
}
} else if (node.key >= temp.key) {
if (temp.right == nil) {
temp.right = node;
node.p = temp;
break;
} else {
temp = temp.right;
}
}
}
fixTree(node);
}
}
private void fixTree(Node node) {
while (node.p.color == R) {
Node y = nil;
if (node.p == node.p.p.left) {
y = node.p.p.right;
private void fixTree(Node node) {
while (node.p.color == R) {
Node y = nil;
if (node.p == node.p.p.left) {
y = node.p.p.right;
if (y != nil && y.color == R) {
node.p.color = B;
y.color = B;
node.p.p.color = R;
node = node.p.p;
continue;
}
if (node == node.p.right) {
node = node.p;
rotateLeft(node);
}
node.p.color = B;
node.p.p.color = R;
rotateRight(node.p.p);
} else {
y = node.p.p.left;
if (y != nil && y.color == R) {
node.p.color = B;
y.color = B;
node.p.p.color = R;
node = node.p.p;
continue;
}
if (node == node.p.left) {
node = node.p;
rotateRight(node);
}
node.p.color = B;
node.p.p.color = R;
rotateLeft(node.p.p);
}
}
root.color = B;
}
if (y != nil && y.color == R) {
node.p.color = B;
y.color = B;
node.p.p.color = R;
node = node.p.p;
continue;
}
if (node == node.p.right) {
node = node.p;
rotateLeft(node);
}
node.p.color = B;
node.p.p.color = R;
rotateRight(node.p.p);
} else {
y = node.p.p.left;
if (y != nil && y.color == R) {
node.p.color = B;
y.color = B;
node.p.p.color = R;
node = node.p.p;
continue;
}
if (node == node.p.left) {
node = node.p;
rotateRight(node);
}
node.p.color = B;
node.p.p.color = R;
rotateLeft(node.p.p);
}
}
root.color = B;
}
void rotateLeft(Node node) {
if (node.p != nil) {
if (node == node.p.left) {
node.p.left = node.right;
} else {
node.p.right = node.right;
}
node.right.p = node.p;
node.p = node.right;
if (node.right.left != nil) {
node.right.left.p = node;
}
node.right = node.right.left;
node.p.left = node;
} else {
Node right = root.right;
root.right = right.left;
right.left.p = root;
root.p = right;
right.left = root;
right.p = nil;
root = right;
}
}
void rotateLeft(Node node) {
if (node.p != nil) {
if (node == node.p.left) {
node.p.left = node.right;
} else {
node.p.right = node.right;
}
node.right.p = node.p;
node.p = node.right;
if (node.right.left != nil) {
node.right.left.p = node;
}
node.right = node.right.left;
node.p.left = node;
} else {
Node right = root.right;
root.right = right.left;
right.left.p = root;
root.p = right;
right.left = root;
right.p = nil;
root = right;
}
}
void rotateRight(Node node) {
if (node.p != nil) {
if (node == node.p.left) {
node.p.left = node.left;
} else {
node.p.right = node.left;
}
void rotateRight(Node node) {
if (node.p != nil) {
if (node == node.p.left) {
node.p.left = node.left;
} else {
node.p.right = node.left;
}
node.left.p = node.p;
node.p = node.left;
if (node.left.right != nil) {
node.left.right.p = node;
}
node.left = node.left.right;
node.p.right = node;
} else {
Node left = root.left;
root.left = root.left.right;
left.right.p = root;
root.p = left;
left.right = root;
left.p = nil;
root = left;
}
}
node.left.p = node.p;
node.p = node.left;
if (node.left.right != nil) {
node.left.right.p = node;
}
node.left = node.left.right;
node.p.right = node;
} else {
Node left = root.left;
root.left = root.left.right;
left.right.p = root;
root.p = left;
left.right = root;
left.p = nil;
root = left;
}
}
void transplant(Node target, Node with) {
if (target.p == nil) {
root = with;
} else if (target == target.p.left) {
target.p.left = with;
} else
target.p.right = with;
with.p = target.p;
}
void transplant(Node target, Node with) {
if (target.p == nil) {
root = with;
} else if (target == target.p.left) {
target.p.left = with;
} else
target.p.right = with;
with.p = target.p;
}
Node treeMinimum(Node subTreeRoot) {
while (subTreeRoot.left != nil) {
subTreeRoot = subTreeRoot.left;
}
return subTreeRoot;
}
Node treeMinimum(Node subTreeRoot) {
while (subTreeRoot.left != nil) {
subTreeRoot = subTreeRoot.left;
}
return subTreeRoot;
}
boolean delete(Node z) {
if ((z = findNode(z, root)) == null)
return false;
Node x;
Node y = z;
int yorigcolor = y.color;
boolean delete(Node z) {
if ((z = findNode(z, root)) == null)
return false;
Node x;
Node y = z;
int yorigcolor = y.color;
if (z.left == nil) {
x = z.right;
transplant(z, z.right);
} else if (z.right == nil) {
x = z.left;
transplant(z, z.left);
} else {
y = treeMinimum(z.right);
yorigcolor = y.color;
x = y.right;
if (y.p == z)
x.p = y;
else {
transplant(y, y.right);
y.right = z.right;
y.right.p = y;
}
transplant(z, y);
y.left = z.left;
y.left.p = y;
y.color = z.color;
}
if (yorigcolor == B)
deleteFixup(x);
return true;
}
if (z.left == nil) {
x = z.right;
transplant(z, z.right);
} else if (z.right == nil) {
x = z.left;
transplant(z, z.left);
} else {
y = treeMinimum(z.right);
yorigcolor = y.color;
x = y.right;
if (y.p == z)
x.p = y;
else {
transplant(y, y.right);
y.right = z.right;
y.right.p = y;
}
transplant(z, y);
y.left = z.left;
y.left.p = y;
y.color = z.color;
}
if (yorigcolor == B)
deleteFixup(x);
return true;
}
void deleteFixup(Node x) {
while (x != root && x.color == B) {
if (x == x.p.left) {
Node w = x.p.right;
if (w.color == R) {
w.color = B;
x.p.color = R;
rotateLeft(x.p);
w = x.p.right;
}
if (w.left.color == B && w.right.color == B) {
w.color = R;
x = x.p;
continue;
} else if (w.right.color == B) {
w.left.color = B;
w.color = R;
rotateRight(w);
w = x.p.right;
}
if (w.right.color == R) {
w.color = x.p.color;
x.p.color = B;
w.right.color = B;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
if (w.color == R) {
w.color = B;
x.p.color = R;
rotateRight(x.p);
w = x.p.left;
}
if (w.right.color == B && w.left.color == B) {
w.color = R;
x = x.p;
continue;
} else if (w.left.color == B) {
w.right.color = B;
w.color = R;
rotateLeft(w);
w = x.p.left;
}
if (w.left.color == R) {
w.color = x.p.color;
x.p.color = B;
w.left.color = B;
rotateRight(x.p);
x = root;
}
}
}
x.color = B;
}
void deleteFixup(Node x) {
while (x != root && x.color == B) {
if (x == x.p.left) {
Node w = x.p.right;
if (w.color == R) {
w.color = B;
x.p.color = R;
rotateLeft(x.p);
w = x.p.right;
}
if (w.left.color == B && w.right.color == B) {
w.color = R;
x = x.p;
continue;
} else if (w.right.color == B) {
w.left.color = B;
w.color = R;
rotateRight(w);
w = x.p.right;
}
if (w.right.color == R) {
w.color = x.p.color;
x.p.color = B;
w.right.color = B;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
if (w.color == R) {
w.color = B;
x.p.color = R;
rotateRight(x.p);
w = x.p.left;
}
if (w.right.color == B && w.left.color == B) {
w.color = R;
x = x.p;
continue;
} else if (w.left.color == B) {
w.right.color = B;
w.color = R;
rotateLeft(w);
w = x.p.left;
}
if (w.left.color == R) {
w.color = x.p.color;
x.p.color = B;
w.left.color = B;
rotateRight(x.p);
x = root;
}
}
}
x.color = B;
}
public void insertDemo() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Add items");
public void insertDemo() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Add items");
int item;
Node node;
int item;
Node node;
item = scan.nextInt();
while (item != -999) {
node = new Node(item);
insert(node);
item = scan.nextInt();
}
printTree(root);
System.out.println("Pre order");
printTreepre(root);
break;
}
}
item = scan.nextInt();
while (item != -999) {
node = new Node(item);
insert(node);
item = scan.nextInt();
}
printTree(root);
System.out.println("Pre order");
printTreepre(root);
break;
}
}
public void deleteDemo() {
Scanner scan = new Scanner(System.in);
System.out.println("Delete items");
int item;
Node node;
item = scan.nextInt();
node = new Node(item);
System.out.print("Deleting item " + item);
if (delete(node)) {
System.out.print(": deleted!");
} else {
System.out.print(": does not exist!");
}
public void deleteDemo() {
Scanner scan = new Scanner(System.in);
System.out.println("Delete items");
int item;
Node node;
item = scan.nextInt();
node = new Node(item);
System.out.print("Deleting item " + item);
if (delete(node)) {
System.out.print(": deleted!");
} else {
System.out.print(": does not exist!");
}
System.out.println();
printTree(root);
System.out.println("Pre order");
printTreepre(root);
}
System.out.println();
printTree(root);
System.out.println("Pre order");
printTreepre(root);
}
}

View File

@ -1,10 +1,10 @@
package DataStructures.Trees;
import java.util.LinkedList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
* @author Varun Upadhyay (https://github.com/varunu28)
*/
// Driver Program
@ -38,13 +38,13 @@ public class TreeTraversal {
}
/**
* The Node class which initializes a Node of a tree
* Consists of all 4 traversal methods: printInOrder, printPostOrder printPreOrder & printLevelOrder
* printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT
* printLevelOrder: Prints by level (starting at root), from left to right.
*/
* The Node class which initializes a Node of a tree
* Consists of all 4 traversal methods: printInOrder, printPostOrder printPreOrder & printLevelOrder
* printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT
* printLevelOrder: Prints by level (starting at root), from left to right.
*/
class Node {
Node left, right;
int data;
@ -53,20 +53,17 @@ class Node {
this.data = data;
}
public void insert (int value) {
public void insert(int value) {
if (value < data) {
if (left == null) {
left = new Node(value);
}
else {
} else {
left.insert(value);
}
}
else {
} else {
if (right == null) {
right = new Node(value);
}
else {
} else {
right.insert(value);
}
}
@ -103,9 +100,9 @@ class Node {
}
/**
* O(n) time algorithm.
* Uses O(n) space to store nodes in a queue to aid in traversal.
*/
* O(n) time algorithm.
* Uses O(n) space to store nodes in a queue to aid in traversal.
*/
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);

View File

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

View File

@ -1,38 +1,37 @@
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
package DataStructures.Trees;
public class ValidBSTOrNot {
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
}
public class ValidBSTOrNot
{
//Root of the Binary Tree
Node root;
/* can give min and max value according to your code or
can write a function to find min and max value of tree. */
/* returns true if given search tree is binary
search tree (efficient version) */
boolean isBST() {
boolean isBST() {
return isBSTUtil(root, Integer.MIN_VALUE,
Integer.MAX_VALUE);
Integer.MAX_VALUE);
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
boolean isBSTUtil(Node node, int min, int max)
{
boolean isBSTUtil(Node node, int min, int max) {
/* an empty tree is BST */
if (node == null)
return true;
/* false if this node violates the min/max constraints */
if (node.data < min || node.data > max)
return false;
@ -40,23 +39,7 @@ public class ValidBSTOrNot
/* otherwise check the subtrees recursively
tightening the min/max constraints */
// Allow only distinct values
return (isBSTUtil(node.left, min, node.data-1) &&
isBSTUtil(node.right, node.data+1, max));
}
/* Driver program to test above functions */
public static void main(String args[])
{
ValidBSTOrNot tree = new ValidBSTOrNot();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
return (isBSTUtil(node.left, min, node.data - 1) &&
isBSTUtil(node.right, node.data + 1, max));
}
}