# 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

17
Others/Abecedarian.java Normal file
View File

@@ -0,0 +1,17 @@
//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;
}
}

47
Others/Armstrong.java Normal file
View File

@@ -0,0 +1,47 @@
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;
}
}
}

43
Others/CountChar.java Normal file
View File

@@ -0,0 +1,43 @@
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;
}
}

61
Others/Dijkshtra.java Normal file
View File

@@ -0,0 +1,61 @@
/*
@author : Mayank K Jha
*/
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
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
}
}
}

49
Others/Factorial.java Normal file
View File

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

24
Others/FibToN.java Normal file
View File

@@ -0,0 +1,24 @@
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;
}
}
}

45
Others/FindingPrimes.java Normal file
View File

@@ -0,0 +1,45 @@
/**
* 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
}
}
}

16
Others/FloydTriangle.java Normal file
View File

@@ -0,0 +1,16 @@
import java.util.Scanner;
public 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;
for(int i=0; i < r; i++) {
for(int j=0; j <= i; j++) {
System.out.print(++n + " ");
}
System.out.println();
}
}
}

15
Others/GCD.java Normal file
View File

@@ -0,0 +1,15 @@
//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;
}
}

158
Others/Huffman.java Normal file
View File

@@ -0,0 +1,158 @@
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();}
}
}

55
Others/KMP.java Normal file
View File

@@ -0,0 +1,55 @@
/*
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

@@ -0,0 +1,57 @@
/***
* A pseudorandom number generator.
*
* @author Tobias Carryer
* Date: October 10, 2017
*/
public class LinearCongruentialGenerator {
private double a, c, m, previousValue;
/***
* These parameters are saved and used when nextNumber() is called.
* The current timestamp in milliseconds is used as the seed.
*
* @param multiplier
* @param increment
* @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
*/
public LinearCongruentialGenerator( double multiplier, double increment, double modulo ) {
this(System.currentTimeMillis(), multiplier, increment, modulo);
}
/***
* These parameters are saved and used when nextNumber() is called.
*
* @param seed
* @param multiplier
* @param increment
* @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
*/
public LinearCongruentialGenerator( double seed, double multiplier, double increment, double modulo ) {
this.previousValue = seed;
this.a = multiplier;
this.c = increment;
this.m = modulo;
}
/**
* The smallest number that can be generated is zero.
* The largest number that can be generated is modulo-1. modulo is set in the constructor.
* @return a pseudorandom number.
*/
public double nextNumber() {
previousValue = (a * previousValue + c) % m;
return previousValue;
}
public static void main( String[] args ) {
// Show the LCG in action.
// Decisive proof that the LCG works could be made by adding each number
// generated to a Set while checking for duplicates.
LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
for( int i = 0; i < 512; i++ ) {
System.out.println(lcg.nextNumber());
}
}
}

View File

@@ -0,0 +1,144 @@
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;
}
}

16
Others/Node.java Normal file
View File

@@ -0,0 +1,16 @@
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;
}
}

16
Others/Palindrome.java Normal file
View File

@@ -0,0 +1,16 @@
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

@@ -0,0 +1,144 @@
import java.util.Stack;
/**
* This implements Queue using two Stacks.
*
* Big O Runtime:
* insert(): O(1)
* remove(): O(1) amortized
* isEmpty(): O(1)
*
* 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 sahilb2
*
*/
class QueueWithStack {
// Stack to keep track of elements inserted into the queue
private Stack inStack;
// Stack to keep track of elements to be removed next in queue
private Stack outStack;
/**
* Constructor
*/
public QueueWithStack() {
this.inStack = new Stack();
this.outStack = new Stack();
}
/**
* Inserts an element at the rear of the queue
*
* @param x element to be added
*/
public void insert(Object x) {
// Insert element into inStack
this.inStack.push(x);
}
/**
* Remove an element from the front of the queue
*
* @return the new front of the queue
*/
public Object remove() {
if(this.outStack.isEmpty()) {
// Move all elements from inStack to outStack (preserving the order)
while(!this.inStack.isEmpty()) {
this.outStack.push( this.inStack.pop() );
}
}
return this.outStack.pop();
}
/**
* Peek at the element from the front of the queue
*
* @return the new front of the queue
*/
public Object peek() {
if(this.outStack.isEmpty()) {
// Move all elements from inStack to outStack (preserving the order)
while(!this.inStack.isEmpty()) {
this.outStack.push( this.inStack.pop() );
}
}
return this.outStack.peek();
}
/**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty() {
return (this.inStack.isEmpty() && this.outStack.isEmpty());
}
}
/**
* This class is the example for the Queue class
*
* @author sahilb2
*
*/
public class QueueUsingTwoStacks {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
QueueWithStack myQueue = new QueueWithStack();
myQueue.insert(1);
// instack: [(top) 1]
// outStack: []
myQueue.insert(2);
// instack: [(top) 2, 1]
// outStack: []
myQueue.insert(3);
// instack: [(top) 3, 2, 1]
// outStack: []
myQueue.insert(4);
// instack: [(top) 4, 3, 2, 1]
// outStack: []
System.out.println(myQueue.isEmpty()); //Will print false
System.out.println(myQueue.remove()); //Will print 1
// instack: []
// outStack: [(top) 2, 3, 4]
myQueue.insert(5);
System.out.println(myQueue.peek()); //Will print 2
// instack: [(top) 5]
// outStack: [(top) 2, 3, 4]
myQueue.remove();
System.out.println(myQueue.peek()); //Will print 3
// instack: [(top) 5]
// outStack: [(top) 3, 4]
myQueue.remove();
System.out.println(myQueue.peek()); //Will print 4
// instack: [(top) 5]
// outStack: [(top) 4]
myQueue.remove();
// instack: [(top) 5]
// outStack: []
System.out.println(myQueue.peek()); //Will print 5
// instack: []
// outStack: [(top) 5]
myQueue.remove();
// instack: []
// outStack: []
System.out.println(myQueue.isEmpty()); //Will print true
}
}

