# Conflicts:
#	Data Structures/HashMap/HashMap.java
#	Huffman.java
#	Misc/FloydTriangle.java
#	Misc/Huffman.java
#	Misc/InsertDeleteInArray.java
#	Misc/RootPrecision.java
#	Misc/ft.java
#	Misc/root_precision.java
#	Others/FloydTriangle.java
#	Others/Huffman.java
#	Others/insert_delete_in_array.java
#	Others/root_precision.java
#	insert_delete_in_array.java
This commit is contained in:
DESKTOP-0VAEMFL\joaom
2017-10-28 12:59:58 +01:00
58 changed files with 2697 additions and 114 deletions

View File

@@ -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;
}

View File

@@ -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();
System.out.println("There are " + CountCharacters(str) + " characters.");
}
/**
* @param str: String to count the characters
*
* @return int: Number of characters in the passed string
* */
public 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;
}
}

View File

@@ -1,56 +0,0 @@
/*
@author : Mayank K Jha
*/
public class Solution {
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
}
}
}

View File

@@ -1,50 +0,0 @@
package factorial;
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);
}
}

View File

@@ -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
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;
}
}
}

View File

@@ -1,45 +0,0 @@
/**
* The Sieve of Eratosthenes is an algorithm use to find prime numbers,
* up to a given value.
* Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
* (This illustration is also in the github repository)
*
* @author Unknown
*
*/
public class FindingPrimes{
/**
* The Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
SOE(20); //Example: Finds all the primes up to 20
}
/**
* The method implementing the Sieve of Eratosthenes
*
* @param n Number to perform SOE on
*/
public static void SOE(int n){
boolean sieve[] = new boolean[n];
int check = (int)Math.round(Math.sqrt(n)); //No need to check for multiples past the square root of n
sieve[0] = false;
sieve[1] = false;
for(int i = 2; i < n; i++)
sieve[i] = true; //Set every index to true except index 0 and 1
for(int i = 2; i< check; i++){
if(sieve[i]==true) //If i is a prime
for(int j = i+i; j < n; j+=i) //Step through the array in increments of i(the multiples of the prime)
sieve[j] = false; //Set every multiple of i to false
}
for(int i = 0; i< n; i++){
if(sieve[i]==true)
System.out.print(i+" "); //In this example it will print 2 3 5 7 11 13 17 19
}
}
}

View File

@@ -1,15 +0,0 @@
//Oskar Enmalm 3/10/17
//This is Euclid's algorithm which is used to find the greatest common denominator
public class GCD{
public static int gcd(int a, int b) {
int r = a % b;
while (r != 0) {
b = r;
r = b % r;
}
return b;
}
}

View File

@@ -1,55 +0,0 @@
/*
Implementation of KnuthMorrisPratt algorithm
Usage:
final String T = "AAAAABAAABA";
final String P = "AAAA";
KMPmatcher(T, P);
*/
public class KMP {
// find the starting index in string T[] that matches the search word P[]
public void KMPmatcher(final String T, final String P) {
final int m = T.length();
final int n = P.length();
final int[] pi = computePrefixFunction(P);
int q = 0;
for (int i = 0; i < m; i++) {
while (q > 0 && T.charAt(i) != P.charAt(q)) {
q = pi[q - 1];
}
if (T.charAt(i) == P.charAt(q)) {
q++;
}
if (q == n) {
System.out.println("Pattern starts: " + (i + 1 - n));
q = pi[q - 1];
}
}
}
// return the prefix function
private int[] computePrefixFunction(final String P) {
final int n = P.length();
final int[] pi = new int[n];
pi[0] = 0;
int q = 0;
for (int i = 1; i < n; i++) {
while (q > 0 && P.charAt(q) != P.charAt(i)) {
q = pi[q - 1];
}
if (P.charAt(q) == P.charAt(i)) {
q++;
}
pi[i] = q;
}
return pi;
}
}

View File

