Restructured the folder
This commit is contained in:
parent
6d76e33c19
commit
3e999d9445
3
.gitignore
vendored
3
.gitignore
vendored
@ -1 +1,2 @@
|
||||
/bin/
|
||||
Java.iml
|
||||
out/
|
||||
|
@ -1,211 +0,0 @@
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class ClosestPair {
|
||||
static int count = 0;// array length
|
||||
static int secondCount = 0;// array length
|
||||
static Location array[] = new Location[10000];
|
||||
static Location point1 = null; // Minimum point coordinate
|
||||
static Location point2 = null; // Minimum point coordinate
|
||||
static double minNum = Double.MAX_VALUE;// Minimum point length
|
||||
|
||||
private static class Location { // Location class
|
||||
double x = 0, y = 0;
|
||||
|
||||
public Location(double x, double y) { //Save x, y coordinates
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
public static int xPartition(Location[] a, int first, int last) { // x-axis Quick Sorting
|
||||
Location pivot = a[last]; // pivot
|
||||
int pIndex = last;
|
||||
int i = first - 1;
|
||||
Location temp; // Temporarily store the value for position transformation
|
||||
for (int j = first; j <= last - 1; j++) {
|
||||
if (a[j].x <= pivot.x) { // Less than or less than pivot
|
||||
i++;
|
||||
temp = a[i]; // array[i] <-> array[j]
|
||||
a[i] = a[j];
|
||||
a[j] = temp;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
temp = a[i];// array[pivot] <-> array[i]
|
||||
a[i] = a[pIndex];
|
||||
a[pIndex] = temp;
|
||||
return i;// pivot index
|
||||
}
|
||||
public static int yPartition(Location[] a, int first, int last) { //y-axis Quick Sorting
|
||||
Location pivot = a[last]; // pivot
|
||||
int pIndex = last;
|
||||
int i = first - 1;
|
||||
Location temp; // Temporarily store the value for position transformation
|
||||
for (int j = first; j <= last - 1; j++) {
|
||||
if (a[j].y <= pivot.y) { // Less than or less than pivot
|
||||
i++;
|
||||
temp = a[i]; // array[i] <-> array[j]
|
||||
a[i] = a[j];
|
||||
a[j] = temp;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
temp = a[i];// array[pivot] <-> array[i]
|
||||
a[i] = a[pIndex];
|
||||
a[pIndex] = temp;
|
||||
return i;// pivot index
|
||||
}
|
||||
|
||||
public static void xQuickSort(Location[] a, int first, int last) { //x-axis Quick Sorting
|
||||
if (first < last) {
|
||||
int q = xPartition(a, first, last); // pivot
|
||||
xQuickSort(a, first, q - 1); // Left
|
||||
xQuickSort(a, q + 1, last); // Right
|
||||
}
|
||||
}
|
||||
|
||||
public static void yQuickSort(Location[] a, int first, int last) { //y-axis Quick Sorting
|
||||
if (first < last) {
|
||||
int q = yPartition(a, first, last); // pivot
|
||||
yQuickSort(a, first, q - 1); // Left
|
||||
yQuickSort(a, q + 1, last); // Right
|
||||
}
|
||||
}
|
||||
|
||||
public static double closestPair(Location[] a, int indexNum, int first, int last) {// closestPair
|
||||
Location divideArray[] = new Location[indexNum]; // array stored before divide
|
||||
System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy from previous array
|
||||
|
||||
int totalNum = indexNum; // number of coordinates in the divideArray array
|
||||
int divideX = indexNum / 2; // Intermediate value for divide
|
||||
Location leftArray[] = new Location[divideX]; //divide - left array
|
||||
Location rightArray[] = new Location[totalNum - divideX]; //divide - right array
|
||||
|
||||
if (indexNum <= 3) { // If the number of coordinates is 3 or less
|
||||
return bruteForce(divideArray);
|
||||
}
|
||||
System.arraycopy(divideArray, 0, leftArray, 0, divideX); //divide - left array
|
||||
System.arraycopy(divideArray, divideX, rightArray, 0, totalNum - divideX); //divide - right array
|
||||
|
||||
double minLeftArea = 0; //Minimum length of left array
|
||||
double minRightArea = 0; //Minimum length of right array
|
||||
double minValue = 0; //Minimum lengt
|
||||
|
||||
minLeftArea = closestPair(leftArray, divideX, 0, divideX - 1); // recursive closestPair
|
||||
minRightArea = closestPair(rightArray, totalNum - divideX, divideX, totalNum - divideX - 1);
|
||||
minValue = Math.min(minLeftArea, minRightArea);// window size (= minimum length)
|
||||
|
||||
// Create window
|
||||
for (int i = 0; i < totalNum; i++) { // Set the size for creating a window and creating a new array for the coordinates in the window
|
||||
double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x);
|
||||
if (xGap < minValue) {
|
||||
secondCount++; // size of the array
|
||||
} else {
|
||||
if (divideArray[i].x > divideArray[divideX].x) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Location firstWindow[] = new Location[secondCount]; // new array for coordinates in window
|
||||
int k = 0;
|
||||
for (int i = 0; i < totalNum; i++) {
|
||||
double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x);
|
||||
if (xGap < minValue) { // if it's inside a window
|
||||
firstWindow[k] = divideArray[i]; // put in an array
|
||||
k++;
|
||||
} else {
|
||||
if (divideArray[i].x > divideArray[divideX].x) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
yQuickSort(firstWindow, 0, secondCount - 1);// Sort by y coordinates
|
||||
/ * Coordinates in Window * /
|
||||
double length = 0;
|
||||
for (int i = 0; i < secondCount - 1; i++) { // size comparison within window
|
||||
for (int j = (i + 1); j < secondCount; j++) {
|
||||
double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x);
|
||||
double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y);
|
||||
if (yGap < minValue) {
|
||||
length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2));
|
||||
if (length < minValue) { // If the measured distance is less than the current minimum distance
|
||||
minValue = length;// Change minimum distance to current distance
|
||||
if (length < minNum) { // Conditional statement for registering final coordinate
|
||||
minNum = length;
|
||||
point1 = firstWindow[i];
|
||||
point2 = firstWindow[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
}
|
||||
secondCount = 0;
|
||||
return minValue;
|
||||
}
|
||||
|
||||
public static double bruteForce(Location[] array) { // When the number of coordinates is less than 3
|
||||
double minValue = Double.MAX_VALUE; // minimum distance
|
||||
double length = 0;
|
||||
double xGap = 0, yGap = 0; // Difference between x, y coordinates
|
||||
if (array.length == 2) { // When there are two coordinates
|
||||
xGap = (array[0].x - array[1].x); // Difference between x coordinates
|
||||
yGap = (array[0].y - array[1].y); // Difference between y coordinates
|
||||
length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // distance between coordinates
|
||||
if (length < minNum) { // Conditional statement for registering final coordinate
|
||||
minNum = length;
|
||||
point1 = array[0];
|
||||
point2 = array[1];
|
||||
}
|
||||
return length;
|
||||
} else if (array.length == 3) { // When there are 3 coordinates
|
||||
for (int i = 0; i < array.length - 1; i++) {
|
||||
for (int j = (i + 1); j < array.length; j++) {
|
||||
xGap = (array[i].x - array[j].x); // Difference between x coordinates
|
||||
yGap = (array[i].y - array[j].y); // Difference between y coordinates
|
||||
length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // distance between coordinates
|
||||
if (length < minValue) { // If the measured distance is less than the current minimum distance
|
||||
minValue = length; // Change minimum distance to current distance
|
||||
if (length < minNum) { // Conditional statement for registering final coordinate
|
||||
minNum = length;
|
||||
point1 = array[i];
|
||||
point2 = array[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return minValue;
|
||||
}
|
||||
return minValue;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// TODO Auto-generated method stub
|
||||
StringTokenizer token;
|
||||
|
||||
BufferedReader in = new BufferedReader(new FileReader("closest_data.txt"));
|
||||
//Input data consists of one x-coordinate and one y-coordinate
|
||||
String ch;
|
||||
|
||||
System.out.println("Input data");
|
||||
while ((ch = in.readLine()) != null) {
|
||||
token = new StringTokenizer(ch, " ");
|
||||
|
||||
array[count] = new Location(Double.parseDouble(token.nextToken()), Double.parseDouble(token.nextToken())); // put in an array
|
||||
count++; // the number of coordinates actually in the array
|
||||
System.out.println("x: "+array[count - 1].x + ", y: " + array[count - 1].y);
|
||||
}
|
||||
|
||||
xQuickSort(array, 0, count - 1); // Sorting by x value
|
||||
|
||||
double result; // minimum distance
|
||||
result = closestPair(array, count, 0, count - 1); // ClosestPair start
|
||||
System.out.println("Output Data");// minimum distance coordinates and distance output
|
||||
System.out.println("(" + point1.x + ", " + point1.y + ")");
|
||||
System.out.println("(" + point2.x + ", " + point2.y + ")");
|
||||
System.out.println("Minimum Distance : " + result);
|
||||
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
2 3
|
||||
2 16
|
||||
3 9
|
||||
6 3
|
||||
7 7
|
||||
9 12
|
||||
10 11
|
||||
15 2
|
||||
15 19
|
||||
16 11
|
||||
17 13
|
||||
19 4
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,108 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class HEncoder {
|
||||
|
||||
public HashMap<Character, String> encoder = new HashMap<>(); // in order to encode
|
||||
public HashMap<String, Character> decoder = new HashMap<>(); // in order to decode
|
||||
|
||||
private static class Node {
|
||||
|
||||
Character ch;
|
||||
Integer freq;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
public static final Nodecomparator Ctor = new Nodecomparator();
|
||||
|
||||
public static class Nodecomparator implements Comparator<Node> {
|
||||
|
||||
@Override
|
||||
public int compare(Node o1, Node o2) {
|
||||
return o2.freq - o1.freq;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public HEncoder(String feeder) {
|
||||
// 1. freq map
|
||||
HashMap<Character, Integer> freqmap = new HashMap<>();
|
||||
for (int i = 0; i < feeder.length(); ++i) {
|
||||
char ch = feeder.charAt(i);
|
||||
if (freqmap.containsKey(ch)) {
|
||||
freqmap.put(ch, freqmap.get(ch) + 1);
|
||||
} else {
|
||||
freqmap.put(ch, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. prepare the heap from keyset
|
||||
genericheap<Node> heap = new genericheap<Node>(Node.Ctor);
|
||||
ArrayList<Character> k = new ArrayList<>(freqmap.keySet());
|
||||
for (Character c : k) {
|
||||
Node n = new Node();
|
||||
n.ch = c;
|
||||
n.left = null;
|
||||
n.right = null;
|
||||
n.freq = freqmap.get(c);
|
||||
heap.add(n);
|
||||
}
|
||||
|
||||
// 3.Prepare tree, remove two , merge, add it back
|
||||
Node fn = new Node();
|
||||
while (heap.size() != 1) {
|
||||
Node n1 = heap.removeHP();
|
||||
Node n2 = heap.removeHP();
|
||||
fn = new Node();
|
||||
|
||||
fn.freq = n1.freq + n2.freq;
|
||||
fn.left = n1;
|
||||
fn.right = n2;
|
||||
|
||||
heap.add(fn);
|
||||
}
|
||||
|
||||
// 4. traverse
|
||||
|
||||
traverse(heap.removeHP(), "");
|
||||
}
|
||||
|
||||
private void traverse(Node node, String osf) {
|
||||
|
||||
if (node.left == null && node.right == null) {
|
||||
encoder.put(node.ch, osf);
|
||||
decoder.put(osf, node.ch);
|
||||
return;
|
||||
}
|
||||
traverse(node.left, osf + "0");
|
||||
traverse(node.right, osf + "1");
|
||||
|
||||
}
|
||||
|
||||
// compression work done here
|
||||
public String compress(String str) {
|
||||
String rv = "";
|
||||
for (int i = 0; i < str.length(); ++i) {
|
||||
rv += encoder.get(str.charAt(i));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
|
||||
//in order to decompress
|
||||
public String decompress(String str) {
|
||||
String s = "";
|
||||
String code = "";
|
||||
for (int i = 0; i < str.length(); ++i) {
|
||||
code += str.charAt(i);
|
||||
if (decoder.containsKey(code)) {
|
||||
s += decoder.get(code);
|
||||
code = "";
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
|
||||
public class compressclient {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
HEncoder h= new HEncoder("aaaabbbcccccccccccdddd");
|
||||
System.out.println(h.compress("aabccd"));
|
||||
System.out.println(h.decompress("101011000111"));
|
||||
}
|
||||
|
||||
}
|
@ -1,93 +0,0 @@
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
|
||||
public class genericheap<T> { // create a generic heap class <T> , where T can be of any type.
|
||||
|
||||
private ArrayList<T> data = new ArrayList<>();
|
||||
private Comparator<T> ctor;
|
||||
|
||||
public genericheap(Comparator<T> ctor) { // constructor to initialize the generic comparator
|
||||
this.ctor=ctor;
|
||||
}
|
||||
|
||||
public int size() { // returns the size of the arraylist data
|
||||
return data.size();
|
||||
}
|
||||
|
||||
public boolean isEmpty() { // checks whether the list is empty or not :: return true or false for the same
|
||||
return data.isEmpty();
|
||||
}
|
||||
|
||||
public void display() { //displays the list
|
||||
System.out.println(this.data);
|
||||
}
|
||||
|
||||
public void add(T integer) { // in this function we have added the <t> type object into the arraylist and called upheapify
|
||||
data.add(integer);
|
||||
upheapify(data.size() - 1);
|
||||
}
|
||||
|
||||
private void upheapify(int ci) {
|
||||
if (ci == 0) {
|
||||
return;
|
||||
}
|
||||
int pi = (ci - 1) / 2;
|
||||
if (isLarger(ci,pi) == true) {
|
||||
swap(ci, pi);
|
||||
upheapify(pi);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isLarger(int i, int j) {
|
||||
T ith = data.get(i);
|
||||
T jth = data.get(j);
|
||||
if(ctor.compare(ith,jth)>0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void swap(int ci, int pi) { // swap function written like this because of the generic property
|
||||
T ith = data.get(ci);
|
||||
T jth=data.get(pi);
|
||||
data.set(ci, jth);
|
||||
data.set(pi, ith);
|
||||
}
|
||||
|
||||
public T getHP() {
|
||||
return data.get(0);
|
||||
}
|
||||
|
||||
public T removeHP() {
|
||||
|
||||
swap(0, data.size() - 1);
|
||||
T rv=data.remove(data.size()-1);
|
||||
downheapify(0);
|
||||
return rv;
|
||||
}
|
||||
|
||||
private void downheapify(int pi) {
|
||||
int lci = 2 * pi + 1;
|
||||
int rci = 2 * pi + 2;
|
||||
|
||||
int max = pi;
|
||||
|
||||
if (lci < data.size() && isLarger(lci, max) == true) {
|
||||
max = lci;
|
||||
}
|
||||
if (rci < data.size() && isLarger(rci, max) == true) {
|
||||
max = rci;
|
||||
}
|
||||
if (max != pi) {
|
||||
swap(pi, max);
|
||||
downheapify(max);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,130 +0,0 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Class for converting from "any" base to "any" other base, when "any" means from 2-36.
|
||||
* Works by going from base 1 to decimal to base 2. Includes auxiliary method for
|
||||
* determining whether a number is valid for a given base.
|
||||
*
|
||||
* @author Michael Rolland
|
||||
* @version 2017.10.10
|
||||
*
|
||||
*/
|
||||
public class AnyBaseToAnyBase {
|
||||
|
||||
// Smallest and largest base you want to accept as valid input
|
||||
static final int MINIMUM_BASE = 2;
|
||||
static final int MAXIMUM_BASE = 36;
|
||||
|
||||
// Driver
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
String n;
|
||||
int b1=0,b2=0;
|
||||
while (true) {
|
||||
try {
|
||||
System.out.print("Enter number: ");
|
||||
n = in.next();
|
||||
System.out.print("Enter beginning base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): ");
|
||||
b1 = in.nextInt();
|
||||
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
continue;
|
||||
}
|
||||
if (!validForBase(n, b1)) {
|
||||
System.out.println("The number is invalid for this base!");
|
||||
continue;
|
||||
}
|
||||
System.out.print("Enter end base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): ");
|
||||
b2 = in.nextInt();
|
||||
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
} catch (InputMismatchException e) {
|
||||
System.out.println("Invalid input.");
|
||||
in.next();
|
||||
}
|
||||
}
|
||||
System.out.println(base2base(n, b1, b2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a number (as a String) is valid for a given base.
|
||||
*/
|
||||
public static boolean validForBase(String n, int base) {
|
||||
char[] validDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
|
||||
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
|
||||
'W', 'X', 'Y', 'Z'};
|
||||
// digitsForBase contains all the valid digits for the base given
|
||||
char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);
|
||||
|
||||
// Convert character array into set for convenience of contains() method
|
||||
HashSet<Character> digitsList = new HashSet();
|
||||
for (int i=0; i<digitsForBase.length; i++)
|
||||
digitsList.add(digitsForBase[i]);
|
||||
|
||||
// Check that every digit in n is within the list of valid digits for that base.
|
||||
for (char c : n.toCharArray())
|
||||
if (!digitsList.contains(c))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to convert any integer from base b1 to base b2. Works by converting from b1 to decimal,
|
||||
* then decimal to b2.
|
||||
* @param n The integer to be converted.
|
||||
* @param b1 Beginning base.
|
||||
* @param b2 End base.
|
||||
* @return n in base b2.
|
||||
*/
|
||||
public static String base2base(String n, int b1, int b2) {
|
||||
// Declare variables: decimal value of n,
|
||||
// character of base b1, character of base b2,
|
||||
// and the string that will be returned.
|
||||
int decimalValue = 0, charB2;
|
||||
char charB1;
|
||||
String output="";
|
||||
// Go through every character of n
|
||||
for (int i=0; i<n.length(); i++) {
|
||||
// store the character in charB1
|
||||
charB1 = n.charAt(i);
|
||||
// if it is a non-number, convert it to a decimal value >9 and store it in charB2
|
||||
if (charB1 >= 'A' && charB1 <= 'Z')
|
||||
charB2 = 10 + (charB1 - 'A');
|
||||
// Else, store the integer value in charB2
|
||||
else
|
||||
charB2 = charB1 - '0';
|
||||
// Convert the digit to decimal and add it to the
|
||||
// decimalValue of n
|
||||
decimalValue = decimalValue * b1 + charB2;
|
||||
}
|
||||
|
||||
// Converting the decimal value to base b2:
|
||||
// A number is converted from decimal to another base
|
||||
// by continuously dividing by the base and recording
|
||||
// the remainder until the quotient is zero. The number in the
|
||||
// new base is the remainders, with the last remainder
|
||||
// being the left-most digit.
|
||||
|
||||
// While the quotient is NOT zero:
|
||||
while (decimalValue != 0) {
|
||||
// If the remainder is a digit < 10, simply add it to
|
||||
// the left side of the new number.
|
||||
if (decimalValue % b2 < 10)
|
||||
output = Integer.toString(decimalValue % b2) + output;
|
||||
// If the remainder is >= 10, add a character with the
|
||||
// corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
|
||||
else
|
||||
output = (char)((decimalValue % b2)+55) + output;
|
||||
// Divide by the new base again
|
||||
decimalValue /= b2;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// Driver program
|
||||
public class AnyBaseToDecimal {
|
||||
public static void main (String[] args) throws Exception{
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
|
||||
String inp = br.readLine();
|
||||
int base = Integer.parseInt(br.readLine());
|
||||
|
||||
System.out.println("Input in base " + base + " is: " + inp);
|
||||
System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base));
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces a decimal value of any given input number of any base
|
||||
* @param inp_num String of which we need the decimal value and base in integer format
|
||||
* @return string format of the decimal value
|
||||
*/
|
||||
|
||||
public static String convertToDecimal(String inp_num, int base) {
|
||||
int len = inp_num.length();
|
||||
int num = 0;
|
||||
int pow = 1;
|
||||
|
||||
for (int i=len-1; i>=0; i--) {
|
||||
if (valOfChar(inp_num.charAt(i)) >= base) {
|
||||
return "Invalid Number";
|
||||
}
|
||||
num += valOfChar(inp_num.charAt(i))*pow;
|
||||
pow *= base;
|
||||
}
|
||||
return String.valueOf(num);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces integer value of the input character and returns it
|
||||
* @param c Char of which we need the integer value of
|
||||
* @return integer value of input char
|
||||
*/
|
||||
|
||||
public static int valOfChar(char c) {
|
||||
if (c >= '0' && c <= '9') {
|
||||
return (int)c - '0';
|
||||
}
|
||||
else {
|
||||
return (int)c - 'A' + 10;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package Java.Conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
//given a source number , source base, destination base, this code can give you the destination number.
|
||||
//sn ,sb,db ---> ()dn . this is what we have to do .
|
||||
|
||||
public class AnytoAny {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int sn = scn.nextInt();
|
||||
int sb = scn.nextInt();
|
||||
int db = scn.nextInt();
|
||||
int m = 1, dec = 0, dn = 0;
|
||||
while (sn != 0) {
|
||||
dec = dec + (sn % 10) * m;
|
||||
m *= sb;
|
||||
sn /= 10;
|
||||
}
|
||||
m = 1;
|
||||
while (dec != 0) {
|
||||
dn = dn + (dec % db) * m;
|
||||
m *= 10;
|
||||
dec /= db;
|
||||
}
|
||||
System.out.println(dn);
|
||||
}
|
||||
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Binary number to a Decimal number
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class BinaryToDecimal
|
||||
{
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,k,d,s=0,c=0;
|
||||
System.out.print("Binary number: ");
|
||||
n=sc.nextInt();
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%10;
|
||||
s+=d*(int)Math.pow(2,c++);
|
||||
k/=10;
|
||||
}
|
||||
System.out.println("Decimal equivalent:"+s);
|
||||
sc.close();
|
||||
}
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
import java.util.*;
|
||||
/**
|
||||
* Converts any Binary Number to a Hexadecimal Number
|
||||
*
|
||||
* @author Nishita Aggarwal
|
||||
*
|
||||
*/
|
||||
public class BinaryToHexadecimal {
|
||||
|
||||
/**
|
||||
* This method converts a binary number to
|
||||
* a hexadecimal number.
|
||||
*
|
||||
* @param binary The binary number
|
||||
* @return The hexadecimal number
|
||||
*/
|
||||
static String binToHex(int binary)
|
||||
{
|
||||
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
|
||||
HashMap<Integer,String> hm=new HashMap<>();
|
||||
//String to store hexadecimal code
|
||||
String hex="";
|
||||
int i;
|
||||
for(i=0 ; i<10 ; i++)
|
||||
{
|
||||
hm.put(i, String.valueOf(i));
|
||||
}
|
||||
for(i=10 ; i<16 ; i++) hm.put(i,String.valueOf((char)('A'+i-10)));
|
||||
int currbit;
|
||||
while(binary != 0)
|
||||
{
|
||||
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
|
||||
for(i=0 ; i<4 ; i++)
|
||||
{
|
||||
currbit = binary % 10;
|
||||
binary = binary / 10;
|
||||
code4 += currbit * Math.pow(2, i);
|
||||
}
|
||||
hex= hm.get(code4) + hex;
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter binary number:");
|
||||
int binary = sc.nextInt();
|
||||
String hex = binToHex(binary);
|
||||
System.out.println("Hexadecimal Code:" + hex);
|
||||
sc.close();
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Binary number to an Octal Number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class BinaryToOctal {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int b = sc.nextInt();
|
||||
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
|
||||
sc.close();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a binary number to
|
||||
* an octal number.
|
||||
*
|
||||
* @param b The binary number
|
||||
* @return The octal number
|
||||
*/
|
||||
public static int convertBinaryToOctal(int b) {
|
||||
int o = 0, r=0, j =1 ;
|
||||
while(b!=0)
|
||||
{
|
||||
r = b % 10;
|
||||
o = o + r * j;
|
||||
j = j * 2;
|
||||
b = b / 10;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Decimal number to a Binary number
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class DecimalToBinary {
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command Line Arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
conventionalConversion();
|
||||
bitwiseConversion();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a decimal number
|
||||
* to a binary number using a conventional
|
||||
* algorithm.
|
||||
*/
|
||||
public static void conventionalConversion() {
|
||||
int n, b = 0, c = 0, d;
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
|
||||
n = input.nextInt();
|
||||
while (n != 0) {
|
||||
d = n % 2;
|
||||
b = b + d * (int) Math.pow(10, c++);
|
||||
n /= 2;
|
||||
} //converting decimal to binary
|
||||
System.out.println("\tBinary number: " + b);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a decimal number
|
||||
* to a binary number using a bitwise
|
||||
* algorithm
|
||||
*/
|
||||
public static void bitwiseConversion() {
|
||||
int n, b = 0, c = 0, d;
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.printf("Bitwise conversion.\n\tEnter the decimal number: ");
|
||||
n = input.nextInt();
|
||||
while (n != 0) {
|
||||
d = (n & 1);
|
||||
b += d * (int) Math.pow(10, c++);
|
||||
n >>= 1;
|
||||
}
|
||||
System.out.println("\tBinary number: " + b);
|
||||
}
|
||||
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
|
||||
class DecimalToHexaDecimal {
|
||||
private static final int sizeOfIntInHalfBytes = 8;
|
||||
private static final int numberOfBitsInAHalfByte = 4;
|
||||
private static final int halfByte = 0x0F;
|
||||
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
|
||||
'F' };
|
||||
|
||||
// Returns the hex value of the dec entered in the parameter.
|
||||
public static String decToHex(int dec) {
|
||||
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
|
||||
hexBuilder.setLength(sizeOfIntInHalfBytes);
|
||||
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
|
||||
int j = dec & halfByte;
|
||||
hexBuilder.setCharAt(i, hexDigits[j]);
|
||||
dec >>= numberOfBitsInAHalfByte;
|
||||
}
|
||||
return hexBuilder.toString().toLowerCase();
|
||||
}
|
||||
|
||||
// Test above function.
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Test...");
|
||||
int dec = 305445566;
|
||||
String libraryDecToHex = Integer.toHexString(dec);
|
||||
String decToHex = decToHex(dec);
|
||||
System.out.println("Result from the library : " + libraryDecToHex);
|
||||
System.out.println("Result decToHex method : " + decToHex);
|
||||
}
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts Decimal numbers to Octal Numbers
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Decimal_Octal
|
||||
{
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line Arguments
|
||||
*/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,k,d,s=0,c=0;
|
||||
System.out.print("Decimal number: ");
|
||||
n=sc.nextInt();
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%8;
|
||||
s+=d*(int)Math.pow(10,c++);
|
||||
k/=8;
|
||||
}
|
||||
|
||||
System.out.println("Octal equivalent:"+s);
|
||||
sc.close();
|
||||
}
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
/**
|
||||
+ * Converts any Hexadecimal Number to Octal
|
||||
+ *
|
||||
+ * @author Tanmay Joshi
|
||||
+ *
|
||||
+ */
|
||||
import java.util.Scanner;
|
||||
|
||||
public class HexToOct
|
||||
{
|
||||
/**
|
||||
+ * This method converts a Hexadecimal number to
|
||||
+ * a decimal number
|
||||
+ *
|
||||
+ * @param The Hexadecimal Number
|
||||
+ * @return The Decimal number
|
||||
+ */
|
||||
public static int hex2decimal(String s)
|
||||
{
|
||||
String str = "0123456789ABCDEF";
|
||||
s = s.toUpperCase();
|
||||
int val = 0;
|
||||
for (int i = 0; i < s.length(); i++)
|
||||
{
|
||||
char a = s.charAt(i);
|
||||
int n = str.indexOf(a);
|
||||
val = 16*val + n;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
+ * This method converts a Decimal number to
|
||||
+ * a octal number
|
||||
+ *
|
||||
+ * @param The Decimal Number
|
||||
+ * @return The Octal number
|
||||
+ */
|
||||
public static int decimal2octal(int q)
|
||||
{
|
||||
int now;
|
||||
int i=1;
|
||||
int octnum=0;
|
||||
while(q>0)
|
||||
{
|
||||
now=q%8;
|
||||
octnum=(now*(int)(Math.pow(10,i)))+octnum;
|
||||
q/=8;
|
||||
i++;
|
||||
}
|
||||
octnum/=10;
|
||||
return octnum;
|
||||
}
|
||||
// Main method that gets the hex input from user and converts it into octal.
|
||||
public static void main(String args[])
|
||||
{
|
||||
String hexadecnum;
|
||||
int decnum,octalnum;
|
||||
Scanner scan = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter Hexadecimal Number : ");
|
||||
hexadecnum = scan.nextLine();
|
||||
|
||||
// first convert hexadecimal to decimal
|
||||
|
||||
decnum = hex2decimal(hexadecnum); //Pass the string to the hex2decimal function and get the decimal form in variable decnum
|
||||
|
||||
// convert decimal to octal
|
||||
octalnum=decimal2octal(decnum);
|
||||
System.out.println("Number in octal: "+octalnum);
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
import java.lang.StringBuilder;
|
||||
import java.util.*;
|
||||
import java.util.Scanner;
|
||||
import javax.swing.*;
|
||||
|
||||
public class HexaDecimalToBinary {
|
||||
|
||||
private final int LONG_BITS = 8;
|
||||
|
||||
public void convert(String numHex) {
|
||||
//String a HexaDecimal:
|
||||
int conHex = Integer.parseInt(numHex, 16);
|
||||
//Hex a Binary:
|
||||
String binary = Integer.toBinaryString(conHex);
|
||||
//Presentation:
|
||||
System.out.println(numHex + " = " + completeDigits(binary));
|
||||
}
|
||||
|
||||
public String completeDigits(String binNum) {
|
||||
for (int i = binNum.length(); i < LONG_BITS; i++) {
|
||||
binNum = "0" + binNum;
|
||||
}
|
||||
return binNum;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Testing Numbers:
|
||||
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB",
|
||||
"19", "01", "02", "03", "04"};
|
||||
HexaDecimalToBinary objConvert = new HexaDecimalToBinary();
|
||||
|
||||
for (String num : hexNums) {
|
||||
objConvert.convert(num);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
package Conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class HexaDecimalToDecimal {
|
||||
|
||||
// convert hexadecimal to decimal
|
||||
public static int getHexaToDec(String hex){
|
||||
String digits = "012345678910ABCDEFF";
|
||||
hex = hex.toUpperCase();
|
||||
int val = 0;
|
||||
for (int i = 0; i < hex.length(); i++)
|
||||
{
|
||||
int d = digits.indexOf(hex.charAt(i));
|
||||
val = 16*val + d;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
// Main method gets the hexadecimal input from user and converts it into Decimal output.
|
||||
|
||||
public static void main(String args[])
|
||||
{
|
||||
String hexa_Input;
|
||||
int dec_output;
|
||||
Scanner scan = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter Hexadecimal Number : ");
|
||||
hexa_Input = scan.nextLine();
|
||||
|
||||
// convert hexadecimal to decimal
|
||||
|
||||
dec_output = getHexaToDec(hexa_Input);
|
||||
/*
|
||||
Pass the string to the getHexaToDec function
|
||||
and it returns the decimal form in the variable dec_output.
|
||||
*/
|
||||
System.out.println("Number in Decimal: "+dec_output);
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal number to a Binary number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class OctalToBinary {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int o = sc.nextInt();
|
||||
System.out.println("Binary equivalent: " + convertOctalToBinary(o));
|
||||
sc.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts an octal number
|
||||
* to a binary number.
|
||||
*
|
||||
* @param o The octal number
|
||||
* @return The binary number
|
||||
*/
|
||||
public static int convertOctalToBinary(int o) {
|
||||
Scanner scan;
|
||||
int num;
|
||||
|
||||
void getVal() {
|
||||
|
||||
System.out.println("Octal to Binary");
|
||||
scan = new Scanner(System.in);
|
||||
// Entering the needed number
|
||||
System.out.println("\nEnter the number : ");
|
||||
num = Integer.parseInt(scan.nextLine(), 8);
|
||||
}
|
||||
|
||||
void convert() {
|
||||
|
||||
String binary = Integer.toBinaryString(num);
|
||||
System.out.println("Binary Value is : " + binary);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal Number to a Decimal Number
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*
|
||||
*/
|
||||
public class OctalToDecimal {
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args
|
||||
* Command line arguments
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.print("Octal Input: ");
|
||||
String inputOctal = sc.nextLine();
|
||||
int result = convertOctalToDecimal(inputOctal);
|
||||
if (result != -1)
|
||||
System.out.println("Result convertOctalToDecimal : " + result);
|
||||
sc.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts an octal number to a decimal number.
|
||||
*
|
||||
* @param inputOctal
|
||||
* The octal number
|
||||
* @return The decimal number
|
||||
*/
|
||||
public static int convertOctalToDecimal(String inputOctal) {
|
||||
|
||||
try {
|
||||
// Actual conversion of Octal to Decimal:
|
||||
Integer outputDecimal = Integer.parseInt(inputOctal, 8);
|
||||
return outputDecimal;
|
||||
} catch (NumberFormatException ne) {
|
||||
// Printing a warning message if the input is not a valid octal
|
||||
// number:
|
||||
System.out.println("Invalid Input, Expecting octal number 0-7");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
/**
|
||||
+ + * Converts any Octal Number to HexaDecimal
|
||||
+ + *
|
||||
+ + * @author Tanmay Joshi
|
||||
+ + *
|
||||
+ + *
|
||||
**/
|
||||
import java.util.Scanner;
|
||||
|
||||
public class OctalToHexadecimal {
|
||||
|
||||
/**
|
||||
+ + * This method converts a Octal number to
|
||||
+ + * a decimal number
|
||||
+ + *
|
||||
+ + * @param The Octal Number
|
||||
+ + * @return The Decimal number
|
||||
+ + */
|
||||
public static int OctToDec(String s)
|
||||
{
|
||||
int i =0;
|
||||
for(int j =0;j<s.length();j++)
|
||||
{
|
||||
char num = s.charAt(j);
|
||||
num-='0';
|
||||
i*=8;
|
||||
i+=num;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
+ + * This method converts a Decimal number to
|
||||
+ + * a Hexadecimal number
|
||||
+ + *
|
||||
+ + * @param The Decimal Number
|
||||
+ + * @return The Hexadecimal number
|
||||
+ + */
|
||||
public static String DecimalToHex(int d) {
|
||||
String digits = "0123456789ABCDEF";
|
||||
if (d <= 0)
|
||||
return "0";
|
||||
String hex = "";
|
||||
while (d > 0) {
|
||||
int digit = d % 16;
|
||||
hex = digits.charAt(digit) + hex;
|
||||
d = d / 16;
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
//Driver Program
|
||||
public static void main ( String args[]) {
|
||||
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter the Octal number: ");
|
||||
String oct = input.next(); //Take octal number as input from user in a string
|
||||
int decimal = OctToDec(oct); //Pass the octal number to function and get converted deciaml form
|
||||
String hex = DecimalToHex(decimal); //Pass the decimla number to function and get converted Hex form of the number
|
||||
System.out.println("The Hexadecimal equivalant is: "+hex);
|
||||
}
|
||||
}
|
||||
|
@ -1,126 +0,0 @@
|
||||
package 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 static class Node<Element> {
|
||||
private Element content;
|
||||
private Node<Element> nextElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return an iterator that iterates over the elements in this bag in arbitrary order
|
||||
*/
|
||||
public Iterator<Element> iterator() {
|
||||
return new ListIterator<>(firstElement);
|
||||
}
|
||||
|
||||
@SuppressWarnings("hiding")
|
||||
private class ListIterator<Element> implements Iterator<Element> {
|
||||
private Node<Element> currentElement;
|
||||
|
||||
public ListIterator(Node<Element> firstElement) {
|
||||
currentElement = firstElement;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return currentElement != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove is not allowed in a bag
|
||||
*/
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Element next() {
|
||||
if (!hasNext())
|
||||
throw new NoSuchElementException();
|
||||
Element element = currentElement.content;
|
||||
currentElement = currentElement.nextElement;
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* main-method for testing
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Bag<String> bag = new Bag<>();
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
@ -1,124 +0,0 @@
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class CircularBuffer {
|
||||
private char[] _buffer;
|
||||
public final int _buffer_size;
|
||||
private int _write_index = 0;
|
||||
private int _read_index = 0;
|
||||
private AtomicInteger _readable_data = new AtomicInteger(0);
|
||||
|
||||
public CircularBuffer(int buffer_size) {
|
||||
if(!IsPowerOfTwo(buffer_size)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
this._buffer_size = buffer_size;
|
||||
_buffer = new char[buffer_size];
|
||||
}
|
||||
|
||||
private boolean IsPowerOfTwo(int i) {
|
||||
return (i & (i - 1)) == 0;
|
||||
}
|
||||
|
||||
private int getTrueIndex(int i) {
|
||||
return i % _buffer_size;
|
||||
}
|
||||
|
||||
public Character readOutChar() {
|
||||
Character result = null;
|
||||
|
||||
//if we have data to read
|
||||
if(_readable_data.get() > 0) {
|
||||
result = new Character(_buffer[getTrueIndex(_read_index)]);
|
||||
_readable_data.decrementAndGet();
|
||||
_read_index++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean writeToCharBuffer(char c) {
|
||||
boolean result = false;
|
||||
|
||||
//if we can write to the buffer
|
||||
if(_readable_data.get() < _buffer_size) {
|
||||
//write to buffer
|
||||
_buffer[getTrueIndex(_write_index)] = c;
|
||||
_readable_data.incrementAndGet();
|
||||
_write_index++;
|
||||
result = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class TestWriteWorker implements Runnable {
|
||||
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
Random _random = new Random();
|
||||
CircularBuffer _buffer;
|
||||
public TestWriteWorker(CircularBuffer cb) {
|
||||
this._buffer = cb;
|
||||
}
|
||||
|
||||
private char getRandomChar() {
|
||||
return _alphabet.charAt(_random.nextInt(_alphabet.length()));
|
||||
}
|
||||
|
||||
public void run() {
|
||||
while(!Thread.interrupted()) {
|
||||
if(!_buffer.writeToCharBuffer(getRandomChar())){
|
||||
Thread.yield();
|
||||
try{
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestReadWorker implements Runnable {
|
||||
CircularBuffer _buffer;
|
||||
public TestReadWorker(CircularBuffer cb) {
|
||||
this._buffer = cb;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
System.out.println("Printing Buffer:");
|
||||
while(!Thread.interrupted()) {
|
||||
Character c = _buffer.readOutChar();
|
||||
if(c != null) {
|
||||
System.out.print(c.charValue());
|
||||
} else {
|
||||
Thread.yield();
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int buffer_size = 1024;
|
||||
//create circular buffer
|
||||
CircularBuffer cb = new CircularBuffer(buffer_size);
|
||||
|
||||
//create threads that read and write the buffer.
|
||||
Thread write_thread = new Thread(new TestWriteWorker(cb));
|
||||
Thread read_thread = new Thread(new TestReadWorker(cb));
|
||||
read_thread.start();
|
||||
write_thread.start();
|
||||
|
||||
//wait some amount of time
|
||||
Thread.sleep(10000);
|
||||
|
||||
//interrupt threads and exit
|
||||
write_thread.interrupt();
|
||||
read_thread.interrupt();
|
||||
}
|
||||
}
|
@ -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 = seperator;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @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!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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
@ -1,3 +0,0 @@
|
||||
id, height, width
|
||||
1, 65.78331, 112.9925
|
||||
12, 67.62333, 114.143
|
|
@ -1 +0,0 @@
|
||||
id, height, width
|
|
@ -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,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();
|
||||
}
|
||||
}
|
@ -1,158 +0,0 @@
|
||||
import java.util.*;
|
||||
class BellmanFord
|
||||
/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
|
||||
start vertex, end vertes and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/
|
||||
{
|
||||
int vertex,edge;
|
||||
private Edge edges[];
|
||||
private int index=0;
|
||||
BellmanFord(int v,int e)
|
||||
{
|
||||
vertex=v;
|
||||
edge=e;
|
||||
edges=new Edge[e];
|
||||
}
|
||||
class Edge
|
||||
{
|
||||
int u,v;
|
||||
int w;
|
||||
/**
|
||||
*@param u Source Vertex
|
||||
* @param v End vertex
|
||||
* @param c Weight
|
||||
*/
|
||||
Edge(int a,int b,int c)
|
||||
{
|
||||
u=a;
|
||||
v=b;
|
||||
w=c;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param p[] Parent array which shows updates in edges
|
||||
* @param i Current vertex under consideration
|
||||
*/
|
||||
void printPath(int p[],int i)
|
||||
{
|
||||
if(p[i]==-1)//Found the path back to parent
|
||||
return;
|
||||
printPath(p,p[i]);
|
||||
System.out.print(i+" ");
|
||||
}
|
||||
public static void main(String args[])
|
||||
{
|
||||
BellmanFord obj=new BellmanFord(0,0);//Dummy object to call nonstatic variables
|
||||
obj.go();
|
||||
}
|
||||
public void go()//Interactive run for understanding the class first time. Assumes source vertex is 0 and shows distaance to all vertices
|
||||
{
|
||||
Scanner sc=new Scanner(System.in);//Grab scanner object for user input
|
||||
int i,v,e,u,ve,w,j,neg=0;
|
||||
System.out.println("Enter no. of vertices and edges please");
|
||||
v=sc.nextInt();
|
||||
e=sc.nextInt();
|
||||
Edge arr[]=new Edge[e];//Array of edges
|
||||
System.out.println("Input edges");
|
||||
for(i=0;i<e;i++)
|
||||
{
|
||||
u=sc.nextInt();
|
||||
ve=sc.nextInt();
|
||||
w=sc.nextInt();
|
||||
arr[i]=new Edge(u,ve,w);
|
||||
}
|
||||
int dist[]=new int[v];//Distance array for holding the finalized shortest path distance between source and all vertices
|
||||
int p[]=new int[v];//Parent array for holding the paths
|
||||
for(i=0;i<v;i++)
|
||||
dist[i]=Integer.MAX_VALUE;//Initializing distance values
|
||||
dist[0]=0;
|
||||
p[0]=-1;
|
||||
for(i=0;i<v-1;i++)
|
||||
{
|
||||
for(j=0;j<e;j++)
|
||||
{
|
||||
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
|
||||
{
|
||||
dist[arr[j].v]=dist[arr[j].u]+arr[j].w;//Update
|
||||
p[arr[j].v]=arr[j].u;
|
||||
}
|
||||
}
|
||||
}
|
||||
//Final cycle for negative checking
|
||||
for(j=0;j<e;j++)
|
||||
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
|
||||
{
|
||||
neg=1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
if(neg==0)//Go ahead and show results of computaion
|
||||
{
|
||||
System.out.println("Distances are: ");
|
||||
for(i=0;i<v;i++)
|
||||
System.out.println(i+" "+dist[i]);
|
||||
System.out.println("Path followed:");
|
||||
for(i=0;i<v;i++)
|
||||
{
|
||||
System.out.print("0 ");
|
||||
printPath(p,i);
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @param source Starting vertex
|
||||
* @param end Ending vertex
|
||||
* @param Edge Array of edges
|
||||
*/
|
||||
public void show(int source,int end, Edge arr[])//Just shows results of computation, if graph is passed to it. The graph should
|
||||
//be created by using addEdge() method and passed by calling getEdgeArray() method
|
||||
{
|
||||
int i,j,v=vertex,e=edge,neg=0;
|
||||
double dist[]=new double[v];//Distance array for holding the finalized shortest path distance between source and all vertices
|
||||
int p[]=new int[v];//Parent array for holding the paths
|
||||
for(i=0;i<v;i++)
|
||||
dist[i]=Integer.MAX_VALUE;//Initializing distance values
|
||||
dist[source]=0;
|
||||
p[source]=-1;
|
||||
for(i=0;i<v-1;i++)
|
||||
{
|
||||
for(j=0;j<e;j++)
|
||||
{
|
||||
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
|
||||
{
|
||||
dist[arr[j].v]=dist[arr[j].u]+arr[j].w;//Update
|
||||
p[arr[j].v]=arr[j].u;
|
||||
}
|
||||
}
|
||||
}
|
||||
//Final cycle for negative checking
|
||||
for(j=0;j<e;j++)
|
||||
if((int)dist[arr[j].u]!=Integer.MAX_VALUE&&dist[arr[j].v]>dist[arr[j].u]+arr[j].w)
|
||||
{
|
||||
neg=1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
if(neg==0)//Go ahead and show results of computaion
|
||||
{
|
||||
System.out.println("Distance is: "+dist[end]);
|
||||
System.out.println("Path followed:");
|
||||
System.out.print(source+" ");
|
||||
printPath(p,end);
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
/**
|
||||
*@param x Source Vertex
|
||||
* @param y End vertex
|
||||
* @param z Weight
|
||||
*/
|
||||
public void addEdge(int x,int y,int z)//Adds unidirectionl Edge
|
||||
{
|
||||
edges[index++]=new Edge(x,y,z);
|
||||
}
|
||||
public Edge[] getEdgeArray()
|
||||
{
|
||||
return edges;
|
||||
}
|
||||
}
|
@ -1,150 +0,0 @@
|
||||
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
|
||||
*
|
||||
*/
|
||||
class Graph<E extends Comparable<E>> {
|
||||
|
||||
class Node {
|
||||
E name;
|
||||
|
||||
public Node(E name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
class Edge {
|
||||
Node startNode, endNode;
|
||||
|
||||
public Edge(Node startNode, Node endNode) {
|
||||
this.startNode = startNode;
|
||||
this.endNode = endNode;
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<Edge> edgeList;
|
||||
ArrayList<Node> nodeList;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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>();
|
||||
|
||||
for (Node n : nodeList) {
|
||||
if (!markedNodes.contains(n)) {
|
||||
markedNodes.add(n);
|
||||
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public class ConnectedComponent {
|
||||
|
||||
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 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());
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
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
|
||||
{
|
||||
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++)
|
||||
{
|
||||
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[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;
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("The Transitive Closure of the Graph");
|
||||
FloydWarshall floydwarshall = new FloydWarshall(numberofvertices);
|
||||
floydwarshall.floydwarshall(adjacency_matrix);
|
||||
scan.close();
|
||||
}
|
||||
}
|
@ -1,129 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
import java.lang.StringBuilder;
|
||||
|
||||
class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
|
||||
ArrayList<Vertex> verticies;
|
||||
|
||||
public AdjacencyListGraph() {
|
||||
verticies = new ArrayList<>();
|
||||
}
|
||||
|
||||
private class Vertex {
|
||||
E data;
|
||||
ArrayList<Vertex> adjacentVerticies;
|
||||
|
||||
public Vertex(E data) {
|
||||
adjacentVerticies = new ArrayList<>();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public boolean addAdjacentVertex(Vertex to) {
|
||||
for (Vertex v: adjacentVerticies) {
|
||||
if (v.data.compareTo(to.data) == 0) {
|
||||
return false; // the edge already exists
|
||||
}
|
||||
}
|
||||
return adjacentVerticies.add(to); // this will return true;
|
||||
}
|
||||
|
||||
public boolean removeAdjacentVertex(E to) {
|
||||
// use indexes here so it is possible to
|
||||
// remove easily without implementing
|
||||
// equals method that ArrayList.remove(Object o) uses
|
||||
for (int i = 0; i < adjacentVerticies.size(); i++) {
|
||||
if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
|
||||
adjacentVerticies.remove(i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* this method removes an edge from the graph between two specified
|
||||
* verticies
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
|
||||
*/
|
||||
public boolean removeEdge(E from, E to) {
|
||||
Vertex fromV = null;
|
||||
for (Vertex v: verticies) {
|
||||
if (from.compareTo(v.data) == 0) {
|
||||
fromV = v;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (fromV == null) return false;
|
||||
return fromV.removeAdjacentVertex(to);
|
||||
}
|
||||
/**
|
||||
* this method adds an edge to the graph between two specified
|
||||
* verticies
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @return returns true if the edge did not exist, return false if it already did
|
||||
*/
|
||||
public boolean addEdge(E from, E to) {
|
||||
Vertex fromV = null, toV = null;
|
||||
for (Vertex v: verticies) {
|
||||
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
|
||||
fromV = v;
|
||||
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
|
||||
toV = v;
|
||||
}
|
||||
if (fromV != null && toV != null) break; // both nodes exist so stop searching
|
||||
}
|
||||
if (fromV == null) {
|
||||
fromV = new Vertex(from);
|
||||
verticies.add(fromV);
|
||||
}
|
||||
if (toV == null) {
|
||||
toV = new Vertex(to);
|
||||
verticies.add(toV);
|
||||
}
|
||||
return fromV.addAdjacentVertex(toV);
|
||||
}
|
||||
|
||||
/**
|
||||
* this gives a list of verticies in the graph and their adjacencies
|
||||
*
|
||||
* @return returns a string describing this graph
|
||||
*/
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Vertex v: verticies) {
|
||||
sb.append("Vertex: ");
|
||||
sb.append(v.data);
|
||||
sb.append("\n");
|
||||
sb.append("Adjacent verticies: ");
|
||||
for (Vertex v2: v.adjacentVerticies) {
|
||||
sb.append(v2.data);
|
||||
sb.append(" ");
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public class Graphs {
|
||||
|
||||
public static void main(String args[]) {
|
||||
AdjacencyListGraph<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(2, 3);
|
||||
assert graph.addEdge(3, 4);
|
||||
assert graph.addEdge(4, 1);
|
||||
assert !graph.addEdge(2, 3);
|
||||
System.out.println(graph);
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -1,145 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class AdjacencyMatrixGraph {
|
||||
private int _numberOfVertices;
|
||||
private int _numberOfEdges;
|
||||
private int[][] _adjacency;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setNumberOfVertices(int newNumberOfVertices) {
|
||||
this._numberOfVertices = newNumberOfVertices;
|
||||
}
|
||||
|
||||
public int numberOfVertices() {
|
||||
return this._numberOfVertices;
|
||||
}
|
||||
|
||||
private void setNumberOfEdges(int newNumberOfEdges) {
|
||||
this._numberOfEdges = newNumberOfEdges;
|
||||
}
|
||||
|
||||
public int numberOfEdges() {
|
||||
return this._numberOfEdges;
|
||||
}
|
||||
|
||||
private void setAdjacency(int[][] newAdjacency) {
|
||||
this._adjacency = newAdjacency;
|
||||
}
|
||||
|
||||
private int[][] adjacency() {
|
||||
return this._adjacency;
|
||||
}
|
||||
|
||||
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 edgeDoesExist(int from, int to) {
|
||||
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
|
||||
return (this.adjacencyOfEdgeDoesExist(from, to));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method adds an edge to the graph between two specified
|
||||
* vertices
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* this method removes an edge from the graph between two specified
|
||||
* vertices
|
||||
*
|
||||
* @param from the data of the vertex the edge is from
|
||||
* @param to the data of the vertex the edge is going to
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
|
||||
//adjacency matrix representation of the graph
|
||||
|
||||
import java.lang.*;
|
||||
|
||||
class PrimMST
|
||||
{
|
||||
// Number of vertices in the graph
|
||||
private static final int V=5;
|
||||
|
||||
// A utility function to find the vertex with minimum key
|
||||
// value, from the set of vertices not yet included in MST
|
||||
int minKey(int key[], Boolean mstSet[])
|
||||
{
|
||||
// Initialize min value
|
||||
int min = Integer.MAX_VALUE, min_index=-1;
|
||||
|
||||
for (int v = 0; v < V; v++)
|
||||
if (mstSet[v] == false && key[v] < min)
|
||||
{
|
||||
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[][])
|
||||
{
|
||||
System.out.println("Edge Weight");
|
||||
for (int i = 1; i < V; 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[][])
|
||||
{
|
||||
// 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];
|
||||
|
||||
// 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++)
|
||||
{
|
||||
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
|
||||
parent[0] = -1; // First node is always root of MST
|
||||
|
||||
// The MST will have V vertices
|
||||
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;
|
||||
key[v] = graph[u][v];
|
||||
}
|
||||
}
|
||||
|
||||
// print the constructed MST
|
||||
printMST(parent, V, graph);
|
||||
}
|
||||
|
||||
public static void main (String[] args)
|
||||
{
|
||||
/* Let us create the following graph
|
||||
2 3
|
||||
(0)--(1)--(2)
|
||||
| / \ |
|
||||
6| 8/ \5 |7
|
||||
| / \ |
|
||||
(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},
|
||||
};
|
||||
|
||||
// Print the solution
|
||||
t.primMST(graph);
|
||||
}
|
||||
}
|
@ -1,283 +0,0 @@
|
||||
<<<<<<< HEAD:Data Structures/HashMap/HashMap.java
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class HashMap<K,V> {
|
||||
public class hmnodes{ //HashMap nodes
|
||||
K key;
|
||||
V value;
|
||||
}
|
||||
|
||||
private int size=0; //size of hashmap
|
||||
private LinkedList<hmnodes> buckets[]; //array of addresses of list
|
||||
|
||||
public HashMap(){
|
||||
buckets=new LinkedList[4]; //initially create bucket of any size
|
||||
for(int i=0;i<4;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
}
|
||||
|
||||
public void put(K key,V value) throws Exception{
|
||||
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
|
||||
int fountAt=find(bi,key); //check if key already exists or not
|
||||
if(fountAt==-1){
|
||||
hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
|
||||
temp.key=key;
|
||||
temp.value=value;
|
||||
buckets[bi].addLast(temp);
|
||||
this.size++;
|
||||
}else{
|
||||
buckets[bi].get(fountAt).value=value;//if already exist modify the value
|
||||
}
|
||||
|
||||
double lambda = (this.size*1.0)/this.buckets.length;
|
||||
if(lambda>2.0){
|
||||
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
public V get(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
return buckets[bi].get(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public V remove(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
this.size--;
|
||||
return buckets[bi].remove(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containskey(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return false;
|
||||
}else{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public int size(){
|
||||
return this.size;
|
||||
}
|
||||
|
||||
|
||||
public boolean isempty(){
|
||||
return this.size==0;
|
||||
}
|
||||
|
||||
public ArrayList<K> keyset() throws Exception{
|
||||
ArrayList<K> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).key);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public ArrayList<V> valueset() throws Exception{
|
||||
ArrayList<V> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).value);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public void display() throws Exception{
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
System.out.print("Bucket: "+i+" ");
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
hmnodes temp=buckets[i].get(j);
|
||||
System.out.print("["+temp.key+"->"+temp.value+"]");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
public int find(int bi,K key) throws Exception{
|
||||
for(int i=0;i<buckets[bi].size();i++){
|
||||
if(key.equals(buckets[bi].get(i).key))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int bucketIndex(K key) throws Exception{
|
||||
int bi=key.hashCode();
|
||||
return Math.abs(bi%buckets.length);
|
||||
}
|
||||
|
||||
private void rehash() throws Exception{
|
||||
LinkedList<hmnodes> ob[]= buckets;
|
||||
buckets=new LinkedList[ob.length*2];
|
||||
for(int i=0;i<ob.length*2;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
|
||||
size = 0;
|
||||
for(int i=0;i<ob.length;i++){
|
||||
for(int j=0;j<ob[i].size();j++){
|
||||
put(ob[i].get(j).key,ob[i].get(j).value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
=======
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class HashMap<K,V> {
|
||||
public class hmnodes{ //HashMap nodes
|
||||
K key;
|
||||
V value;
|
||||
}
|
||||
|
||||
private int size=0; //size of hashmap
|
||||
private LinkedList<hmnodes> buckets[]; //array of addresses of list
|
||||
|
||||
public HashMap(){
|
||||
buckets=new LinkedList[4]; //initially create bucket of any size
|
||||
for(int i=0;i<4;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
}
|
||||
|
||||
public void put(K key,V value) throws Exception{
|
||||
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
|
||||
int fountAt=find(bi,key); //check if key already exists or not
|
||||
if(fountAt==-1){
|
||||
hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
|
||||
temp.key=key;
|
||||
temp.value=value;
|
||||
buckets[bi].addLast(temp);
|
||||
this.size++;
|
||||
}else{
|
||||
buckets[bi].get(fountAt).value=value;//if already exist modify the value
|
||||
}
|
||||
|
||||
double lambda = (this.size*1.0)/this.buckets.length;
|
||||
if(lambda>2.0){
|
||||
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
public V get(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
return buckets[bi].get(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public V remove(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return null;
|
||||
}else{
|
||||
this.size--;
|
||||
return buckets[bi].remove(fountAt).value;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containskey(K key) throws Exception{
|
||||
int bi=bucketIndex(key);
|
||||
int fountAt=find(bi,key);
|
||||
if(fountAt==-1){
|
||||
return false;
|
||||
}else{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public int size(){
|
||||
return this.size;
|
||||
}
|
||||
|
||||
|
||||
public boolean isempty(){
|
||||
return this.size==0;
|
||||
}
|
||||
|
||||
public ArrayList<K> keyset() throws Exception{
|
||||
ArrayList<K> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).key);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public ArrayList<V> valueset() throws Exception{
|
||||
ArrayList<V> arr=new ArrayList<>();
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
arr.add(buckets[i].get(j).value);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public void display() throws Exception{
|
||||
for(int i=0;i<buckets.length;i++){
|
||||
System.out.print("Bucket: "+i+" ");
|
||||
for(int j=0;j<buckets[i].size();j++){
|
||||
hmnodes temp=buckets[i].get(j);
|
||||
System.out.print("["+temp.key+"->"+temp.value+"]");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
public int find(int bi,K key) throws Exception{
|
||||
for(int i=0;i<buckets[bi].size();i++){
|
||||
if(key.equals(buckets[bi].get(i).key))
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int bucketIndex(K key) throws Exception{
|
||||
int bi=key.hashCode();
|
||||
return Math.abs(bi%buckets.length);
|
||||
}
|
||||
|
||||
private void rehash() throws Exception{
|
||||
LinkedList<hmnodes> ob[]= buckets;
|
||||
buckets=new LinkedList[ob.length*2];
|
||||
for(int i=0;i<ob.length*2;i++)
|
||||
buckets[i]=new LinkedList<>();
|
||||
|
||||
size = 0;
|
||||
for(int i=0;i<ob.length;i++){
|
||||
for(int j=0;j<ob[i].size();j++){
|
||||
put(ob[i].get(j).key,ob[i].get(j).value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
>>>>>>> 7e3a8c55c865471a33f6932a022a1059c5243fc3:data_structures/HashMap/HashMap.java
|
@ -1,39 +0,0 @@
|
||||
class HashMap {
|
||||
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 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);
|
||||
|
||||
buckets[hash].delete(key);
|
||||
}
|
||||
public void displayHashtable() {
|
||||
for (int i = 0;i < hsize ; i++) {
|
||||
System.out.printf("Bucket %d :",i);
|
||||
buckets[i].display();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
class LinkedList {
|
||||
|
||||
private Node Head;
|
||||
private int size;
|
||||
|
||||
public LinkedList() {
|
||||
Head = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
public void insert(int data) {
|
||||
|
||||
Node temp = Head;
|
||||
Node newnode = new Node(data);
|
||||
|
||||
size++;
|
||||
|
||||
if(Head == null) {
|
||||
Head = newnode;
|
||||
}
|
||||
else {
|
||||
newnode.next = Head;
|
||||
Head = newnode;
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(int data) {
|
||||
if(size == 0) {
|
||||
System.out.println("UnderFlow!");
|
||||
return;
|
||||
}
|
||||
|
||||
else {
|
||||
Node curr = Head;
|
||||
if (curr.data == data) {
|
||||
Head = curr.next;
|
||||
size--;
|
||||
return;
|
||||
}
|
||||
else {
|
||||
|
||||
while(curr.next.next != null) {
|
||||
if(curr.next.data == data){
|
||||
curr.next = curr.next.next;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Key not Found");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void display() {
|
||||
Node temp = Head;
|
||||
while(temp != null) {
|
||||
System.out.printf("%d ",temp.data);
|
||||
temp = temp.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
|
||||
int choice, key;
|
||||
|
||||
HashMap h = new HashMap(7);
|
||||
|
||||
while (true) {
|
||||
System.out.println("Enter your Choice :");
|
||||
System.out.println("1. Add Key");
|
||||
System.out.println("2. Delete Key");
|
||||
System.out.println("3. Print Table");
|
||||
System.out.println("4. Exit");
|
||||
|
||||
Scanner In = new Scanner(System.in);
|
||||
|
||||
choice = In.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1: {
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertHash(key);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteHash(key);
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
System.out.println("Print table");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
class Node {
|
||||
int data;
|
||||
Node next;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
/**
|
||||
* @author Nicolas Renard
|
||||
* Exception to be thrown if the getElement method is used on an empty heap.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class EmptyHeapException extends Exception {
|
||||
|
||||
public EmptyHeapException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package heaps;
|
||||
|
||||
/**
|
||||
* Interface common to heap data structures.<br>
|
||||
* <p>Heaps are tree-like data structures that allow storing elements in a specific
|
||||
* way. Each node corresponds to an element and has one parent node (except for the root) and
|
||||
* at most two children nodes. Every element contains a key, and those keys
|
||||
* indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall
|
||||
* be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a
|
||||
* max-heap).</p>
|
||||
* <p>All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in
|
||||
* O(log n) time.</p>
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface Heap {
|
||||
|
||||
/**
|
||||
*
|
||||
* @return the top element in the heap, the one with lowest key for min-heap or with
|
||||
* the highest key for max-heap
|
||||
* @throws Exception if heap is empty
|
||||
*/
|
||||
public abstract HeapElement getElement() throws EmptyHeapException;
|
||||
/**
|
||||
* Inserts an element in the heap. Adds it to then end and toggle it until it finds its
|
||||
* right position.
|
||||
*
|
||||
* @param element an instance of the HeapElement class.
|
||||
*/
|
||||
public abstract void insertElement(HeapElement element);
|
||||
|
||||
/**
|
||||
* Delete an element in the heap.
|
||||
*
|
||||
* @param elementIndex int containing the position in the heap of the element to be deleted.
|
||||
*/
|
||||
public abstract void deleteElement(int elementIndex);
|
||||
|
||||
}
|
@ -1,132 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
import java.lang.Double;
|
||||
import java.lang.Object;
|
||||
|
||||
/**
|
||||
* Class for heap elements.<br>
|
||||
* <p>A heap element contains two attributes: a key which will be used to build the tree (int
|
||||
* or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit
|
||||
* to carry any information he/she likes. Be aware that the use of a mutable object might
|
||||
* jeopardize the integrity of this information. </p>
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class HeapElement {
|
||||
private final double key;
|
||||
private final Object additionalInfo;
|
||||
|
||||
// Constructors
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'double'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(double key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'int'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(int key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Integer'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(Integer key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Double'
|
||||
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
|
||||
* additional information of use for the user
|
||||
*/
|
||||
public HeapElement(Double key, Object info) {
|
||||
this.key = key;
|
||||
this.additionalInfo = info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'double'
|
||||
*/
|
||||
public HeapElement(double key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of primitive type 'int'
|
||||
*/
|
||||
public HeapElement(int key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Integer'
|
||||
*/
|
||||
public HeapElement(Integer key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key : a number of object type 'Double'
|
||||
*/
|
||||
public HeapElement(Double key) {
|
||||
this.key = key;
|
||||
this.additionalInfo = null;
|
||||
}
|
||||
|
||||
// Getters
|
||||
/**
|
||||
* @return the object containing the additional info provided by the user.
|
||||
*/
|
||||
public Object getInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
/**
|
||||
* @return the key value of the element
|
||||
*/
|
||||
public double getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
// Overridden object methods
|
||||
|
||||
public String toString() {
|
||||
return "Key: " + key + " - " +additionalInfo.toString();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param otherHeapElement
|
||||
* @return true if the keys on both elements are identical and the additional info objects
|
||||
* are identical.
|
||||
*/
|
||||
public boolean equals(HeapElement otherHeapElement) {
|
||||
return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
|
||||
}
|
||||
}
|
@ -1,115 +0,0 @@
|
||||
package heaps;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
|
||||
* to its children's.
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class MaxHeap implements Heap {
|
||||
|
||||
private final List<HeapElement> maxHeap;
|
||||
|
||||
public MaxHeap(List<HeapElement> listElements) throws Exception {
|
||||
maxHeap = new ArrayList<HeapElement>();
|
||||
for (HeapElement heapElement : listElements) {
|
||||
if (heapElement != null) insertElement(heapElement);
|
||||
else System.out.println("Null element. Not added to heap");
|
||||
}
|
||||
if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
|
||||
}
|
||||
|
||||
// Get the element at a given index. The key for the list is equal to index value - 1
|
||||
public HeapElement getElement(int elementIndex) {
|
||||
if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
return maxHeap.get(elementIndex - 1);
|
||||
}
|
||||
|
||||
// Get the key of the element at a given index
|
||||
private double getElementKey(int elementIndex) {
|
||||
return maxHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
// Swaps two elements in the heap
|
||||
private void swap(int index1, int index2) {
|
||||
HeapElement temporaryElement = maxHeap.get(index1 - 1);
|
||||
maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
|
||||
maxHeap.set(index2 - 1, temporaryElement);
|
||||
}
|
||||
|
||||
// Toggle an element up to its right place as long as its key is lower than its parent's
|
||||
private void toggleUp(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
while (getElementKey((int) Math.floor(elementIndex/2)) < key) {
|
||||
swap(elementIndex, (int) Math.floor(elementIndex/2));
|
||||
elementIndex = (int) Math.floor(elementIndex/2);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle an element down to its right place as long as its key is higher
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
|
||||
while ((2*elementIndex <= maxHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) {
|
||||
swap(elementIndex, 2*elementIndex + 1);
|
||||
elementIndex = 2*elementIndex + 1;
|
||||
}
|
||||
else {
|
||||
swap(elementIndex, 2*elementIndex);
|
||||
elementIndex = 2*elementIndex;
|
||||
}
|
||||
wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private HeapElement extractMax() {
|
||||
HeapElement result = maxHeap.get(0);
|
||||
deleteElement(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertElement(HeapElement element) {
|
||||
maxHeap.add(element);
|
||||
toggleUp(maxHeap.size());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (maxHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
// The last element in heap replaces the one to be deleted
|
||||
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
|
||||
maxHeap.remove(maxHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
|
||||
// ... or down ?
|
||||
else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) ||
|
||||
((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeapElement getElement() throws EmptyHeapException {
|
||||
try {
|
||||
return extractMax();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -1,115 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package heaps;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
|
||||
* to its children's.
|
||||
* @author Nicolas Renard
|
||||
*
|
||||
*/
|
||||
public class MinHeap implements Heap {
|
||||
|
||||
private final List<HeapElement> minHeap;
|
||||
|
||||
public MinHeap(List<HeapElement> listElements) throws Exception {
|
||||
minHeap = new ArrayList<HeapElement>();
|
||||
for (HeapElement heapElement : listElements) {
|
||||
if (heapElement != null) insertElement(heapElement);
|
||||
else System.out.println("Null element. Not added to heap");
|
||||
}
|
||||
if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
|
||||
}
|
||||
|
||||
// Get the element at a given index. The key for the list is equal to index value - 1
|
||||
public HeapElement getElement(int elementIndex) {
|
||||
if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
return minHeap.get(elementIndex - 1);
|
||||
}
|
||||
|
||||
// Get the key of the element at a given index
|
||||
private double getElementKey(int elementIndex) {
|
||||
return minHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
// Swaps two elements in the heap
|
||||
private void swap(int index1, int index2) {
|
||||
HeapElement temporaryElement = minHeap.get(index1 - 1);
|
||||
minHeap.set(index1 - 1, minHeap.get(index2 - 1));
|
||||
minHeap.set(index2 - 1, temporaryElement);
|
||||
}
|
||||
|
||||
// Toggle an element up to its right place as long as its key is lower than its parent's
|
||||
private void toggleUp(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
while (getElementKey((int) Math.floor(elementIndex/2)) > key) {
|
||||
swap(elementIndex, (int) Math.floor(elementIndex/2));
|
||||
elementIndex = (int) Math.floor(elementIndex/2);
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle an element down to its right place as long as its key is higher
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
|
||||
while ((2*elementIndex <= minHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) {
|
||||
swap(elementIndex, 2*elementIndex + 1);
|
||||
elementIndex = 2*elementIndex + 1;
|
||||
}
|
||||
else {
|
||||
swap(elementIndex, 2*elementIndex);
|
||||
elementIndex = 2*elementIndex;
|
||||
}
|
||||
wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private HeapElement extractMin() {
|
||||
HeapElement result = minHeap.get(0);
|
||||
deleteElement(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertElement(HeapElement element) {
|
||||
minHeap.add(element);
|
||||
toggleUp(minHeap.size());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (minHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
// The last element in heap replaces the one to be deleted
|
||||
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
|
||||
minHeap.remove(minHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
|
||||
// ... or down ?
|
||||
else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) ||
|
||||
((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeapElement getElement() throws EmptyHeapException {
|
||||
try {
|
||||
return extractMin();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,214 +0,0 @@
|
||||
/**
|
||||
* This class implements a DoublyLinkedList. This is done using the classes
|
||||
* LinkedList and Link.
|
||||
*
|
||||
* A linked list is simplar to an array, it holds values. However,
|
||||
* links in a linked list do not have indees. With a linked list
|
||||
* you do not need to predetermine it's size as it grows and shrinks
|
||||
* as it is edited. This is an example of a double ended, doubly
|
||||
* linked list. Each link references the next link and the previous
|
||||
* one.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
|
||||
class DoublyLinkedList{
|
||||
/** Head refers to the front of the list */
|
||||
private Link head;
|
||||
/** Tail refers to the back of the list */
|
||||
private Link tail;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public DoublyLinkedList(){
|
||||
head = null;
|
||||
tail = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an element at the head
|
||||
*
|
||||
* @param x Element to be inserted
|
||||
*/
|
||||
public void insertHead(int x){
|
||||
Link newLink = new Link(x); //Create a new link with a value attached to it
|
||||
if(isEmpty()) //Set the first element added to be the tail
|
||||
tail = newLink;
|
||||
else
|
||||
head.previous = newLink; // newLink <-- currenthead(head)
|
||||
newLink.next = head; // newLink <--> currenthead(head)
|
||||
head = newLink; // newLink(head) <--> oldhead
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an element at the tail
|
||||
*
|
||||
* @param x Element to be inserted
|
||||
*/
|
||||
public void insertTail(int x){
|
||||
Link newLink = new Link(x);
|
||||
newLink.next = null; // currentTail(tail) newlink -->
|
||||
tail.next = newLink; // currentTail(tail) --> newLink -->
|
||||
newLink.previous = tail; // currentTail(tail) <--> newLink -->
|
||||
tail = newLink; // oldTail <--> newLink(tail) -->
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element at the head
|
||||
*
|
||||
* @return The new head
|
||||
*/
|
||||
public Link deleteHead(){
|
||||
Link temp = head;
|
||||
head = head.next; // oldHead <--> 2ndElement(head)
|
||||
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
|
||||
if(head == null)
|
||||
tail = null;
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element at the tail
|
||||
*
|
||||
* @return The new tail
|
||||
*/
|
||||
public Link deleteTail(){
|
||||
Link temp = tail;
|
||||
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
|
||||
tail.next = null; // 2ndLast(tail) --> null
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the element from somewhere in the list
|
||||
*
|
||||
* @param x element to be deleted
|
||||
* @return Link deleted
|
||||
*/
|
||||
public Link delete(int x){
|
||||
Link current = head;
|
||||
|
||||
while(current.value != x) //Find the position to delete
|
||||
current = current.next;
|
||||
|
||||
if(current == head)
|
||||
deleteHead();
|
||||
|
||||
else if(current == tail)
|
||||
deleteTail();
|
||||
|
||||
else{ //Before: 1 <--> 2(current) <--> 3
|
||||
current.previous.next = current.next; // 1 --> 3
|
||||
current.next.previous = current.previous; // 1 <--> 3
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts element and reorders
|
||||
*
|
||||
* @param x Element to be added
|
||||
*/
|
||||
public void insertOrdered(int x){
|
||||
Link newLink = new Link(x);
|
||||
Link current = head;
|
||||
while(current != null && x > current.value) //Find the position to insert
|
||||
current = current.next;
|
||||
|
||||
if(current == head)
|
||||
insertHead(x);
|
||||
|
||||
else if(current == null)
|
||||
insertTail(x);
|
||||
|
||||
else{ //Before: 1 <--> 2(current) <--> 3
|
||||
newLink.previous = current.previous; // 1 <-- newLink
|
||||
current.previous.next = newLink; // 1 <--> newLink
|
||||
newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
|
||||
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if list is empty
|
||||
*
|
||||
* @return true if list is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(head == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints contents of the list
|
||||
*/
|
||||
public void display(){ //Prints contents of the list
|
||||
Link current = head;
|
||||
while(current!=null){
|
||||
current.displayLink();
|
||||
current = current.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is used to implement the nodes of the
|
||||
* linked list.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Link{
|
||||
/** Value of node */
|
||||
public int value;
|
||||
/** This points to the link in front of the new link */
|
||||
public Link next;
|
||||
/** This points to the link behind the new link */
|
||||
public Link previous;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param value Value of node
|
||||
*/
|
||||
public Link(int value){
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the node
|
||||
*/
|
||||
public void displayLink(){
|
||||
System.out.print(value+" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
DoublyLinkedList myList = new DoublyLinkedList();
|
||||
|
||||
myList.insertHead(13);
|
||||
myList.insertHead(7);
|
||||
myList.insertHead(10);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
|
||||
|
||||
myList.insertTail(11);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
|
||||
|
||||
myList.deleteTail();
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
|
||||
|
||||
myList.delete(7);
|
||||
myList.display(); // <-- 10(head) <--> 13(tail) -->
|
||||
|
||||
myList.insertOrdered(23);
|
||||
myList.insertOrdered(67);
|
||||
myList.insertOrdered(3);
|
||||
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
|
||||
}
|
||||
}
|
@ -1,151 +0,0 @@
|
||||
/**
|
||||
* This class implements a SinglyLinked List. This is done
|
||||
* using SinglyLinkedList class and a LinkForLinkedList Class.
|
||||
*
|
||||
* A linked list is implar to an array, it hold values.
|
||||
* However, links in a linked list do not have indexes. With
|
||||
* a linked list you do not need to predetermine it's size as
|
||||
* it gorws and shrinks as it is edited. This is an example of
|
||||
* a singly linked list. Elements can only be added/removed
|
||||
* at the head/front of the list.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class SinglyLinkedList{
|
||||
/**Head refered to the front of the list */
|
||||
private Node head;
|
||||
|
||||
/**
|
||||
* Constructor of SinglyLinkedList
|
||||
*/
|
||||
public SinglyLinkedList(){
|
||||
head = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method inserts an element at the head
|
||||
*
|
||||
* @param x Element to be added
|
||||
*/
|
||||
public void insertHead(int x){
|
||||
Node newNode = new Node(x); //Create a new link with a value attached to it
|
||||
newNode.next = head; //Set the new link to point to the current head
|
||||
head = newNode; //Now set the new link to be the head
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inserts a new node at a specified position
|
||||
* @param head head node of the linked list
|
||||
* @param data data to be stored in a new node
|
||||
* @param position position at which a new node is to be inserted
|
||||
* @return reference of the head of the linked list
|
||||
*/
|
||||
|
||||
Node InsertNth(Node head, int data, int position) {
|
||||
|
||||
Node newNode = new Node();
|
||||
newNode.data = data;
|
||||
|
||||
if (position == 0) {
|
||||
newNode.next = head;
|
||||
return newNode;
|
||||
}
|
||||
|
||||
Node current = head;
|
||||
|
||||
while (--position > 0) {
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
newNode.next = current.next;
|
||||
current.next = newNode;
|
||||
return head;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method deletes an element at the head
|
||||
*
|
||||
* @return The element deleted
|
||||
*/
|
||||
public Node deleteHead(){
|
||||
Node temp = head;
|
||||
head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the list is empty
|
||||
*
|
||||
* @return true is list is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(head == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints contents of the list
|
||||
*/
|
||||
public void display(){
|
||||
Node current = head;
|
||||
while(current!=null){
|
||||
System.out.print(current.getValue()+" ");
|
||||
current = current.next;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
SinglyLinkedList myList = new SinglyLinkedList();
|
||||
|
||||
System.out.println(myList.isEmpty()); //Will print true
|
||||
|
||||
myList.insertHead(5);
|
||||
myList.insertHead(7);
|
||||
myList.insertHead(10);
|
||||
|
||||
myList.display(); // 10(head) --> 7 --> 5
|
||||
|
||||
myList.deleteHead();
|
||||
|
||||
myList.display(); // 7(head) --> 5
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is the nodes of the SinglyLinked List.
|
||||
* They consist of a vlue and a pointer to the node
|
||||
* after them.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Node{
|
||||
/** The value of the node */
|
||||
public int value;
|
||||
/** Point to the next node */
|
||||
public Node next; //This is what the link will point to
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param valuein Value to be put in the node
|
||||
*/
|
||||
public Node(int valuein){
|
||||
value = valuein;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns value of the node
|
||||
*/
|
||||
public int getValue(){
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
@ -1,259 +0,0 @@
|
||||
/**
|
||||
* Matrix data-type.
|
||||
*
|
||||
* @author Kyler Smith, 2017
|
||||
*/
|
||||
|
||||
|
||||
public class Matrix {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int[][] data1 = new int[0][0];
|
||||
int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
|
||||
int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
|
||||
|
||||
Matrix m1 = new Matrix(data1);
|
||||
Matrix m2 = new Matrix(data2);
|
||||
Matrix m3 = new Matrix(data3);
|
||||
|
||||
System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns());
|
||||
System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns());
|
||||
System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns());
|
||||
|
||||
//check for reference issues
|
||||
System.out.println("m2 -->\n" + m2);
|
||||
data2[1][1] = 101;
|
||||
System.out.println("m2 -->\n" + m2);
|
||||
|
||||
//test equals
|
||||
System.out.println("m2==null: " + m2.equals(null)); //false
|
||||
System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false
|
||||
System.out.println("m2==m1: " + m2.equals(m1)); //false
|
||||
System.out.println("m2==m2: " + m2.equals(m2)); //true
|
||||
System.out.println("m2==m3: " + m2.equals(m3)); //false
|
||||
|
||||
//test operations (valid)
|
||||
System.out.println("2 * m2:\n" + m2.scale(2));
|
||||
System.out.println("m2 / 2:\n" + m2.divide(2));
|
||||
System.out.println("m2 + m3:\n" + m2.plus(m3));
|
||||
System.out.println("m2 - m3:\n" + m2.minus(m3));
|
||||
System.out.println("m2 * m3: \n"+m2.multiply(m3));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Data needs to be a deep copy as not to change the original state.
|
||||
*/
|
||||
private int[][] data;
|
||||
|
||||
/**
|
||||
* Constructor for the matrix takes in a 2D array
|
||||
*
|
||||
* @param pData
|
||||
*/
|
||||
public Matrix(int[][] pData) {
|
||||
|
||||
/** Make a deep copy of the data */
|
||||
if(pData.length != 0) {
|
||||
int[][] newData = new int[pData.length][pData[0].length];
|
||||
|
||||
for(int i = 0; i < pData.length; i++)
|
||||
for(int j = 0; j < pData[0].length; j++)
|
||||
newData[i][j] = pData[i][j];
|
||||
|
||||
this.data = newData;
|
||||
} else {
|
||||
this.data = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element specified by the given location
|
||||
*
|
||||
* @param x : x cooridinate
|
||||
* @param y : y cooridinate
|
||||
* @return int : value at location
|
||||
*/
|
||||
public int getElement(int x, int y) {
|
||||
return data[x][y];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the Matrix
|
||||
*
|
||||
* @return rows
|
||||
*/
|
||||
public int getRows() {
|
||||
if(this.data == null)
|
||||
return 0;
|
||||
|
||||
return data.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows in the Matrix
|
||||
*
|
||||
* @return columns
|
||||
*/
|
||||
public int getColumns() {
|
||||
if(this.data == null)
|
||||
return 0;
|
||||
return data[0].length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this matrix scaled by a factor. That is, computes sA where s is a
|
||||
* constant and A is a matrix (this object).
|
||||
*
|
||||
* @param scalar : value to scale by
|
||||
* @return A new matrix scaled by the scalar value
|
||||
*/
|
||||
public Matrix scale(int scalar) {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] * scalar;
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns this matrix divided by a factor. That is, computes sA where s is a
|
||||
* constant and A is a matrix (this object).
|
||||
*
|
||||
* @param scalar : value to divide by
|
||||
* @return A new matrix scaled by the scalar value
|
||||
*/
|
||||
public Matrix divide(int scalar) {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] / scalar;
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds this matrix to another matrix.
|
||||
*
|
||||
* @param other : Matrix to be added
|
||||
* @return addend
|
||||
*/
|
||||
public Matrix plus(Matrix other) throws RuntimeException {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
|
||||
throw new RuntimeException("Not the same size matrix.");
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] + other.getElement(i, j);
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtracts this matrix from another matrix.
|
||||
*
|
||||
* @param other : Matrix to be subtracted
|
||||
* @return difference
|
||||
*/
|
||||
public Matrix minus(Matrix other) throws RuntimeException {
|
||||
|
||||
int[][] newData = new int[this.data.length][this.data[0].length];
|
||||
|
||||
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
|
||||
throw new RuntimeException("Not the same size matrix.");
|
||||
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < this.getColumns(); ++j)
|
||||
newData[i][j] = this.data[i][j] - other.getElement(i, j);
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiplies this matrix with another matrix.
|
||||
*
|
||||
* @param other : Matrix to be multiplied with
|
||||
* @return product
|
||||
*/
|
||||
public Matrix multiply(Matrix other) throws RuntimeException {
|
||||
|
||||
int[][] newData = new int[this.data.length][other.getColumns()];
|
||||
|
||||
if(this.getColumns() !=other.getRows())
|
||||
throw new RuntimeException("The two matrices cannot be multiplied.");
|
||||
int sum;
|
||||
for (int i = 0; i < this.getRows(); ++i)
|
||||
for(int j = 0; j < other.getColumns(); ++j){
|
||||
sum = 0;
|
||||
for(int k=0;k<this.getColumns();++k){
|
||||
sum += this.data[i][k] * other.getElement(k, j);
|
||||
}
|
||||
newData[i][j] = sum;
|
||||
}
|
||||
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the matrix passed is equal to this matrix
|
||||
*
|
||||
* @param other : the other matrix
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(Matrix other) {
|
||||
return this == other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Matrix as a String in the following format
|
||||
*
|
||||
* [ a b c ] ...
|
||||
* [ x y z ] ...
|
||||
* [ i j k ] ...
|
||||
* ...
|
||||
*
|
||||
* @return Matrix as String
|
||||
* TODO: Work formatting for different digit sizes
|
||||
*/
|
||||
public String toString() {
|
||||
String str = "";
|
||||
|
||||
for(int i = 0; i < this.data.length; i++) {
|
||||
str += "[ ";
|
||||
for(int j = 0; j < this.data[0].length; j++) {
|
||||
str += data[i][j];
|
||||
str += " ";
|
||||
}
|
||||
str += "]";
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns transposed matrix of this matrix.
|
||||
*
|
||||
* @return transposed Matrix.
|
||||
*/
|
||||
public Matrix transpose() {
|
||||
|
||||
int[][] newData = new int[this.data[0].length][this.data.length];
|
||||
|
||||
for (int i = 0; i < this.getColumns(); ++i)
|
||||
for(int j = 0; j < this.getRows(); ++j)
|
||||
newData[i][j] = this.data[j][i];
|
||||
|
||||
return new Matrix(newData);
|
||||
}
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class GenericArrayListQueue<T> {
|
||||
ArrayList<T> _queue = new ArrayList<T>();
|
||||
|
||||
private boolean hasElements() {
|
||||
return !_queue.isEmpty();
|
||||
}
|
||||
|
||||
public T peek() {
|
||||
T result = null;
|
||||
if(this.hasElements()) { result = _queue.get(0); }
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean add(T element) {
|
||||
return _queue.add(element);
|
||||
}
|
||||
|
||||
public T poll() {
|
||||
T result = null;
|
||||
if(this.hasElements()) { result = _queue.remove(0); }
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
|
||||
System.out.println("Running...");
|
||||
assert queue.peek() == null;
|
||||
assert queue.poll() == null;
|
||||
assert queue.add(1) == true;
|
||||
assert queue.peek() == 1;
|
||||
assert queue.add(2) == true;
|
||||
assert queue.peek() == 1;
|
||||
assert queue.poll() == 1;
|
||||
assert queue.peek() == 2;
|
||||
assert queue.poll() == 2;
|
||||
assert queue.peek() == null;
|
||||
assert queue.poll() == null;
|
||||
System.out.println("Finished.");
|
||||
}
|
||||
}
|
@ -1,123 +0,0 @@
|
||||
/**
|
||||
* This class implements a PriorityQueue.
|
||||
*
|
||||
* A priority queue adds elements into positions based on their priority.
|
||||
* So the most important elements are placed at the front/on the top.
|
||||
* In this example I give numbers that are bigger, a higher priority.
|
||||
* Queues in theory have no fixed size but when using an array
|
||||
* implementation it does.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class PriorityQueue{
|
||||
/** The max size of the queue */
|
||||
private int maxSize;
|
||||
/** The array for the queue */
|
||||
private int[] queueArray;
|
||||
/** How many items are in the queue */
|
||||
private int nItems;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the queue
|
||||
*/
|
||||
public PriorityQueue(int size){
|
||||
maxSize = size;
|
||||
queueArray = new int[size];
|
||||
nItems = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an element in it's appropriate place
|
||||
*
|
||||
* @param value Value to be inserted
|
||||
*/
|
||||
public void insert(int value){
|
||||
if(nItems == 0){
|
||||
queueArray[0] = value;
|
||||
}
|
||||
else{
|
||||
int j = nItems;
|
||||
while(j > 0 && queueArray[j-1] > value){
|
||||
queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
|
||||
j--;
|
||||
}
|
||||
queueArray[j] = value; //Once the correct position is found the value is inserted
|
||||
}
|
||||
nItems++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the element from the front of the queue
|
||||
*
|
||||
* @return The element removed
|
||||
*/
|
||||
public int remove(){
|
||||
return queueArray[--nItems];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the front of the queue
|
||||
*
|
||||
* @return element at the front of the queue
|
||||
*/
|
||||
public int peek(){
|
||||
return queueArray[nItems-1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is empty
|
||||
*
|
||||
* @return true if the queue is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(nItems == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is full
|
||||
*
|
||||
* @return true if the queue is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(nItems == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in the queue
|
||||
*
|
||||
* @return number of elements in the queue
|
||||
*/
|
||||
public int getSize(){
|
||||
return nItems;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class implements the PriorityQueue class above.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class PriorityQueues{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command Line Arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
PriorityQueue myQueue = new PriorityQueue(4);
|
||||
myQueue.insert(10);
|
||||
myQueue.insert(2);
|
||||
myQueue.insert(5);
|
||||
myQueue.insert(3);
|
||||
//[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
|
||||
|
||||
for(int i = 3; i>=0; i--)
|
||||
System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2]
|
||||
|
||||
//As you can see, a Priority Queue can be used as a sorting algotithm
|
||||
}
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
/**
|
||||
* This implements Queues by using the class Queue.
|
||||
*
|
||||
* A queue data structure functions the same as a real world queue.
|
||||
* The elements that are added first are the first to be removed.
|
||||
* New elements are added to the back/rear of the queue.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Queue{
|
||||
/** Max size of the queue */
|
||||
private int maxSize;
|
||||
/** The array representing the queue */
|
||||
private int[] queueArray;
|
||||
/** Front of the queue */
|
||||
private int front;
|
||||
/** Rear of the queue */
|
||||
private int rear;
|
||||
/** How many items are in the queue */
|
||||
private int nItems;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the new queue
|
||||
*/
|
||||
public Queue(int size){
|
||||
maxSize = size;
|
||||
queueArray = new int[size];
|
||||
front = 0;
|
||||
rear = -1;
|
||||
nItems = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an element at the rear of the queue
|
||||
*
|
||||
* @param x element to be added
|
||||
* @return True if the element was added successfully
|
||||
*/
|
||||
public boolean insert(int x){
|
||||
if(isFull())
|
||||
return false;
|
||||
if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front
|
||||
rear = -1;
|
||||
rear++;
|
||||
queueArray[rear] = x;
|
||||
nItems++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an element from the front of the queue
|
||||
*
|
||||
* @return the new front of the queue
|
||||
*/
|
||||
public int remove(){ //Remove an element from the front of the queue
|
||||
if(isEmpty()){
|
||||
System.out.println("Queue is empty");
|
||||
return -1;
|
||||
}
|
||||
int temp = queueArray[front];
|
||||
front++;
|
||||
if(front == maxSize) //Dealing with wrap-around again
|
||||
front = 0;
|
||||
nItems--;
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the front of the queue
|
||||
*
|
||||
* @return element at the front of the queue
|
||||
*/
|
||||
public int peekFront(){
|
||||
return queueArray[front];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks what's at the rear of the queue
|
||||
*
|
||||
* @return element at the rear of the queue
|
||||
*/
|
||||
public int peekRear(){
|
||||
return queueArray[rear];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is empty
|
||||
*
|
||||
* @return true if the queue is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(nItems == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the queue is full
|
||||
*
|
||||
* @return true if the queue is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(nItems == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in the queue
|
||||
*
|
||||
* @return number of elements in the queue
|
||||
*/
|
||||
public int getSize(){
|
||||
return nItems;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class is the example for the Queue class
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class Queues{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Queue myQueue = new Queue(4);
|
||||
myQueue.insert(10);
|
||||
myQueue.insert(2);
|
||||
myQueue.insert(5);
|
||||
myQueue.insert(3);
|
||||
//[10(front), 2, 5, 3(rear)]
|
||||
|
||||
System.out.println(myQueue.isFull()); //Will print true
|
||||
|
||||
myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue
|
||||
//[10, 2(front), 5, 3(rear)]
|
||||
|
||||
myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around
|
||||
// [7(rear), 2(front), 5, 3]
|
||||
|
||||
System.out.println(myQueue.peekFront()); //Will print 2
|
||||
System.out.println(myQueue.peekRear()); //Will print 7
|
||||
}
|
||||
}
|
@ -1,89 +0,0 @@
|
||||
package data_structures.Stacks;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
*
|
||||
* The nested brackets problem is a problem that determines if a sequence of
|
||||
* brackets are properly nested. A sequence of brackets s is considered properly
|
||||
* nested if any of the following conditions are true: - s is empty - s has the
|
||||
* form (U) or [U] or {U} where U is a properly nested string - s has the form
|
||||
* VW where V and W are properly nested strings For example, the string
|
||||
* "()()[()]" is properly nested but "[(()]" is not. The function called
|
||||
* is_balanced takes as input a string S which is a sequence of brackets and
|
||||
* returns true if S is nested and false otherwise.
|
||||
*
|
||||
* @author akshay sharma
|
||||
* @date: 2017-10-17
|
||||
* @author <a href="https://github.com/khalil2535">khalil2535<a>
|
||||
*
|
||||
*/
|
||||
class BalancedBrackets {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
static boolean is_balanced(String s) {
|
||||
Stack<Character> bracketsStack = new Stack<>();
|
||||
char[] text = s.toCharArray();
|
||||
for (char x : text) {
|
||||
switch (x) {
|
||||
case '{':
|
||||
case '<':
|
||||
case '(':
|
||||
case '[':
|
||||
bracketsStack.push(x);
|
||||
break;
|
||||
case '}':
|
||||
if (bracketsStack.peek() == '{') {
|
||||
bracketsStack.pop();
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case '>':
|
||||
if (bracketsStack.peek() == '<') {
|
||||
bracketsStack.pop();
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case ')':
|
||||
if (bracketsStack.peek() == '(') {
|
||||
bracketsStack.pop();
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
case ']':
|
||||
if (bracketsStack.peek() == '[') {
|
||||
bracketsStack.pop();
|
||||
break;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bracketsStack.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
* @TODO remove main method and Test using JUnit or other methodology
|
||||
*/
|
||||
public static void main(String args[]) {
|
||||
try (Scanner in = new Scanner(System.in)) {
|
||||
System.out.println("Enter sequence of brackets: ");
|
||||
String s = in.nextLine();
|
||||
if (is_balanced(s)) {
|
||||
System.out.println(s + " is balanced");
|
||||
} else {
|
||||
System.out.println(s + " ain't balanced");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,183 +0,0 @@
|
||||
/**
|
||||
* Implementation of a stack using nodes.
|
||||
* Unlimited size, no arraylist.
|
||||
*
|
||||
* @author Kyler Smith, 2017
|
||||
*/
|
||||
|
||||
|
||||
public class NodeStack<Item> {
|
||||
|
||||
/**
|
||||
* Entry point for the program.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
NodeStack<Integer> Stack = new NodeStack<Integer>();
|
||||
|
||||
Stack.push(3);
|
||||
Stack.push(4);
|
||||
Stack.push(5);
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 5 4 3
|
||||
|
||||
Integer x = Stack.pop(); // x = 5
|
||||
Stack.push(1);
|
||||
Stack.push(8);
|
||||
Integer y = Stack.peek(); // y = 8
|
||||
System.out.println("Testing :");
|
||||
Stack.print(); // prints : 8 1 4 3
|
||||
|
||||
System.out.println("Testing :");
|
||||
System.out.println("x : " + x);
|
||||
System.out.println("y : " + y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Information each node should contain.
|
||||
* @value data : information of the value in the node
|
||||
* @value head : the head of the stack
|
||||
* @value next : the next value from this node
|
||||
* @value previous : the last value from this node
|
||||
* @value size : size of the stack
|
||||
*/
|
||||
private Item data;
|
||||
private static NodeStack<?> head;
|
||||
private NodeStack<?> next;
|
||||
private NodeStack<?> previous;
|
||||
private static int size = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Constructors for the NodeStack.
|
||||
*/
|
||||
public NodeStack() {
|
||||
}
|
||||
|
||||
private NodeStack(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a value onto the stack.
|
||||
*
|
||||
* @param item : value to be put on the stack.
|
||||
*/
|
||||
public void push(Item item) {
|
||||
|
||||
NodeStack<Item> newNs = new NodeStack<Item>(item);
|
||||
|
||||
if(this.isEmpty()) {
|
||||
NodeStack.setHead(new NodeStack<>(item));
|
||||
newNs.setNext(null);
|
||||
newNs.setPrevious(null);
|
||||
} else {
|
||||
newNs.setPrevious(NodeStack.head);
|
||||
NodeStack.head.setNext(newNs);
|
||||
NodeStack.head = newNs;
|
||||
}
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Value to be taken off the stack.
|
||||
*
|
||||
* @return item : value that is returned.
|
||||
*/
|
||||
public Item pop() {
|
||||
|
||||
Item item = (Item) NodeStack.head.getData();
|
||||
|
||||
NodeStack.head = NodeStack.head.getPrevious();
|
||||
NodeStack.head.setNext(null);
|
||||
|
||||
NodeStack.setSize(NodeStack.getSize() - 1);
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Value that is next to be taken off the stack.
|
||||
*
|
||||
* @return item : the next value that would be popped off the stack.
|
||||
*/
|
||||
public Item peek() {
|
||||
return (Item) NodeStack.head.getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the stack is empty or there is a value in.
|
||||
*
|
||||
* @return boolean : whether or not the stack has anything in it.
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return NodeStack.getSize() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of the stack.
|
||||
*
|
||||
* @return int : number of values in the stack.
|
||||
*/
|
||||
public int size() {
|
||||
return NodeStack.getSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print the contents of the stack in the following format.
|
||||
*
|
||||
* x <- head (next out)
|
||||
* y
|
||||
* z <- tail (first in)
|
||||
* .
|
||||
* .
|
||||
* .
|
||||
*
|
||||
*/
|
||||
public void print() {
|
||||
for(NodeStack<?> n = NodeStack.head; n != null; n = n.previous) {
|
||||
System.out.println(n.getData().toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Getters and setters (private) */
|
||||
private NodeStack<?> getHead() {
|
||||
return NodeStack.head;
|
||||
}
|
||||
|
||||
private static void setHead(NodeStack<?> ns) {
|
||||
NodeStack.head = ns;
|
||||
}
|
||||
|
||||
private NodeStack<?> getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
private void setNext(NodeStack<?> next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
private NodeStack<?> getPrevious() {
|
||||
return previous;
|
||||
}
|
||||
|
||||
private void setPrevious(NodeStack<?> previous) {
|
||||
this.previous = previous;
|
||||
}
|
||||
|
||||
private static int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
private static void setSize(int size) {
|
||||
NodeStack.size = size;
|
||||
}
|
||||
|
||||
private Item getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
private void setData(Item item) {
|
||||
this.data = item;
|
||||
}
|
||||
}
|
@ -1,109 +0,0 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// An implementation of a Stack using a Linked List
|
||||
|
||||
class StackOfLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LinkedListStack stack = new LinkedListStack();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
stack.push(4);
|
||||
stack.push(5);
|
||||
|
||||
stack.printStack();
|
||||
|
||||
System.out.println("Size of stack currently is: " + stack.getSize());
|
||||
|
||||
stack.pop();
|
||||
stack.pop();
|
||||
|
||||
System.out.println("Top element of stack currently is: " + stack.peek());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A node class
|
||||
|
||||
class Node {
|
||||
public int data;
|
||||
public Node next;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A class which implements a stack using a linked list
|
||||
*
|
||||
* Contains all the stack methods : push, pop, printStack, isEmpty
|
||||
**/
|
||||
|
||||
class LinkedListStack {
|
||||
|
||||
Node head = null;
|
||||
int size = 0;
|
||||
|
||||
public void push(int x) {
|
||||
Node n = new Node(x);
|
||||
if (getSize() == 0) {
|
||||
head = n;
|
||||
}
|
||||
else {
|
||||
Node temp = head;
|
||||
n.next = temp;
|
||||
head = n;
|
||||
}
|
||||
size++;
|
||||
}
|
||||
|
||||
public void pop() {
|
||||
if (getSize() == 0) {
|
||||
System.out.println("Empty stack. Nothing to pop");
|
||||
}
|
||||
|
||||
Node temp = head;
|
||||
head = head.next;
|
||||
size--;
|
||||
|
||||
System.out.println("Popped element is: " + temp.data);
|
||||
}
|
||||
|
||||
public int peek() {
|
||||
if (getSize() == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return head.data;
|
||||
}
|
||||
|
||||
public void printStack() {
|
||||
|
||||
Node temp = head;
|
||||
System.out.println("Stack is printed as below: ");
|
||||
while (temp != null) {
|
||||
System.out.println(temp.data + " ");
|
||||
temp = temp.next;
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return getSize() == 0;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
}
|
@ -1,240 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* This class implements a Stack using two different implementations.
|
||||
* Stack is used with a regular array and Stack2 uses an ArrayList.
|
||||
*
|
||||
* A stack is exactly what it sounds like. An element gets added to the top of
|
||||
* the stack and only the element on the top may be removed. This is an example
|
||||
* of an array implementation of a Stack. So an element can only be added/removed
|
||||
* from the end of the array. In theory stack have no fixed size, but with an
|
||||
* array implementation it does.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Stack{
|
||||
/** The max size of the Stack */
|
||||
private int maxSize;
|
||||
/** The array representation of the Stack */
|
||||
private int[] stackArray;
|
||||
/** The top of the stack */
|
||||
private int top;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param size Size of the Stack
|
||||
*/
|
||||
public Stack(int size){
|
||||
maxSize = size;
|
||||
stackArray = new int[maxSize];
|
||||
top = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an element to the top of the stack
|
||||
*
|
||||
* @param value The element added
|
||||
*/
|
||||
public void push(int value){
|
||||
if(!isFull()){ //Checks for a full stack
|
||||
top++;
|
||||
stackArray[top] = value;
|
||||
}else{
|
||||
resize(maxSize*2);
|
||||
push(value);// don't forget push after resizing
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the top element of the stack and returns the value you've removed
|
||||
*
|
||||
* @return value popped off the Stack
|
||||
*/
|
||||
public int pop(){
|
||||
if(!isEmpty()){ //Checks for an empty stack
|
||||
return stackArray[top--];
|
||||
}
|
||||
|
||||
if(top < maxSize/4){
|
||||
resize(maxSize/2);
|
||||
return pop();// don't forget pop after resizing
|
||||
}
|
||||
else{
|
||||
System.out.println("The stack is already empty");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element at the top of the stack
|
||||
*
|
||||
* @return element at the top of the stack
|
||||
*/
|
||||
public int peek(){
|
||||
if(!isEmpty()){ //Checks for an empty stack
|
||||
return stackArray[top];
|
||||
}else{
|
||||
System.out.println("The stack is empty, cant peek");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private void resize(int newSize){
|
||||
//private int[] transferArray = new int[newSize]; we can't put modifires here !
|
||||
int[] transferArray = new int[newSize];
|
||||
|
||||
//for(int i = 0; i < stackArray.length(); i++){ the length isn't a method .
|
||||
for(int i = 0; i < stackArray.length; i++){
|
||||
transferArray[i] = stackArray[i];
|
||||
stackArray = transferArray;
|
||||
}
|
||||
maxSize = newSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is empty
|
||||
*
|
||||
* @return true if the stack is empty
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
return(top == -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stack is full
|
||||
*
|
||||
* @return true if the stack is full
|
||||
*/
|
||||
public boolean isFull(){
|
||||
return(top+1 == maxSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes everything in the Stack
|
||||
*
|
||||
* Doesn't delete elements in the array
|
||||
* but if you call push method after calling
|
||||
* makeEmpty it will overwrite previous
|
||||
* values
|
||||
*/
|
||||
public void makeEmpty(){ //Doesn't delete elements in the array but if you call
|
||||
top = -1; //push method after calling makeEmpty it will overwrite previous values
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an ArrayList Implementation of stack, Where size is not
|
||||
* a problem we can extend the stack as much as we want.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Stack2{
|
||||
/** ArrayList representation of the stack */
|
||||
ArrayList<Integer> stackList;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
Stack2(){
|
||||
stackList=new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds value to the end of list which
|
||||
* is the top for stack
|
||||
*
|
||||
* @param value value to be added
|
||||
*/
|
||||
void push(int value){
|
||||
stackList.add(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pops last element of list which is indeed
|
||||
* the top for Stack
|
||||
*
|
||||
* @return Element popped
|
||||
*/
|
||||
int pop(){
|
||||
|
||||
if(!isEmpty()){ // checks for an empty Stack
|
||||
|
||||
int popValue=stackList.get(stackList.size()-1);
|
||||
stackList.remove(stackList.size()-1); //removes the poped element from the list
|
||||
return popValue;
|
||||
}
|
||||
else{
|
||||
System.out.print("The stack is already empty ");
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for empty Stack
|
||||
*
|
||||
* @return true if stack is empty
|
||||
*/
|
||||
boolean isEmpty(){
|
||||
if(stackList.isEmpty())
|
||||
return true;
|
||||
|
||||
else return false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Top element of stack
|
||||
*
|
||||
* @return top element of stack
|
||||
*/
|
||||
int peek(){
|
||||
return stackList.get(stackList.size()-1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class implements the Stack and Stack2 created above
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
public class Stacks{
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String args[]){
|
||||
Stack myStack = new Stack(4); //Declare a stack of maximum size 4
|
||||
//Populate the stack
|
||||
myStack.push(5);
|
||||
myStack.push(8);
|
||||
myStack.push(2);
|
||||
myStack.push(9);
|
||||
|
||||
System.out.println("*********************Stack Array Implementation*********************");
|
||||
System.out.println(myStack.isEmpty()); //will print false
|
||||
System.out.println(myStack.isFull()); //will print true
|
||||
System.out.println(myStack.peek()); //will print 9
|
||||
System.out.println(myStack.pop()); //will print 9
|
||||
System.out.println(myStack.peek()); // will print 2
|
||||
|
||||
Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4
|
||||
//Populate the stack
|
||||
myStack2.push(5);
|
||||
myStack2.push(8);
|
||||
myStack2.push(2);
|
||||
myStack2.push(9);
|
||||
|
||||
System.out.println("*********************Stack List Implementation*********************");
|
||||
System.out.println(myStack2.isEmpty()); //will print false
|
||||
System.out.println(myStack2.peek()); //will print 9
|
||||
System.out.println(myStack2.pop()); //will print 9
|
||||
System.out.println(myStack2.peek()); // will print 2
|
||||
System.out.println(myStack2.pop()); //will print 2
|
||||
}
|
||||
}
|
@ -1,212 +0,0 @@
|
||||
public class AVLTree {
|
||||
|
||||
private Node root;
|
||||
|
||||
private class Node {
|
||||
private int key;
|
||||
private int balance;
|
||||
private int height;
|
||||
private Node left, right, parent;
|
||||
|
||||
Node(int k, Node p) {
|
||||
key = k;
|
||||
parent = p;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean insert(int key) {
|
||||
if (root == null)
|
||||
root = new Node(key, null);
|
||||
else {
|
||||
Node n = root;
|
||||
Node parent;
|
||||
while (true) {
|
||||
if (n.key == key)
|
||||
return false;
|
||||
|
||||
parent = n;
|
||||
|
||||
boolean goLeft = n.key > key;
|
||||
n = goLeft ? n.left : n.right;
|
||||
|
||||
if (n == null) {
|
||||
if (goLeft) {
|
||||
parent.left = new Node(key, parent);
|
||||
} else {
|
||||
parent.right = new Node(key, parent);
|
||||
}
|
||||
rebalance(parent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void delete(Node node){
|
||||
if(node.left == null && node.right == null){
|
||||
if(node.parent == null) root = null;
|
||||
else{
|
||||
Node parent = node.parent;
|
||||
if(parent.left == node){
|
||||
parent.left = null;
|
||||
}else parent.right = null;
|
||||
rebalance(parent);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(node.left!=null){
|
||||
Node child = node.left;
|
||||
while (child.right!=null) child = child.right;
|
||||
node.key = child.key;
|
||||
delete(child);
|
||||
}else{
|
||||
Node child = node.right;
|
||||
while (child.left!=null) child = child.left;
|
||||
node.key = child.key;
|
||||
delete(child);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(int delKey) {
|
||||
if (root == null)
|
||||
return;
|
||||
Node node = root;
|
||||
Node child = root;
|
||||
|
||||
while (child != null) {
|
||||
node = child;
|
||||
child = delKey >= node.key ? node.right : node.left;
|
||||
if (delKey == node.key) {
|
||||
delete(node);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void rebalance(Node n) {
|
||||
setBalance(n);
|
||||
|
||||
if (n.balance == -2) {
|
||||
if (height(n.left.left) >= height(n.left.right))
|
||||
n = rotateRight(n);
|
||||
else
|
||||
n = rotateLeftThenRight(n);
|
||||
|
||||
} else if (n.balance == 2) {
|
||||
if (height(n.right.right) >= height(n.right.left))
|
||||
n = rotateLeft(n);
|
||||
else
|
||||
n = rotateRightThenLeft(n);
|
||||
}
|
||||
|
||||
if (n.parent != null) {
|
||||
rebalance(n.parent);
|
||||
} else {
|
||||
root = n;
|
||||
}
|
||||
}
|
||||
|
||||
private Node rotateLeft(Node a) {
|
||||
|
||||
Node b = a.right;
|
||||
b.parent = a.parent;
|
||||
|
||||
a.right = b.left;
|
||||
|
||||
if (a.right != null)
|
||||
a.right.parent = a;
|
||||
|
||||
b.left = a;
|
||||
a.parent = b;
|
||||
|
||||
if (b.parent != null) {
|
||||
if (b.parent.right == a) {
|
||||
b.parent.right = b;
|
||||
} else {
|
||||
b.parent.left = b;
|
||||
}
|
||||
}
|
||||
|
||||
setBalance(a, b);
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private Node rotateRight(Node a) {
|
||||
|
||||
Node b = a.left;
|
||||
b.parent = a.parent;
|
||||
|
||||
a.left = b.right;
|
||||
|
||||
if (a.left != null)
|
||||
a.left.parent = a;
|
||||
|
||||
b.right = a;
|
||||
a.parent = b;
|
||||
|
||||
if (b.parent != null) {
|
||||
if (b.parent.right == a) {
|
||||
b.parent.right = b;
|
||||
} else {
|
||||
b.parent.left = b;
|
||||
}
|
||||
}
|
||||
|
||||
setBalance(a, b);
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private Node rotateLeftThenRight(Node n) {
|
||||
n.left = rotateLeft(n.left);
|
||||
return rotateRight(n);
|
||||
}
|
||||
|
||||
private Node rotateRightThenLeft(Node n) {
|
||||
n.right = rotateRight(n.right);
|
||||
return rotateLeft(n);
|
||||
}
|
||||
|
||||
private int height(Node n) {
|
||||
if (n == null)
|
||||
return -1;
|
||||
return n.height;
|
||||
}
|
||||
|
||||
private void setBalance(Node... nodes) {
|
||||
for (Node n : nodes)
|
||||
reheight(n);
|
||||
n.balance = height(n.right) - height(n.left);
|
||||
}
|
||||
|
||||
public void printBalance() {
|
||||
printBalance(root);
|
||||
}
|
||||
|
||||
private void printBalance(Node n) {
|
||||
if (n != null) {
|
||||
printBalance(n.left);
|
||||
System.out.printf("%s ", n.balance);
|
||||
printBalance(n.right);
|
||||
}
|
||||
}
|
||||
|
||||
private void reheight(Node node){
|
||||
if(node!=null){
|
||||
node.height=1 + Math.max(height(node.left), height(node.right));
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AVLTree tree = new AVLTree();
|
||||
|
||||
System.out.println("Inserting values 1 to 10");
|
||||
for (int i = 1; i < 10; i++)
|
||||
tree.insert(i);
|
||||
|
||||
System.out.print("Printing balance: ");
|
||||
tree.printBalance();
|
||||
}
|
||||
}
|
@ -1,268 +0,0 @@
|
||||
/**
|
||||
* This entire class is used to build a Binary Tree data structure.
|
||||
* There is the Node Class and the Tree Class, both explained below.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* This class implements the nodes that will go on the Binary Tree.
|
||||
* They consist of the data in them, the node to the left, the node
|
||||
* to the right, and the parent from which they came from.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Node{
|
||||
/** Data for the node */
|
||||
public int data;
|
||||
/** The Node to the left of this one */
|
||||
public Node left;
|
||||
/** The Node to the right of this one */
|
||||
public Node right;
|
||||
/** The parent of this node */
|
||||
public Node parent;
|
||||
|
||||
/**
|
||||
* Constructor of Node
|
||||
*
|
||||
* @param value Value to put in the node
|
||||
*/
|
||||
public Node(int value){
|
||||
data = value;
|
||||
left = null;
|
||||
right = null;
|
||||
parent = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A binary tree is a data structure in which an element
|
||||
* has two successors(children). The left child is usually
|
||||
* smaller than the parent, and the right child is usually
|
||||
* bigger.
|
||||
*
|
||||
* @author Unknown
|
||||
*
|
||||
*/
|
||||
class Tree{
|
||||
/** The root of the Binary Tree */
|
||||
private Node root;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public Tree(){
|
||||
root = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to find a Node with a certain value
|
||||
*
|
||||
* @param key Value being looked for
|
||||
* @return The node if it finds it, otherwise returns the parent
|
||||
*/
|
||||
public Node find(int key) {
|
||||
Node current = root;
|
||||
while (current != null) {
|
||||
if(key < current.data) {
|
||||
current = current.left;
|
||||
} else if(key > current.data) {
|
||||
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 + " ");
|
||||
}
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,226 +0,0 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class treeclass {
|
||||
private class Node {
|
||||
int data;
|
||||
ArrayList<Node> child = new ArrayList<>();
|
||||
}
|
||||
|
||||
private Node root;
|
||||
private int size;
|
||||
|
||||
/*
|
||||
A generic tree is a tree which can have as many children as it can be
|
||||
It might be possible that every node present is directly connected to
|
||||
root node.
|
||||
|
||||
In this code
|
||||
Every function has two copies: one function is helper function which can be called from
|
||||
main and from that function a private function is called which will do the actual work.
|
||||
I have done this, while calling from main one have to give minimum parameters.
|
||||
|
||||
*/
|
||||
public treeclass() { //Constructor
|
||||
Scanner scn = new Scanner(System.in);
|
||||
root = create_treeG(null, 0, scn);
|
||||
}
|
||||
|
||||
private Node create_treeG(Node node, int childindx, Scanner scn) {
|
||||
// display
|
||||
if (node == null) {
|
||||
System.out.println("Enter root's data");
|
||||
} else {
|
||||
System.out.println("Enter data of parent of index " + node.data + " " + childindx);
|
||||
}
|
||||
// input
|
||||
node = new Node();
|
||||
node.data = scn.nextInt();
|
||||
System.out.println("number of children");
|
||||
int number = scn.nextInt();
|
||||
for (int i = 0; i < number; i++) {
|
||||
Node childd = create_treeG(node, i, scn);
|
||||
size++;
|
||||
node.child.add(childd);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to display the generic tree
|
||||
*/
|
||||
public void display() { //Helper function
|
||||
display_1(root);
|
||||
return;
|
||||
}
|
||||
|
||||
private void display_1(Node parent) {
|
||||
System.out.print(parent.data + "=>");
|
||||
for (int i = 0; i < parent.child.size(); i++) {
|
||||
System.out.print(parent.child.get(i).data + " ");
|
||||
}
|
||||
System.out.println(".");
|
||||
for (int i = 0; i < parent.child.size(); i++) {
|
||||
display_1(parent.child.get(i));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
One call store the size directly but if you are asked compute size this function to calcuate
|
||||
size goes as follows
|
||||
*/
|
||||
|
||||
public int size2call() {
|
||||
return size2(root);
|
||||
}
|
||||
|
||||
public int size2(Node roott) {
|
||||
int sz = 0;
|
||||
for (int i = 0; i < roott.child.size(); i++) {
|
||||
sz += size2(roott.child.get(i));
|
||||
}
|
||||
return sz + 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to compute maximum value in the generic tree
|
||||
*/
|
||||
public int maxcall() {
|
||||
int maxi = root.data;
|
||||
return max(root, maxi);
|
||||
}
|
||||
|
||||
private int max(Node roott, int maxi) {
|
||||
if (maxi < roott.data)
|
||||
maxi = roott.data;
|
||||
for (int i = 0; i < roott.child.size(); i++) {
|
||||
maxi = max(roott.child.get(i), maxi);
|
||||
}
|
||||
|
||||
return maxi;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to compute HEIGHT of the generic tree
|
||||
*/
|
||||
|
||||
public int heightcall() {
|
||||
return height(root) - 1;
|
||||
}
|
||||
|
||||
private int height(Node node) {
|
||||
int h = 0;
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
int k = height(node.child.get(i));
|
||||
if (k > h)
|
||||
h = k;
|
||||
}
|
||||
return h + 1;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to find whether a number is present in the generic tree or not
|
||||
*/
|
||||
|
||||
public boolean findcall(int info) {
|
||||
return find(root, info);
|
||||
}
|
||||
|
||||
private boolean find(Node node, int info) {
|
||||
if (node.data == info)
|
||||
return true;
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
if (find(node.child.get(i), info))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to calculate depth of generic tree
|
||||
*/
|
||||
public void depthcaller(int dep) {
|
||||
depth(root, dep);
|
||||
}
|
||||
|
||||
public void depth(Node node, int dep) {
|
||||
if (dep == 0) {
|
||||
System.out.println(node.data);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
depth(node.child.get(i), dep - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in pre-order
|
||||
*/
|
||||
public void preordercall() {
|
||||
preorder(root);
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
private void preorder(Node node) {
|
||||
System.out.print(node.data + " ");
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
preorder(node.child.get(i));
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in post-order
|
||||
*/
|
||||
public void postordercall() {
|
||||
postorder(root);
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
private void postorder(Node node) {
|
||||
for (int i = 0; i < node.child.size(); i++)
|
||||
postorder(node.child.get(i));
|
||||
System.out.print(node.data + " ");
|
||||
}
|
||||
|
||||
/*
|
||||
Function to print generic tree in level-order
|
||||
*/
|
||||
|
||||
public void levelorder() {
|
||||
LinkedList<Node> q = new LinkedList<>();
|
||||
q.addLast(root);
|
||||
while (!q.isEmpty()) {
|
||||
int k = q.getFirst().data;
|
||||
System.out.print(k + " ");
|
||||
|
||||
for (int i = 0; i < q.getFirst().child.size(); i++) {
|
||||
q.addLast(q.getFirst().child.get(i));
|
||||
}
|
||||
q.removeFirst();
|
||||
}
|
||||
System.out.println(".");
|
||||
}
|
||||
|
||||
/*
|
||||
Function to remove all leaves of generic tree
|
||||
*/
|
||||
public void removeleavescall() {
|
||||
removeleaves(root);
|
||||
}
|
||||
|
||||
private void removeleaves(Node node) {
|
||||
ArrayList<Integer> arr = new ArrayList<>();
|
||||
for (int i = 0; i < node.child.size(); i++) {
|
||||
if (node.child.get(i).child.size() == 0) {
|
||||
arr.add(i);
|
||||
// node.child.remove(i);
|
||||
// i--;
|
||||
} else
|
||||
removeleaves(node.child.get(i));
|
||||
}
|
||||
for (int i = arr.size() - 1; i >= 0; i--) {
|
||||
node.child.remove(arr.get(i) + 0);
|
||||
}
|
||||
}
|
||||
|
@ -1,78 +0,0 @@
|
||||
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()
|
||||
{
|
||||
root = null;
|
||||
}
|
||||
|
||||
/* function to print level order traversal of tree*/
|
||||
void printLevelOrder()
|
||||
{
|
||||
int h = height(root);
|
||||
int i;
|
||||
for (i=1; i<=h; i++)
|
||||
printGivenLevel(root, i);
|
||||
}
|
||||
|
||||
/* Compute the "height" of a tree -- the number of
|
||||
nodes along the longest path from the root node
|
||||
down to the farthest leaf node.*/
|
||||
int height(Node root)
|
||||
{
|
||||
if (root == null)
|
||||
return 0;
|
||||
else
|
||||
{
|
||||
/* compute height of each subtree */
|
||||
int lheight = height(root.left);
|
||||
int rheight = height(root.right);
|
||||
|
||||
/* use the larger one */
|
||||
if (lheight > rheight)
|
||||
return(lheight+1);
|
||||
else return(rheight+1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Print nodes at the given level */
|
||||
void printGivenLevel (Node root ,int level)
|
||||
{
|
||||
if (root == null)
|
||||
return;
|
||||
if (level == 1)
|
||||
System.out.print(root.data + " ");
|
||||
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();
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
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 {
|
||||
|
||||
Node root;
|
||||
|
||||
/* Given a binary tree. Print its nodes in level order
|
||||
using array for implementing queue */
|
||||
void printLevelOrder()
|
||||
{
|
||||
Queue<Node> queue = new LinkedList<Node>();
|
||||
queue.add(root);
|
||||
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();
|
||||
}
|
||||
}
|
@ -1,105 +0,0 @@
|
||||
// Java program to print top view of Binary tree
|
||||
import java.util.*;
|
||||
|
||||
// Class for a tree node
|
||||
class TreeNode
|
||||
{
|
||||
// Members
|
||||
int key;
|
||||
TreeNode left, right;
|
||||
|
||||
// Constructor
|
||||
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)
|
||||
{
|
||||
node = n;
|
||||
hd = h;
|
||||
}
|
||||
}
|
||||
|
||||
// Class for a Binary Tree
|
||||
class Tree
|
||||
{
|
||||
TreeNode root;
|
||||
|
||||
// Constructors
|
||||
public Tree() { root = null; }
|
||||
public Tree(TreeNode n) { root = n; }
|
||||
|
||||
// This method prints nodes in top view of binary tree
|
||||
public void printTopView()
|
||||
{
|
||||
// base case
|
||||
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())
|
||||
{
|
||||
// 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))
|
||||
{
|
||||
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));
|
||||
if (n.right != null)
|
||||
Q.add(new QItem(n.right, hd+1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver class to test above methods
|
||||
public class PrintTopViewofTree
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
/* Create following Binary Tree
|
||||
1
|
||||
/ \
|
||||
2 3
|
||||
\
|
||||
4
|
||||
\
|
||||
5
|
||||
\
|
||||
6*/
|
||||
TreeNode root = new TreeNode(1);
|
||||
root.left = new TreeNode(2);
|
||||
root.right = new TreeNode(3);
|
||||
root.left.right = new TreeNode(4);
|
||||
root.left.right.right = new TreeNode(5);
|
||||
root.left.right.right.right = new TreeNode(6);
|
||||
Tree t = new Tree(root);
|
||||
System.out.println("Following are nodes in top view of Binary Tree");
|
||||
t.printTopView();
|
||||
}
|
||||
}
|
@ -1,330 +0,0 @@
|
||||
/**
|
||||
*
|
||||
* @author jack870131
|
||||
*/
|
||||
public class RedBlackBST {
|
||||
|
||||
private final int R = 0;
|
||||
private final int B = 1;
|
||||
|
||||
private class Node {
|
||||
|
||||
int key = -1, color = B;
|
||||
Node left = nil, right = nil, p = nil;
|
||||
|
||||
Node(int key) {
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
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 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 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;
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
@ -1,124 +0,0 @@
|
||||
import java.util.LinkedList;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
// Driver Program
|
||||
public class TreeTraversal {
|
||||
public static void main(String[] args) {
|
||||
Node tree = new Node(5);
|
||||
tree.insert(3);
|
||||
tree.insert(2);
|
||||
tree.insert(7);
|
||||
tree.insert(4);
|
||||
tree.insert(6);
|
||||
tree.insert(8);
|
||||
|
||||
// Prints 5 3 2 4 7 6 8
|
||||
System.out.println("Pre order traversal:");
|
||||
tree.printPreOrder();
|
||||
System.out.println();
|
||||
// Prints 2 3 4 5 6 7 8
|
||||
System.out.println("In order traversal:");
|
||||
tree.printInOrder();
|
||||
System.out.println();
|
||||
// Prints 2 4 3 6 8 7 5
|
||||
System.out.println("Post order traversal:");
|
||||
tree.printPostOrder();
|
||||
System.out.println();
|
||||
// Prints 5 3 7 2 4 6 8
|
||||
System.out.println("Level order traversal:");
|
||||
tree.printLevelOrder();
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void insert (int value) {
|
||||
if (value < data) {
|
||||
if (left == null) {
|
||||
left = new Node(value);
|
||||
}
|
||||
else {
|
||||
left.insert(value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (right == null) {
|
||||
right = new Node(value);
|
||||
}
|
||||
else {
|
||||
right.insert(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void printInOrder() {
|
||||
if (left != null) {
|
||||
left.printInOrder();
|
||||
}
|
||||
System.out.print(data + " ");
|
||||
if (right != null) {
|
||||
right.printInOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public void printPreOrder() {
|
||||
System.out.print(data + " ");
|
||||
if (left != null) {
|
||||
left.printPreOrder();
|
||||
}
|
||||
if (right != null) {
|
||||
right.printPreOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public void printPostOrder() {
|
||||
if (left != null) {
|
||||
left.printPostOrder();
|
||||
}
|
||||
if (right != null) {
|
||||
right.printPostOrder();
|
||||
}
|
||||
System.out.print(data + " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
while (queue.size() > 0) {
|
||||
Node head = queue.remove();
|
||||
System.out.print(head.data + " ");
|
||||
// Add children of recently-printed node to queue, if they exist.
|
||||
if (head.left != null) {
|
||||
queue.add(head.left);
|
||||
}
|
||||
if (head.right != null) {
|
||||
queue.add(head.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,135 +0,0 @@
|
||||
//Trie Data structure implementation without any libraries */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
|
||||
*
|
||||
*/
|
||||
import java.util.Scanner;
|
||||
|
||||
public class TrieImp {
|
||||
|
||||
public class TrieNode {
|
||||
TrieNode[] child;
|
||||
boolean end;
|
||||
|
||||
public TrieNode(){
|
||||
child = new TrieNode[26];
|
||||
end = false;
|
||||
}
|
||||
}
|
||||
private final TrieNode root;
|
||||
public TrieImp(){
|
||||
root = new TrieNode();
|
||||
}
|
||||
|
||||
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){
|
||||
node = new TrieNode();
|
||||
currentNode.child[word.charAt(i)-'a']=node;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
currentNode.end = true;
|
||||
}
|
||||
public boolean search(String word){
|
||||
TrieNode currentNode = root;
|
||||
for(int i=0;i<word.length();i++){
|
||||
char ch = word.charAt(i);
|
||||
TrieNode node = currentNode.child[ch-'a'];
|
||||
if(node == null){
|
||||
return false;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
return currentNode.end;
|
||||
}
|
||||
|
||||
public boolean delete(String word){
|
||||
TrieNode currentNode = root;
|
||||
for(int i=0;i<word.length();i++){
|
||||
char ch = word.charAt(i);
|
||||
TrieNode node = currentNode.child[ch-'a'];
|
||||
if(node == null){
|
||||
return false;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
if(currentNode.end == true){
|
||||
currentNode.end = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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){
|
||||
return word.matches("^[a-z]+$");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
TrieImp obj = new TrieImp();
|
||||
String word;
|
||||
@SuppressWarnings("resource")
|
||||
Scanner scan = new Scanner(System.in);
|
||||
sop("string should contain only a-z character for all operation");
|
||||
while(true){
|
||||
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
|
||||
try{
|
||||
int t = scan.nextInt();
|
||||
switch (t) {
|
||||
case 1:
|
||||
word = scan.next();
|
||||
if(isValid(word))
|
||||
obj.insert(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
break;
|
||||
case 2:
|
||||
word = scan.next();
|
||||
boolean resS=false;
|
||||
if(isValid(word))
|
||||
resS = obj.search(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
if(resS)
|
||||
sop("word found");
|
||||
else
|
||||
sop("word not found");
|
||||
break;
|
||||
case 3:
|
||||
word = scan.next();
|
||||
boolean resD=false;
|
||||
if(isValid(word))
|
||||
resD = obj.delete(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
if(resD){
|
||||
sop("word got deleted successfully");
|
||||
}else{
|
||||
sop("word not found");
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
sop("Quit successfully");
|
||||
System.exit(1);
|
||||
break;
|
||||
default:
|
||||
sop("Input int from 1-4");
|
||||
break;
|
||||
}
|
||||
}catch(Exception e){
|
||||
String badInput = scan.next();
|
||||
sop("This is bad input: " + badInput);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
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() {
|
||||
return isBSTUtil(root, Integer.MIN_VALUE,
|
||||
Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
/* Returns true if the given tree is a BST and its
|
||||
values are >= min and <= max. */
|
||||
boolean isBSTUtil(Node node, int min, int max)
|
||||
{
|
||||
/* an empty tree is BST */
|
||||
if (node == null)
|
||||
return true;
|
||||
|
||||
/* false if this node violates the min/max constraints */
|
||||
if (node.data < min || node.data > max)
|
||||
return false;
|
||||
|
||||
/* otherwise check the subtrees recursively
|
||||
tightening the min/max constraints */
|
||||
// Allow only distinct values
|
||||
return (isBSTUtil(node.left, min, node.data-1) &&
|
||||
isBSTUtil(node.right, node.data+1, max));
|
||||
}
|
||||
|
||||
/* 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");
|
||||
}
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class CoinChange {
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
|
||||
int amount = 12;
|
||||
int[] coins = {1, 2, 5};
|
||||
|
||||
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the number of combinations of getting change for a given amount and change coins
|
||||
*
|
||||
* @param coins The list of coins
|
||||
* @param amount The amount for which we need to find the change
|
||||
* Finds the number of combinations of change
|
||||
**/
|
||||
public static int change(int[] coins, int amount) {
|
||||
|
||||
int[] combinations = new int[amount+1];
|
||||
combinations[0] = 1;
|
||||
|
||||
for (int coin : coins) {
|
||||
for (int i=coin; i<amount+1; i++) {
|
||||
combinations[i] += combinations[i-coin];
|
||||
}
|
||||
// Uncomment the below line to see the state of combinations for each coin
|
||||
// printAmount(combinations);
|
||||
}
|
||||
|
||||
return combinations[amount];
|
||||
}
|
||||
|
||||
// A basic print method which prints all the contents of the array
|
||||
public static void printAmount(int[] arr) {
|
||||
|
||||
for (int i=0; i<arr.length; i++) {
|
||||
System.out.print(arr[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
}
|
@ -1,89 +0,0 @@
|
||||
/**
|
||||
Author : SUBHAM SANGHAI
|
||||
A Dynamic Programming based solution for Edit Distance problem In Java
|
||||
**/
|
||||
|
||||
/**Description of Edit Distance with an Example:
|
||||
|
||||
Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another,
|
||||
by counting the minimum number of operations required to transform one string into the other. The
|
||||
distance operations are the removal, insertion, or substitution of a character in the string.
|
||||
|
||||
|
||||
The Distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
|
||||
|
||||
kitten → sitten (substitution of "s" for "k")
|
||||
sitten → sittin (substitution of "i" for "e")
|
||||
sittin → sitting (insertion of "g" at the end).**/
|
||||
|
||||
import java.util.Scanner;
|
||||
public class Edit_Distance
|
||||
{
|
||||
|
||||
|
||||
|
||||
public static int minDistance(String word1, String word2)
|
||||
{
|
||||
int len1 = word1.length();
|
||||
int len2 = word2.length();
|
||||
// len1+1, len2+1, because finally return dp[len1][len2]
|
||||
int[][] dp = new int[len1 + 1][len2 + 1];
|
||||
/* If second string is empty, the only option is to
|
||||
insert all characters of first string into second*/
|
||||
for (int i = 0; i <= len1; i++)
|
||||
{
|
||||
dp[i][0] = i;
|
||||
}
|
||||
/* If first string is empty, the only option is to
|
||||
insert all characters of second string into first*/
|
||||
for (int j = 0; j <= len2; j++)
|
||||
{
|
||||
dp[0][j] = j;
|
||||
}
|
||||
//iterate though, and check last char
|
||||
for (int i = 0; i < len1; i++)
|
||||
{
|
||||
char c1 = word1.charAt(i);
|
||||
for (int j = 0; j < len2; j++)
|
||||
{
|
||||
char c2 = word2.charAt(j);
|
||||
//if last two chars equal
|
||||
if (c1 == c2)
|
||||
{
|
||||
//update dp value for +1 length
|
||||
dp[i + 1][j + 1] = dp[i][j];
|
||||
}
|
||||
else
|
||||
{
|
||||
/* if two characters are different ,
|
||||
then take the minimum of the various operations(i.e insertion,removal,substitution)*/
|
||||
int replace = dp[i][j] + 1;
|
||||
int insert = dp[i][j + 1] + 1;
|
||||
int delete = dp[i + 1][j] + 1;
|
||||
|
||||
int min = replace > insert ? insert : replace;
|
||||
min = delete > min ? min : delete;
|
||||
dp[i + 1][j + 1] = min;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* return the final answer , after traversing through both the strings*/
|
||||
return dp[len1][len2];
|
||||
}
|
||||
|
||||
|
||||
// Driver program to test above function
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner input = new Scanner(System.in);
|
||||
String s1,s2;
|
||||
System.out.println("Enter the First String");
|
||||
s1 = input.nextLine();
|
||||
System.out.println("Enter the Second String");
|
||||
s2 = input.nextLine();
|
||||
//ans stores the final Edit Distance between the two strings
|
||||
int ans=0;
|
||||
ans=minDistance(s1,s2);
|
||||
System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 +"\" is "+ans);
|
||||
}
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
//Dynamic Programming solution for the Egg Dropping Puzzle
|
||||
public class EggDropping
|
||||
{
|
||||
|
||||
// min trials with n eggs and m floors
|
||||
|
||||
private static int minTrials(int n, int m)
|
||||
{
|
||||
|
||||
int eggFloor[][] = new int[n+1][m+1];
|
||||
int result, x;
|
||||
|
||||
for (int i = 1; i <= n; i++)
|
||||
{
|
||||
eggFloor[i][0] = 0; // Zero trial for zero floor.
|
||||
eggFloor[i][1] = 1; // One trial for one floor
|
||||
}
|
||||
|
||||
// j trials for only 1 egg
|
||||
|
||||
for (int j = 1; j <= m; j++)
|
||||
eggFloor[1][j] = j;
|
||||
|
||||
// Using bottom-up approach in DP
|
||||
|
||||
for (int i = 2; i <= n; i++)
|
||||
{
|
||||
for (int j = 2; j <= m; j++)
|
||||
{
|
||||
eggFloor[i][j] = Integer.MAX_VALUE;
|
||||
for (x = 1; x <= j; x++)
|
||||
{
|
||||
result = 1 + Math.max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
|
||||
|
||||
//choose min of all values for particular x
|
||||
if (result < eggFloor[i][j])
|
||||
eggFloor[i][j] = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return eggFloor[n][m];
|
||||
}
|
||||
|
||||
//testing program
|
||||
public static void main(String args[])
|
||||
{
|
||||
int n = 2, m = 4;
|
||||
//result outputs min no. of trials in worst case for n eggs and m floors
|
||||
int result = minTrials(n, m);
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
@ -1,75 +0,0 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
public class Fibonacci {
|
||||
|
||||
private static Map<Integer,Integer> map = new HashMap<Integer,Integer>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
int n = Integer.parseInt(br.readLine());
|
||||
|
||||
System.out.println(fibMemo(n)); // Returns 8 for n = 6
|
||||
System.out.println(fibBotUp(n)); // Returns 8 for n = 6
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the nth fibonacci number using memoization technique
|
||||
*
|
||||
* @param n The input n for which we have to determine the fibonacci number
|
||||
* Outputs the nth fibonacci number
|
||||
**/
|
||||
|
||||
private static int fibMemo(int n) {
|
||||
if (map.containsKey(n)) {
|
||||
return map.get(n);
|
||||
}
|
||||
|
||||
int f;
|
||||
|
||||
if (n <= 2) {
|
||||
f = 1;
|
||||
}
|
||||
else {
|
||||
f = fibMemo(n-1) + fibMemo(n-2);
|
||||
map.put(n,f);
|
||||
}
|
||||
|
||||
return f;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method finds the nth fibonacci number using bottom up
|
||||
*
|
||||
* @param n The input n for which we have to determine the fibonacci number
|
||||
* Outputs the nth fibonacci number
|
||||
**/
|
||||
|
||||
private static int fibBotUp(int n) {
|
||||
|
||||
Map<Integer,Integer> fib = new HashMap<Integer,Integer>();
|
||||
|
||||
for (int i=1;i<n+1;i++) {
|
||||
int f = 1;
|
||||
if (i<=2) {
|
||||
f = 1;
|
||||
}
|
||||
else {
|
||||
f = fib.get(i-1) + fib.get(i-2);
|
||||
}
|
||||
fib.put(i, f);
|
||||
}
|
||||
|
||||
return fib.get(n);
|
||||
}
|
||||
}
|
||||
|
@ -1,55 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Program to implement Kadane’s Algorithm to
|
||||
* calculate maximum contiguous subarray sum of an array
|
||||
* Time Complexity: O(n)
|
||||
*
|
||||
* @author Nishita Aggarwal
|
||||
*
|
||||
*/
|
||||
|
||||
public class KadaneAlgorithm {
|
||||
|
||||
/**
|
||||
* This method implements Kadane's Algorithm
|
||||
*
|
||||
* @param arr The input array
|
||||
* @return The maximum contiguous subarray sum of the array
|
||||
*
|
||||
*/
|
||||
static int largestContiguousSum(int arr[]){
|
||||
int i,len=arr.length,cursum=0,maxsum=Integer.MIN_VALUE;
|
||||
if(len==0) //empty array
|
||||
return 0;
|
||||
for(i=0;i<len;i++){
|
||||
cursum+=arr[i];
|
||||
if(cursum>maxsum){
|
||||
maxsum=cursum;
|
||||
}
|
||||
if(cursum<=0){
|
||||
cursum=0;
|
||||
}
|
||||
}
|
||||
return maxsum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Scanner sc=new Scanner(System.in);
|
||||
int n,arr[],i;
|
||||
n=sc.nextInt();
|
||||
arr=new int[n];
|
||||
for(i=0;i<n;i++){
|
||||
arr[i]=sc.nextInt();
|
||||
}
|
||||
int maxContSum=largestContiguousSum(arr);
|
||||
System.out.println(maxContSum);
|
||||
sc.close();
|
||||
}
|
||||
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
// A Dynamic Programming based solution for 0-1 Knapsack problem
|
||||
|
||||
public class Knapsack
|
||||
{
|
||||
|
||||
private static int knapSack(int W, int wt[], int val[], int n)
|
||||
{
|
||||
int i, w;
|
||||
int rv[][] = new int[n+1][W+1]; //rv means return value
|
||||
|
||||
// Build table rv[][] in bottom up manner
|
||||
for (i = 0; i <= n; i++)
|
||||
{
|
||||
for (w = 0; w <= W; w++)
|
||||
{
|
||||
if (i==0 || w==0)
|
||||
rv[i][w] = 0;
|
||||
else if (wt[i-1] <= w)
|
||||
rv[i][w] = Math.max(val[i-1] + rv[i-1][w-wt[i-1]], rv[i-1][w]);
|
||||
else
|
||||
rv[i][w] = rv[i-1][w];
|
||||
}
|
||||
}
|
||||
|
||||
return rv[n][W];
|
||||
}
|
||||
|
||||
|
||||
// Driver program to test above function
|
||||
public static void main(String args[])
|
||||
{
|
||||
int val[] = new int[]{50, 100, 130};
|
||||
int wt[] = new int[]{10, 20, 40};
|
||||
int W = 50;
|
||||
int n = val.length;
|
||||
System.out.println(knapSack(W, wt, val, n));
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
/**
|
||||
*
|
||||
* @author Kshitij VERMA (github.com/kv19971)
|
||||
* LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance)
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
public class LevenshteinDistance{
|
||||
private static int minimum(int a, int b, int c){
|
||||
if(a < b && a < c){
|
||||
return a;
|
||||
}else if(b < a && b < c){
|
||||
return b;
|
||||
}else{
|
||||
return c;
|
||||
}
|
||||
}
|
||||
private static int calculate_distance(String a, String b){
|
||||
int len_a = a.length() + 1;
|
||||
int len_b = b.length() + 1;
|
||||
int [][] distance_mat = new int[len_a][len_b];
|
||||
for(int i = 0; i < len_a; i++){
|
||||
distance_mat[i][0] = i;
|
||||
}
|
||||
for(int j = 0; j < len_b; j++){
|
||||
distance_mat[0][j] = j;
|
||||
}
|
||||
for(int i = 0; i < len_a; i++){
|
||||
for(int j = 0; i < len_b; j++){
|
||||
int cost;
|
||||
if (a.charAt(i) == b.charAt(j)){
|
||||
cost = 0;
|
||||
}else{
|
||||
cost = 1;
|
||||
}
|
||||
distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost;
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return distance_mat[len_a-1][len_b-1];
|
||||
|
||||
}
|
||||
public static void main(String [] args){
|
||||
String a = ""; // enter your string here
|
||||
String b = ""; // enter your string here
|
||||
|
||||
System.out.print("Levenshtein distance between "+a + " and "+b+ " is: ");
|
||||
System.out.println(calculate_distance(a,b));
|
||||
|
||||
|
||||
}
|
||||
}
|
@ -1,66 +0,0 @@
|
||||
class LongestCommonSubsequence {
|
||||
|
||||
public static String getLCS(String str1, String str2) {
|
||||
|
||||
//At least one string is null
|
||||
if(str1 == null || str2 == null)
|
||||
return null;
|
||||
|
||||
//At least one string is empty
|
||||
if(str1.length() == 0 || str2.length() == 0)
|
||||
return "";
|
||||
|
||||
String[] arr1 = str1.split("");
|
||||
String[] arr2 = str2.split("");
|
||||
|
||||
//lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2
|
||||
int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1];
|
||||
|
||||
for(int i = 0; i < arr1.length + 1; i++)
|
||||
lcsMatrix[i][0] = 0;
|
||||
for(int j = 1; j < arr2.length + 1; j++)
|
||||
lcsMatrix[0][j] = 0;
|
||||
for(int i = 1; i < arr1.length + 1; i++) {
|
||||
for(int j = 1; j < arr2.length + 1; j++) {
|
||||
if(arr1[i-1].equals(arr2[j-1])) {
|
||||
lcsMatrix[i][j] = lcsMatrix[i-1][j-1] + 1;
|
||||
} else {
|
||||
lcsMatrix[i][j] = lcsMatrix[i-1][j] > lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return lcsString(str1, str2, lcsMatrix);
|
||||
}
|
||||
|
||||
public static String lcsString (String str1, String str2, int[][] lcsMatrix) {
|
||||
StringBuilder lcs = new StringBuilder();
|
||||
int i = str1.length(),
|
||||
j = str2.length();
|
||||
while(i > 0 && j > 0) {
|
||||
if(str1.charAt(i-1) == str2.charAt(j-1)) {
|
||||
lcs.append(str1.charAt(i-1));
|
||||
i--;
|
||||
j--;
|
||||
} else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) {
|
||||
i--;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return lcs.reverse().toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str1 = "DSGSHSRGSRHTRD";
|
||||
String str2 = "DATRGAGTSHS";
|
||||
String lcs = getLCS(str1, str2);
|
||||
|
||||
//Print LCS
|
||||
if(lcs != null) {
|
||||
System.out.println("String 1: " + str1);
|
||||
System.out.println("String 2: " + str2);
|
||||
System.out.println("LCS: " + lcs);
|
||||
System.out.println("LCS length: " + lcs.length());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Afrizal Fikri (https://github.com/icalF)
|
||||
*
|
||||
*/
|
||||
public class LongestIncreasingSubsequence {
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int n = sc.nextInt();
|
||||
|
||||
int ar[] = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
ar[i] = sc.nextInt();
|
||||
}
|
||||
|
||||
System.out.println(LIS(ar));
|
||||
}
|
||||
|
||||
private static int upperBound(int[] ar, int l, int r, int key) {
|
||||
while (l < r-1) {
|
||||
int m = (l + r) / 2;
|
||||
if (ar[m] >= key)
|
||||
r = m;
|
||||
else
|
||||
l = m;
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
private static int LIS(int[] array) {
|
||||
int N = array.length;
|
||||
if (N == 0)
|
||||
return 0;
|
||||
|
||||
int[] tail = new int[N];
|
||||
int length = 1; // always points empty slot in tail
|
||||
|
||||
tail[0] = array[0];
|
||||
for (int i = 1; i < N; i++) {
|
||||
|
||||
// new smallest value
|
||||
if (array[i] < tail[0])
|
||||
tail[0] = array[i];
|
||||
|
||||
// array[i] extends largest subsequence
|
||||
else if (array[i] > tail[length-1])
|
||||
tail[length++] = array[i];
|
||||
|
||||
// array[i] will become end candidate of an existing subsequence or
|
||||
// Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
|
||||
// (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
|
||||
else
|
||||
tail[upperBound(tail, -1, length-1, array[i])] = array[i];
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
/* A Dynamic Programming solution for Rod cutting problem
|
||||
Returns the best obtainable price for a rod of
|
||||
length n and price[] as prices of different pieces */
|
||||
|
||||
public class RodCutting {
|
||||
|
||||
private static int cutRod(int price[],int n)
|
||||
{
|
||||
int val[] = new int[n+1];
|
||||
val[0] = 0;
|
||||
|
||||
for (int i = 1; i<=n; i++)
|
||||
{
|
||||
int max_val = Integer.MIN_VALUE;
|
||||
for (int j = 0; j < i; j++)
|
||||
max_val = Math.max(max_val,price[j] + val[i-j-1]);
|
||||
|
||||
val[i] = max_val;
|
||||
}
|
||||
|
||||
return val[n];
|
||||
}
|
||||
|
||||
//main function to test
|
||||
public static void main(String args[])
|
||||
{
|
||||
int arr[] = new int[] {2, 5, 13, 19, 20};
|
||||
int size = arr.length;
|
||||
System.out.println("Maximum Obtainable Value is " +
|
||||
cutRod(arr, size));
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class MinimizingLateness {
|
||||
|
||||
private static class Schedule { // Schedule class
|
||||
int t = 0; // Time required for the operation to be performed
|
||||
int d = 0; // Time the job should be completed
|
||||
int s = 0; // Start time of the task
|
||||
int f = 0; // End time of the operation
|
||||
|
||||
public Schedule(int t, int d) {
|
||||
this.t = t;
|
||||
this.d = d;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// TODO Auto-generated method stub
|
||||
StringTokenizer token;
|
||||
|
||||
String ch;
|
||||
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
|
||||
int indexCount; // size of array index
|
||||
ch = in.readLine();
|
||||
indexCount = Integer.parseInt(ch); // The first line specifies the size of the operation (= the size of the array)
|
||||
System.out.println("Input Data : ");
|
||||
System.out.println(indexCount); // number of operations
|
||||
Schedule array[] = new Schedule[indexCount]; // Create an array to hold the operation
|
||||
int i = 0;
|
||||
while ((ch = in.readLine()) != null) {
|
||||
token = new StringTokenizer(ch, " ");
|
||||
// Include the time required for the operation to be performed in the array and the time it should be completed.
|
||||
array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
|
||||
i++; // 다음 인덱스
|
||||
System.out.println(array[i - 1].t + " " + array[i - 1].d);
|
||||
}
|
||||
|
||||
int tryTime = 0; // Total time worked
|
||||
int lateness = 0; // Lateness
|
||||
for (int j = 0; j < indexCount - 1; j++) {
|
||||
array[j].s = tryTime; // Start time of the task
|
||||
array[j].f = tryTime + array[j].t; // Time finished
|
||||
tryTime = tryTime + array[j].t; // Add total work time
|
||||
// Lateness
|
||||
lateness = lateness + Math.max(0, tryTime - array[j].d);
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("Output Data : ");
|
||||
System.out.println(lateness);
|
||||
}
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
6
|
||||
3 6
|
||||
2 8
|
||||
1 9
|
||||
4 9
|
||||
3 14
|
||||
2 15
|
@ -1,41 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
public class PalindromePrime {
|
||||
|
||||
public static void main(String[] args) { // Main funtion
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Enter the quantity of First Palindromic Primes you want");
|
||||
int n = in.nextInt(); // Input of how mant first pallindromic prime we want
|
||||
funtioning(n); // calling funtion - functioning
|
||||
}
|
||||
|
||||
public static boolean prime(int num) { // checking if number is prime or not
|
||||
for (int divisor = 2; divisor <= num / 2; divisor++) {
|
||||
if (num % divisor == 0) {
|
||||
return false; // false if not prime
|
||||
}
|
||||
}
|
||||
return true; // True if prime
|
||||
}
|
||||
|
||||
public static int reverse(int n){ // Returns the reverse of the number
|
||||
int reverse = 0;
|
||||
while(n!=0){
|
||||
reverse = reverse * 10;
|
||||
reverse = reverse + n%10;
|
||||
n = n/10;
|
||||
}
|
||||
return reverse;
|
||||
}
|
||||
|
||||
public static void funtioning(int y){
|
||||
int count =0;
|
||||
int num = 2;
|
||||
while(count < y){
|
||||
if(prime(num) && num == reverse(num)){ // number is prime and it's reverse is same
|
||||
count++; // counts check when to terminate while loop
|
||||
System.out.print(num + "\n"); // Print the Palindromic Prime
|
||||
}
|
||||
num++; // inrease iterator value by one
|
||||
}
|
||||
}
|
||||
};
|
@ -1,73 +0,0 @@
|
||||
public class heap_sort
|
||||
{
|
||||
public void sort(int arr[])
|
||||
{
|
||||
int n = arr.length;
|
||||
|
||||
// Build heap (rearrange array)
|
||||
for (int i = n / 2 - 1; i >= 0; i--)
|
||||
heapify(arr, n, i);
|
||||
|
||||
// One by one extract an element from heap
|
||||
for (int i=n-1; i>=0; i--)
|
||||
{
|
||||
// Move current root to end
|
||||
int temp = arr[0];
|
||||
arr[0] = arr[i];
|
||||
arr[i] = temp;
|
||||
|
||||
// call max heapify on the reduced heap
|
||||
heapify(arr, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// To heapify a subtree rooted with node i which is
|
||||
// an index in arr[]. n is size of heap
|
||||
void heapify(int arr[], int n, int i)
|
||||
{
|
||||
int largest = i; // Initialize largest as root
|
||||
int l = 2*i + 1; // left = 2*i + 1
|
||||
int r = 2*i + 2; // right = 2*i + 2
|
||||
|
||||
// If left child is larger than root
|
||||
if (l < n && arr[l] > arr[largest])
|
||||
largest = l;
|
||||
|
||||
// If right child is larger than largest so far
|
||||
if (r < n && arr[r] > arr[largest])
|
||||
largest = r;
|
||||
|
||||
// If largest is not root
|
||||
if (largest != i)
|
||||
{
|
||||
int swap = arr[i];
|
||||
arr[i] = arr[largest];
|
||||
arr[largest] = swap;
|
||||
|
||||
// Recursively heapify the affected sub-tree
|
||||
heapify(arr, n, largest);
|
||||
}
|
||||
}
|
||||
|
||||
/* A utility function to print array of size n */
|
||||
static void printArray(int arr[])
|
||||
{
|
||||
int n = arr.length;
|
||||
for (int i=0; i<n; ++i)
|
||||
System.out.print(arr[i]+" ");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// Driver program
|
||||
public static void main(String args[])
|
||||
{
|
||||
int arr[] = {12, 11, 13, 5, 6, 7};
|
||||
int n = arr.length;
|
||||
|
||||
heap_sort ob = new heap_sort();
|
||||
ob.sort(arr);
|
||||
|
||||
System.out.println("Sorted array is");
|
||||
printArray(arr);
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
//Oskar Enmalm 29/9/17
|
||||
//An Abecadrian is a word where each letter is in alphabetical order
|
||||
|
||||
class Abecedarian{
|
||||
|
||||
public static boolean isAbecedarian(String s){
|
||||
int index = s.length() - 1;
|
||||
|
||||
for(int i =0; i <index; i++){
|
||||
|
||||
if(s.charAt(i)<=s.charAt(i + 1)){} //Need to check if each letter for the whole word is less than the one before it
|
||||
|
||||
else{return false;}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* A utility to check if a given number is armstrong or not. Armstrong number is
|
||||
* a number that is equal to the sum of cubes of its digits for example 0, 1,
|
||||
* 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3
|
||||
*
|
||||
* @author mani manasa mylavarapu
|
||||
*
|
||||
*/
|
||||
public class Armstrong {
|
||||
public static void main(String[] args) {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.println("please enter the number");
|
||||
int n = scan.nextInt();
|
||||
boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n);
|
||||
if (isArmstrong) {
|
||||
System.out.println("the number is armstrong");
|
||||
} else {
|
||||
System.out.println("the number is not armstrong");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given number is an armstrong number or not. Armstrong
|
||||
* number is a number that is equal to the sum of cubes of its digits for
|
||||
* example 0, 1, 153, 370, 371, 407 etc.
|
||||
*
|
||||
* @param number
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean checkIfANumberIsAmstrongOrNot(int number) {
|
||||
int remainder, sum = 0, temp = 0;
|
||||
temp = number;
|
||||
while (number > 0) {
|
||||
remainder = number % 10;
|
||||
sum = sum + (remainder * remainder * remainder);
|
||||
number = number / 10;
|
||||
}
|
||||
if (sum == temp) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Nishita Aggarwal
|
||||
*
|
||||
* Brian Kernighan’s Algorithm
|
||||
*
|
||||
* algorithm to count the number of set bits in a given number
|
||||
*
|
||||
* Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the
|
||||
* rightmost set bit).
|
||||
* So if we subtract a number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit.
|
||||
*
|
||||
* If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
|
||||
*
|
||||
*
|
||||
* Time Complexity: O(logn)
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
public class BrianKernighanAlgorithm {
|
||||
|
||||
/**
|
||||
* @param num: number in which we count the set bits
|
||||
*
|
||||
* @return int: Number of set bits
|
||||
* */
|
||||
static int countSetBits(int num)
|
||||
{
|
||||
int cnt = 0;
|
||||
while(num != 0)
|
||||
{
|
||||
num = num & (num-1);
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args : command line arguments
|
||||
*
|
||||
*/
|
||||
public static void main(String args[])
|
||||
{
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int num = sc.nextInt();
|
||||
int setBitCount = countSetBits(num);
|
||||
System.out.println(setBitCount);
|
||||
sc.close();
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
|
||||
/**
|
||||
* @author Kyler Smith, 2017
|
||||
*
|
||||
* Implementation of a character count.
|
||||
* (Slow, could be improved upon, effectively O(n).
|
||||
* */
|
||||
|
||||
public class CountChar {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter your text: ");
|
||||
String str = input.nextLine();
|
||||
input.close();
|
||||
System.out.println("There are " + CountCharacters(str) + " characters.");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param str: String to count the characters
|
||||
*
|
||||
* @return int: Number of characters in the passed string
|
||||
* */
|
||||
|
||||
private static int CountCharacters(String str) {
|
||||
|
||||
int count = 0;
|
||||
|
||||
if(str == "" || str == null) //Exceptions
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
if(!Character.isWhitespace(str.charAt(i))) {
|
||||
count++;
|
||||
}}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
/*
|
||||
@author : Mayank K Jha
|
||||
|
||||
*/
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
|
||||
public class Dijkshtra {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Scanner in =new Scanner(System.in);
|
||||
|
||||
int n=in.nextInt(); //n = Number of nodes or vertices
|
||||
int m=in.nextInt(); //m = Number of Edges
|
||||
long w[][]=new long [n+1][n+1]; //Adjacency Matrix
|
||||
|
||||
//Initializing Matrix with Certain Maximum Value for path b/w any two vertices
|
||||
for (long[] row: w)
|
||||
Arrays.fill(row, 1000000l);
|
||||
//From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
|
||||
//For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l .
|
||||
|
||||
//Taking Input as Edge Location b/w a pair of vertices
|
||||
for(int i=0;i<m;i++){
|
||||
int x=in.nextInt(),y=in.nextInt();
|
||||
long cmp=in.nextLong();
|
||||
if(w[x][y]>cmp){ //Comparing previous edge value with current value - Cycle Case
|
||||
w[x][y]=cmp; w[y][x]=cmp;
|
||||
}
|
||||
}
|
||||
|
||||
//Implementing Dijkshtra's Algorithm
|
||||
|
||||
Stack<Integer> t=new Stack<Integer>();
|
||||
int src=in.nextInt();
|
||||
for(int i=1;i<=n;i++){
|
||||
if(i!=src){t.push(i);}}
|
||||
Stack <Integer> p=new Stack<Integer>();
|
||||
p.push(src);
|
||||
w[src][src]=0;
|
||||
while(!t.isEmpty()){int min=989997979,loc=-1;
|
||||
for(int i=0;i<t.size();i++){
|
||||
w[src][t.elementAt(i)]=Math.min(w[src][t.elementAt(i)],w[src][p.peek()]
|
||||
+w[p.peek()][t.elementAt(i)]);
|
||||
if(w[src][t.elementAt(i)]<=min){
|
||||
min=(int) w[src][t.elementAt(i)];loc=i;}
|
||||
}
|
||||
p.push(t.elementAt(loc));t.removeElementAt(loc);}
|
||||
|
||||
//Printing shortest path from the given source src
|
||||
for(int i=1;i<=n;i++){
|
||||
if(i!=src && w[src][i]!=1000000l){System.out.print(w[src][i]+" ");}
|
||||
else if(i!=src){System.out.print("-1"+" ");} //Printing -1 if there is no path b/w given pair of edges
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This program will print out the factorial of any non-negative
|
||||
* number that you input into it.
|
||||
*
|
||||
* @author Marcus
|
||||
*
|
||||
*/
|
||||
public class Factorial{
|
||||
|
||||
/**
|
||||
* The main method
|
||||
*
|
||||
* @param args Command line arguments
|
||||
*/
|
||||
public static void main(String[] args){
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter a non-negative integer: ");
|
||||
|
||||
//If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
|
||||
try{
|
||||
int number = input.nextInt();
|
||||
|
||||
//We keep prompting the user until they enter a positive number
|
||||
while(number < 0){
|
||||
System.out.println("Your input must be non-negative. Please enter a positive number: ");
|
||||
number = input.nextInt();
|
||||
}
|
||||
//Display the result
|
||||
System.out.println("The factorial of " + number + " will yield: " + factorial(number));
|
||||
|
||||
}catch(Exception e){
|
||||
System.out.println("Error: You did not enter an integer. Program has terminated.");
|
||||
}
|
||||
input.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive Factorial Method
|
||||
*
|
||||
* @param n The number to factorial
|
||||
* @return The factorial of the number
|
||||
*/
|
||||
public static long factorial(int n){
|
||||
if(n == 0 || n == 1) return 1;
|
||||
return n * factorial(n - 1);
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FibToN {
|
||||
|
||||
public static void main(String[] args) {
|
||||
//take input
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
// print fibonacci sequence less than N
|
||||
int first = 0, second = 1;
|
||||
//first fibo and second fibonacci are 0 and 1 respectively
|
||||
scn.close();
|
||||
while(first <= N){
|
||||
//print first fibo 0 then add second fibo into it while updating second as well
|
||||
|
||||
System.out.println(first);
|
||||
|
||||
int next = first+ second;
|
||||
first = second;
|
||||
second = next;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
import java.util.Scanner;
|
||||
|
||||
|
||||
class FloydTriangle {
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
|
||||
int r = sc.nextInt(), n = 0;
|
||||
sc.close();
|
||||
for(int i=0; i < r; i++) {
|
||||
for(int j=0; j <= i; j++) {
|
||||
System.out.print(++n + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
//Oskar Enmalm 3/10/17
|
||||
//This is Euclid's algorithm which is used to find the greatest common denominator
|
||||
//Overide function name gcd
|
||||
|
||||
public class GCD{
|
||||
|
||||
public static int gcd(int num1, int num2) {
|
||||
|
||||
int gcdValue = num1 % num2;
|
||||
while (gcdValue != 0) {
|
||||
num2 = gcdValue;
|
||||
gcdValue = num2 % gcdValue;
|
||||
}
|
||||
return num2;
|
||||
}
|
||||
public static int gcd(int[] number) {
|
||||
int result = number[0];
|
||||
for(int i = 1; i < number.length; i++)
|
||||
//call gcd function (input two value)
|
||||
result = gcd(result, number[i]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] myIntArray = {4,16,32};
|
||||
//call gcd function (input array)
|
||||
System.out.println(gcd(myIntArray));
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
import java.lang.Math;
|
||||
/*
|
||||
* author: @AKS1996
|
||||
* Guass Legendre Algorithm
|
||||
* ref https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm
|
||||
*
|
||||
*/
|
||||
|
||||
public class GuassLegendre {
|
||||
|
||||
public static void main(String[] args) {
|
||||
for(int i=1;i<=3;++i)
|
||||
System.out.println(pi(i));
|
||||
|
||||
}
|
||||
|
||||
static double pi(int l){
|
||||
/*
|
||||
* l: No of loops to run
|
||||
*/
|
||||
|
||||
double a = 1,b=Math.pow(2,-0.5),t=0.25,p=1;
|
||||
for(int i=0;i<l;++i){
|
||||
double temp[] = update(a,b,t,p);
|
||||
a = temp[0];
|
||||
b = temp[1];
|
||||
t = temp[2];
|
||||
p = temp[3];
|
||||
}
|
||||
|
||||
return Math.pow(a+b, 2)/(4*t);
|
||||
}
|
||||
|
||||
static double[] update(double a, double b, double t, double p){
|
||||
double values[] = new double[4];
|
||||
values[0] = (a+b)/2;
|
||||
values[1] = Math.sqrt(a*b);
|
||||
values[2] = t - p*Math.pow(a - values[0],2);
|
||||
values[3] = 2*p;
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
}
|
@ -1,158 +0,0 @@
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
/**
|
||||
*
|
||||
* @author Mayank Kumar (mk9440)
|
||||
*/
|
||||
/*
|
||||
Output :
|
||||
|
||||
Enter number of distinct letters
|
||||
6
|
||||
Enter letters with its frequncy to encode
|
||||
Enter letter : a
|
||||
Enter frequncy : 45
|
||||
|
||||
Enter letter : b
|
||||
Enter frequncy : 13
|
||||
|
||||
Enter letter : c
|
||||
Enter frequncy : 12
|
||||
|
||||
Enter letter : d
|
||||
Enter frequncy : 16
|
||||
|
||||
Enter letter : e
|
||||
Enter frequncy : 9
|
||||
|
||||
Enter letter : f
|
||||
Enter frequncy : 5
|
||||
|
||||
Letter Encoded Form
|
||||
a 0
|
||||
b 1 0 1
|
||||
c 1 0 0
|
||||
d 1 1 1
|
||||
e 1 1 0 1
|
||||
f 1 1 0 0
|
||||
|
||||
*/
|
||||
|
||||
class Node{
|
||||
String letr="";
|
||||
int freq=0,data=0;
|
||||
Node left=null,right=null;
|
||||
}
|
||||
|
||||
//A comparator class to sort list on the basis of their frequency
|
||||
class comp implements Comparator<Node>{
|
||||
@Override
|
||||
public int compare(Node o1, Node o2) {
|
||||
if(o1.freq>o2.freq){return 1;}
|
||||
else if(o1.freq<o2.freq){return -1;}
|
||||
else{return 0;}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class Huffman {
|
||||
|
||||
// A simple function to print a given list
|
||||
//I just made it for debugging
|
||||
public static void print_list(List li){
|
||||
Iterator<Node> it=li.iterator();
|
||||
while(it.hasNext()){Node n=it.next();System.out.print(n.freq+" ");}System.out.println();
|
||||
}
|
||||
|
||||
//Function for making tree (Huffman Tree)
|
||||
public static Node make_huffmann_tree(List li){
|
||||
//Sorting list in increasing order of its letter frequency
|
||||
li.sort(new comp());
|
||||
Node temp=null;
|
||||
Iterator it=li.iterator();
|
||||
//System.out.println(li.size());
|
||||
//Loop for making huffman tree till only single node remains in list
|
||||
while(true){
|
||||
temp=new Node();
|
||||
//a and b are Node which are to be combine to make its parent
|
||||
Node a=new Node(),b=new Node();
|
||||
a=null;b=null;
|
||||
//checking if list is eligible for combining or not
|
||||
//here first assignment of it.next in a will always be true as list till end will
|
||||
//must have atleast one node
|
||||
a=(Node)it.next();
|
||||
//Below condition is to check either list has 2nd node or not to combine
|
||||
//If this condition will be false, then it means construction of huffman tree is completed
|
||||
if(it.hasNext()){b=(Node)it.next();}
|
||||
//Combining first two smallest nodes in list to make its parent whose frequncy
|
||||
//will be equals to sum of frequency of these two nodes
|
||||
if(b!=null){
|
||||
temp.freq=a.freq+b.freq;a.data=0;b.data=1;//assigining 0 and 1 to left and right nodes
|
||||
temp.left=a;temp.right=b;
|
||||
//after combing, removing first two nodes in list which are already combined
|
||||
li.remove(0);//removes first element which is now combined -step1
|
||||
li.remove(0);//removes 2nd element which comes on 1st position after deleting first in step1
|
||||
li.add(temp);//adding new combined node to list
|
||||
//print_list(li); //For visualizing each combination step
|
||||
}
|
||||
//Sorting after combining to again repeat above on sorted frequency list
|
||||
li.sort(new comp());
|
||||
it=li.iterator();//resetting list pointer to first node (head/root of tree)
|
||||
if(li.size()==1){return (Node)it.next();} //base condition ,returning root of huffman tree
|
||||
}
|
||||
}
|
||||
|
||||
//Function for finding path between root and given letter ch
|
||||
public static void dfs(Node n,String ch){
|
||||
Stack<Node> st=new Stack(); // stack for storing path
|
||||
int freq=n.freq; // recording root freq to avoid it adding in path encoding
|
||||
find_path_and_encode(st,n,ch,freq);
|
||||
}
|
||||
|
||||
//A simple utility function to print stack (Used for printing path)
|
||||
public static void print_path(Stack<Node> st){
|
||||
for(int i=0;i<st.size();i++){
|
||||
System.out.print(st.elementAt(i).data+" ");
|
||||
}
|
||||
}
|
||||
|
||||
public static void find_path_and_encode(Stack<Node> st,Node root,String s,int f){
|
||||
//Base condition
|
||||
if(root!= null){
|
||||
if(root.freq!=f){st.push(root);} // avoiding root to add in path/encoding bits
|
||||
if(root.letr.equals(s)){print_path(st);return;} // Recursion stopping condition when path gets founded
|
||||
find_path_and_encode(st,root.left,s,f);
|
||||
find_path_and_encode(st,root.right,s,f);
|
||||
//Popping if path not found in right or left of this node,because we previously
|
||||
//pushed this node in taking a mindset that it might be in path
|
||||
st.pop();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]){
|
||||
List <Node> li=new LinkedList<>();
|
||||
Scanner in=new Scanner(System.in);
|
||||
System.out.println("Enter number of distinct letters ");
|
||||
int n=in.nextInt();
|
||||
String s[]=new String[n];
|
||||
System.out.print("Enter letters with its frequncy to encode\n");
|
||||
for(int i=0;i<n;i++){
|
||||
Node a=new Node();
|
||||
System.out.print("Enter letter : ");
|
||||
a.letr=in.next();s[i]=a.letr;
|
||||
System.out.print("Enter frequncy : ");
|
||||
a.freq=in.nextInt();System.out.println();
|
||||
li.add(a);
|
||||
}
|
||||
Node root=new Node();
|
||||
root=make_huffmann_tree(li);
|
||||
System.out.println("Letter\t\tEncoded Form");
|
||||
for(int i=0;i<n;i++){
|
||||
System.out.print(s[i]+"\t\t");dfs(root,s[i]);System.out.println();}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user