View File

@@ -0,0 +1,59 @@
/*
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

@@ -0,0 +1,70 @@
/* 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);
}
}
}

46
Others/ReverseString.java Normal file
View File

@@ -0,0 +1,46 @@
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="+reverse(srr));
br.close();
}
}

View File

@@ -0,0 +1,38 @@
import java.util.*;
public class Postfix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
System.out.println(postfixEvaluate(post));
}
// Evaluates the given postfix expression string and returns the result.
public static int postfixEvaluate(String exp) {
Stack<Integer> s = new Stack<Integer> ();
Scanner tokens = new Scanner(exp);
while (tokens.hasNext()) {
if (tokens.hasNextInt()) {
s.push(tokens.nextInt()); // If int then push to stack
} else { // else pop top two values and perform the operation
int num2 = s.pop();
int num1 = s.pop();
String op = tokens.next();
if (op.equals("+")) {
s.push(num1 + num2);
} else if (op.equals("-")) {
s.push(num1 - num2);
} else if (op.equals("*")) {
s.push(num1 * num2);
} else {
s.push(num1 / num2);
}
// "+", "-", "*", "/"
}
}
return s.pop();
}
}

View File

@@ -0,0 +1,26 @@
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
}
}

26
Others/countwords.java Normal file
View File

@@ -0,0 +1,26 @@
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;
}
}

27
Others/crc32.java Normal file
View File

@@ -0,0 +1,27 @@
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

@@ -0,0 +1,46 @@
import java.util.*;
public class Array {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // Input statement
System.out.println("Enter the size of the array");
int size = s.nextInt();
int a[] = new int[size];
int i;
// To enter the initial elements
for(i=0;i<size;i++){
System.out.println("Enter the element");
a[i] = s.nextInt();
}
// To insert a new element(we are creating a new array)
System.out.println("Enter the index at which the element should be inserted");
int insert_pos = s.nextInt();
System.out.println("Enter the element to be inserted");
int ins = s.nextInt();
int size2 = size + 1;
int b[] =new int[size2];
for(i=0;i<size2;i++){
if(i <= insert_pos){
b[i] = a[i];
}
else{
b[i] = a[i-1];
}
}
b[insert_pos] = ins;
for(i=0;i<size2;i++){
System.out.println(b[i]);
}
// To delete an element given the index
System.out.println("Enter the index at which element is to be deleted");
int del_pos = s.nextInt();
for(i=del_pos;i<size2-1;i++){
b[i] = b[i+1];
}
for(i=0;i<size2-1;i++)
System.out.println(b[i]);
}
}

30
Others/krishnamurthy.java Normal file
View File

@@ -0,0 +1,30 @@
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

@@ -0,0 +1,45 @@
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();
}
}

View File

@@ -0,0 +1,29 @@
import java.util.*;
public class Solution {
public static void main(String[] args) {
//take input
Scanner scn = new Scanner(System.in);
int N = scn.nextInt(); //N is the input number
int P = scn.nextInt(); //P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
System.out.println(squareRoot(N, P));
}
public static double squareRoot(int N, int P) {
double rv = 0; //rv means return value
double root = Math.pow(N, 0.5);
//calculate precision to power of 10 and then multiply it with root value.
int precision = (int) Math.pow(10, P);
root = root * precision;
/*typecast it into integer then divide by precision and again typecast into double
so as to have decimal points upto P precision */
rv = (int)root;
return (double)rv/precision;
}
}