@@ -1,144 +0,0 @@
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Class for finding the lowest base in which a given integer is a palindrome.
* Includes auxiliary methods for converting between bases and reversing strings.
*
* NOTE: There is potential for error, see note at line 63.
*
* @author RollandMichael
* @version 2017.09.28
*
*/
public class LowestBasePalindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=0;
while (true) {
try {
System.out.print("Enter number: ");
n = in.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
in.next();
}
}
System.out.println(n+" is a palindrome in base "+lowestBasePalindrome(n));
System.out.println(base2base(Integer.toString(n),10, lowestBasePalindrome(n)));
}
/**
* Given a number in base 10, returns the lowest base in which the
* number is represented by a palindrome (read the same left-to-right
* and right-to-left).
* @param num A number in base 10.
* @return The lowest base in which num is a palindrome.
*/
public static int lowestBasePalindrome(int num) {
int base, num2=num;
int digit;
char digitC;
boolean foundBase=false;
String newNum = "";
String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while (!foundBase) {
// Try from bases 2 to num-1
for (base=2; base<num2; base++) {
newNum="";
while(num>0) {
// Obtain the first digit of n in the current base,
// which is equivalent to the integer remainder of (n/base).
// The next digit is obtained by dividing n by the base and
// continuing the process of getting the remainder. This is done
// until n is <=0 and the number in the new base is obtained.
digit = (num % base);
num/=base;
// If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
// form is just its value in ASCII.
// NOTE: This may cause problems, as the capital letters are ASCII values
// 65-90. It may cause false positives when one digit is, for instance 10 and assigned
// 'A' from the character array and the other is 65 and also assigned 'A'.
// Regardless, the character is added to the representation of n
// in the current base.
if (digit>=digits.length()) {
digitC=(char)(digit);
newNum+=digitC;
continue;
}
newNum+=digits.charAt(digit);
}
// Num is assigned back its original value for the next iteration.
num=num2;
// Auxiliary method reverses the number.
String reverse = reverse(newNum);
// If the number is read the same as its reverse, then it is a palindrome.
// The current base is returned.
if (reverse.equals(newNum)) {
foundBase=true;
return base;
}
}
}
// If all else fails, n is always a palindrome in base n-1. ("11")
return num-1;
}
private static String reverse(String str) {
String reverse = "";
for(int i=str.length()-1; i>=0; i--) {
reverse += str.charAt(i);
}
return reverse;
}
private 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;
}
}

View File

@@ -1,16 +0,0 @@
public class Node {
public Object anElement;
public Node less;
public Node greater;
public Node(Object theElement) {
this(theElement, null, null); //an empty node at the end will be by itself with no children, therefore the other 2 parameters are always null
//obviously the node can still be a child of other elements
}
public Node(Object currentElement, Node lessSide, Node greaterSide) {
anElement = currentElement;
this.less = lessSide;
this.greater = greaterSide;
}
}

View File

@@ -1,16 +0,0 @@
class Palindrome {
public String reverseString(String x){ //*helper method
String output = "";
for(int i=x.length()-1; i>=0; i--){
output += x.charAt(i); //addition of chars create String
}
return output;
}
public Boolean isPalindrome(String x){ //*palindrome method, returns true if palindrome
return (x.equalsIgnoreCase(reverseString(x)));
}
}

View File

@@ -1,59 +0,0 @@
/*
This program will return all the subsequences of the input string in a string array;
Sample Input:
abc
Sample Output:
"" ( Empty String )
c
b
bc
a
ac
ab
abc
*/
import java.util.Scanner;
public class ReturnSubsequence {
/*
Main function will accept the given string and implement return subsequences function
*/
public static void main(String[] args) {
System.out.println("Enter String: ");
Scanner s=new Scanner(System.in);
String givenString=s.next(); //given string
String[] subsequence=returnSubsequence(givenString); //calling returnSubsequence() function
System.out.println("Subsequences : ");
for(int i=0;i<subsequence.length;i++) //print the given array of subsequences
{
System.out.println(subsequence[i]);
}
}
/*
Recursive function to return Subsequences
*/
private static String[] returnSubsequence(String givenString) {
if(givenString.length()==0) // If string is empty we will create an array of size=1 and insert "" (Empty string) in it
{
String[] ans=new String[1];
ans[0]="";
return ans;
}
String[] SmallAns=returnSubsequence(givenString.substring(1)); //recursive call to get subsequences of substring starting from index position=1
String[] ans=new String[2*SmallAns.length];// Our answer will be an array off string of size=2*SmallAns
int i=0;
for (;i<SmallAns.length;i++)
{
ans[i]=SmallAns[i]; //Copying all the strings present in SmallAns to ans string array
}
for (int k=0;k<SmallAns.length;k++)
{
ans[k+SmallAns.length]=givenString.charAt(0)+SmallAns[k]; // Insert character at index=0 of the given substring in front of every string in SmallAns
}
return ans;
}
}

View File

@@ -1,74 +0,0 @@
/* Program to reverse a Stack using Recursion*/
import java.util.Stack;
public class ReverseStackUsingRecursion {
//Stack
private static Stack<Integer> stack=new Stack<>();
//Main function
public static void main(String[] args) {
//To Create a Dummy Stack containing integers from 0-9
for(int i=0;i<10;i++)
{
stack.push(i);
}
System.out.println("STACK");
//To print that dummy Stack
for(int k=9;k>=0;k--)
{
System.out.println(k);
}
//Reverse Function called
reverseUsingRecursion(stack);
System.out.println("REVERSED STACK : ");
//To print reversed stack
while (!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
//Function Used to reverse Stack Using Recursion
private static void reverseUsingRecursion(Stack<Integer> stack) {
if(stack.isEmpty()) // If stack is empty then return
{
return;
}
/* All items are stored in call stack until we reach the end*/
int temptop=stack.peek();
stack.pop();
reverseUsingRecursion(stack); //Recursion call
insertAtEnd(temptop); // Insert items held in call stack one by one into stack
}
//Function used to insert element at the end of stack
private static void insertAtEnd(int temptop) {
if(stack.isEmpty())
{
stack.push(temptop); // If stack is empty push the element
}
else {
int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
stack.pop();
insertAtEnd(temptop); //Recursive call
stack.push(temp);
}
}
}

View File

@@ -1,46 +0,0 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This method produces a reversed version of a string
*
* @author Unknown
*
*/
class ReverseString
{
/**
* This method reverses the string str and returns it
* @param str String to be reversed
* @return Reversed string
*/
public static String reverse(String str){
if(str.isEmpty() || str == null) return str;
char arr[] = str.toCharArray();
for(int i = 0, j = str.length() - 1; i < j; i++, j--){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return new String(arr);
}
/**
* Main Method
*
* @param args Command line arguments
* @throws IOException Exception thrown because of BufferedReader
*/
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String srr=br.readLine();
System.out.println("Reverse="+reverseString(srr));
br.close();
}
}

View File

@@ -1,26 +0,0 @@
import java.util.Scanner;
class TowerOfHanoi
{
public static void shift(int n, String startPole, String intermediatePole, String endPole)
{
if (n == 0) // if n becomes zero the program returns thus ending the loop.
{
return;
}
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
shift(n - 1, startPole, endPole, intermediatePole);
System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
shift(n - 1, intermediatePole, startPole, endPole);
}
public static void main(String[] args)
{
System.out.print("Enter number of discs on Pole 1: ");
Scanner scanner = new Scanner(System.in);
int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
}
}

View File

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

View File

@@ -1,27 +0,0 @@
import java.util.BitSet;
//Generates a crc32 checksum for a given string or byte array
public class crc32 {
public static void main(String[] args) {
System.out.println(Integer.toHexString(crc32("Hello World")));
}
public static int crc32(String str) {
return crc32(str.getBytes());
}
public static int crc32(byte[] data) {
BitSet bitSet = BitSet.valueOf(data);
int crc32 = 0xFFFFFFFF; //initial value
for(int i=0;i<data.length*8;i++) {
if(((crc32>>>31)&1) != (bitSet.get(i)?1:0))
crc32 = (crc32 << 1) ^ 0x04C11DB7; //xoring with polynomial
else
crc32 = (crc32 << 1);
}
crc32 = Integer.reverse(crc32); //result reflect
return crc32 ^ 0xFFFFFFFF; //final xor value
}
}

View File

@@ -1,29 +0,0 @@
import java.util.Scanner;
class krishnamurthy
{
int fact(int n)
{
int i,p=1;
for(i=n;i>=1;i--)
p=p*i;
return p;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b,s=0;
System.out.print("Enter the number : ");
a=sc.nextInt();
int n=a;
while(a>0)
{
b=a%10;
s=s+fact(b);
a=a/10;
}
if(s==n)
System.out.print(n+" is a krishnamurthy number");
else
System.out.print(n+" is not a krishnamurthy number");
}
}

View File

@@ -1,45 +0,0 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
public class removeDuplicateFromString {
public static void main (String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inp_str = br.readLine();
System.out.println("Actual string is: " + inp_str);
System.out.println("String after removing duplicates: " + removeDuplicate(inp_str));
br.close();
}
/**
* This method produces a string after removing all the duplicate characters from input string and returns it
* Example: Input String - "aabbbccccddddd"
* Output String - "abcd"
* @param s String from which duplicate characters have to be removed
* @return string with only unique characters
*/
public static String removeDuplicate(String s) {
if(s.isEmpty() || s == null) {
return s;
}
StringBuilder sb = new StringBuilder("");
int n = s.length();
for (int i = 0; i < n; i++) {
if (sb.toString().indexOf(s.charAt(i)) == -1) {
sb.append(String.valueOf(s.charAt(i)));
}
}
return sb.toString();
}
}