diff --git a/1add.java b/1add.java new file mode 100644 index 0000000..a158954 --- /dev/null +++ b/1add.java @@ -0,0 +1,16 @@ +class Main { + public static void main(String[] args) { + + // create boolean variables + boolean booleanValue1 = true; + boolean booleanValue2 = false; + + // convert boolean to string + // using valueOf() + String stringValue1 = String.valueOf(booleanValue1); + String stringValue2 = String.valueOf(booleanValue2); + + System.out.println(stringValue1); // true + System.out.println(stringValue2); // true + } +} diff --git a/Abstract_Class_Example.java b/Abstract_Class_Example.java new file mode 100644 index 0000000..4ff5db7 --- /dev/null +++ b/Abstract_Class_Example.java @@ -0,0 +1,137 @@ +//Subscribed by Mritunjay Kumar +//https://www.facebook.com/Mritunjay70/posts/1445812775628125 +abstract class Person { + String name; + int age; + + Person() { + + } + Person(String n, int r) { + name = n; + age = r; + } + + void setData(String name1, int age1) + { + name = name1; + age = age1; + } + + void printDetails() + { + System.out.print("Name: "+name+" Age: "+age); + } + + abstract void exceptional(); + + final void isAdult() { + if (age > 18) System.out.println("\t Yes"); + } +} // class Person ends + +class Student extends Person +{ + double cpi; + + Student() { + + } + Student(String n, int r, double c) { + + super(n, r); + cpi = c; + } + + void setData(String name1, int age1, double cpi1) + { + super.setData(name1, age1); + cpi = cpi1; + } + + void printDetails() + { + System.out.println(); + super.printDetails(); + System.out.print(" CPI: "+cpi); + } + + void f() { + + } + + void exceptional() + { + if (cpi > 9.5) System.out.print(" Exceptional "); + } + + void isAdult(Person p) { + + } +} // class Student ends here + +abstract class test extends Student { + abstract void f(); + void f2(){ + + } +} + +class Faculty extends Person +{ + float noOfPub; + + Faculty() { + + } + Faculty(String n, int r, float nop) { + super(n, r); + noOfPub = nop; + } + + void setData(String name1, int age1, int nop) + { + super.setData(name1, age1); + noOfPub = nop; + } + + void printDetails() + { + System.out.println(); + super.printDetails(); + System.out.print(" No of Pub: "+noOfPub); + } + + void exceptional() + { + if (noOfPub > 100) System.out.print(" Exceptional "); + } +} + +public class AbstractDemo { + + public static void main(String[] args) + { + Student s1 = new Student(), s2 = new Student(); + Faculty f1 = new Faculty(), f2 = new Faculty(); + + s1.setData("A", 10, 9.7); s2.setData("B", 10, 7.0); + f1.setData("C", 70, 300); f2.setData("D", 75, 50); + + Person [] p= new Person[4]; + + p[0] = s1; + p[1] = s2; + p[2] = f1; + p[3] = f2; + + for (int index=0; index n); + } + + /* Driver program to test above function */ + public static void main(String args[])throws + IOException + { + if(checkAbundant(12)) + System.out.println("YES"); + else + System.out.println("NO"); + if(checkAbundant(15)) + System.out.println("YES"); + else + System.out.println("NO"); + } +} diff --git a/Area_of_circle.java b/Area_of_circle.java new file mode 100644 index 0000000..d4a36b3 --- /dev/null +++ b/Area_of_circle.java @@ -0,0 +1,17 @@ +#https://www.facebook.com/jeet/posts/2729372946102639 +# Subscribed by Code House + +import java.util.Scanner; +public class Area +{ + public static void main(String[] args) + { + int r; + double pi = 3.14, area; + Scanner s = new Scanner(System.in); + System.out.print("Enter radius of circle:"); + r = s.nextInt(); + area = pi * r * r; + System.out.println("Area of circle:"+area); + } +} diff --git a/Basic Calculator Operations.java b/Basic Calculator Operations.java new file mode 100644 index 0000000..b2c82ed --- /dev/null +++ b/Basic Calculator Operations.java @@ -0,0 +1,38 @@ +#Subscribed to CodeHouseIndia +import java.util.Scanner; +public class Calculator { +public static void main(String[] args) { +Scanner reader = new Scanner(System.in); +System.out.print("Enter two numbers: "); +// nextDouble() reads the next double from the keyboard +double first = reader.nextDouble(); +double second = reader.nextDouble(); +System.out.print("Enter an operator (+, -, *, /): "); +char operator = reader.next().charAt(0); +double result; +//switch case for each of the operations +switch(operator) +{ +case '+': +result = first + second; +break; +case '-': +result = first - second; +break; +case '*': +result = first * second; +break; +case '/': +result = first / second; +break; +// operator doesn't match any case constant (+, -, *, /) + + +default: +System.out.printf("Error! operator is not correct"); +return; +} +//printing the result of the operations +System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result); +} +} diff --git a/Binary Tree b/Binary Tree new file mode 100644 index 0000000..3c082af --- /dev/null +++ b/Binary Tree @@ -0,0 +1,74 @@ + + + + + + + +// Binary Tree in Java + +// Node creation +class Node { + int key; + Node left, right; + + public Node(int item) { + key = item; + left = right = null; + } +} + +class BinaryTree { + Node root; + + BinaryTree(int key) { + root = new Node(key); + } + + BinaryTree() { + root = null; + } + + // Traverse Inorder + public void traverseInOrder(Node node) { + if (node != null) { + traverseInOrder(node.left); + System.out.print(" " + node.key); + traverseInOrder(node.right); + } + } + + // Traverse Postorder + public void traversePostOrder(Node node) { + if (node != null) { + traversePostOrder(node.left); + traversePostOrder(node.right); + System.out.print(" " + node.key); + } + } + + // Traverse Preorder + public void traversePreOrder(Node node) { + if (node != null) { + System.out.print(" " + node.key); + traversePreOrder(node.left); + traversePreOrder(node.right); + } + } + + public static void main(String[] args) { + BinaryTree tree = new BinaryTree(); + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + + System.out.print("Pre order Traversal: "); + tree.traversePreOrder(tree.root); + System.out.print("\nIn order Traversal: "); + tree.traverseInOrder(tree.root); + System.out.print("\nPost order Traversal: "); + tree.traversePostOrder(tree.root); + } +} diff --git a/Bitonic_Array.java b/Bitonic_Array.java new file mode 100644 index 0000000..ea6fca4 --- /dev/null +++ b/Bitonic_Array.java @@ -0,0 +1,71 @@ +/* https://www.facebook.com/shanroy1999/posts/2795036240730237 +Subscribed by : Shantanu Roy(shan.roy1999@gmail.com) */ + +import java.util.Scanner; + +class Bitonic_Array +{ + public static int isBitonic(int arr[], int N) + { + if (arr[0] > arr[1]) + return -1; + + int i, j; + for (i = 2; i < N; i++) { + if (arr[i - 1] >= arr[i]) { + break; + } + } + + if (i == N - 1) { + return 1; + } + + for (j = i + 1; j < N; j++) { + if (arr[j - 1] <= arr[j]) { + break; + } + } + + if (j != N) { + return -1; + } + + return 1; + } + + public static void main(String args[]) + { + System.out.println("Enter number of elements in array"); + Scanner sc = new Scanner(System.in); + int N = sc.nextInt(); + System.out.println("Enter elements of array"); + int[] arr = new int[N]; + for (int i = 0; i < N; i++) { + arr[i] = sc.nextInt(); + } + int ans = isBitonic(arr, N); + if (ans == -1) + System.out.println("The array is not bitonic"); + else + System.out.println("The array is bitonic"); + } +} + +/* +Input: +N = 5 +arr = {0, 1, 2, 3, 4} +Output: +The array is not bitonic +Input: +N = 5 +arr = {0, 2, 4, 3, 1} +Output: +The array is bitonic +Input: +N = 5 +arr = {4, 3, 2, 1, 0} +Output: +The array is not bitonic +*/ diff --git a/CALCULATOR USING JAVA b/CALCULATOR USING JAVA new file mode 100644 index 0000000..c1dd98c --- /dev/null +++ b/CALCULATOR USING JAVA @@ -0,0 +1,41 @@ +package math; + +import java.util.Scanner; + +public class CalculatorDemo { + + public static void main(String[] args) { + double num1,num2; + Scanner sc=new Scanner(System.in); + System.out.println("Enter the numbers"); + num1=sc.nextDouble(); + num2=sc.nextDouble(); + System.out.println("Enter the operator (+,-,*,/)"); + char op =sc.next().charAt(0); + double o=0; + switch(op) { + case '+': + o=num1+num2; + break; + case '-': + o=num1-num2; + break; + case '*': + o=num1*num2; + break; + case '/': + o=num1/num2; + break; + default: + System.out.println("You enter wrong input"); + break; + + } + System.out.println("The final result:"); + System.out.println(); + System.out.println(num1 + " "+ op +" "+ num2 +" = "+o); + + + } + +} diff --git a/Caesar Cipher.java b/Caesar Cipher.java new file mode 100644 index 0000000..99ec458 --- /dev/null +++ b/Caesar Cipher.java @@ -0,0 +1,35 @@ +class CaesarCipher +{ + public static StringBuffer encrypt(String text, int s) + { + StringBuffer result= new StringBuffer(); + + for (int i=0; i +#include + +int main() +{ + float principal, rate, year, ci; + + printf("Enter principal: "); + scanf("%f", &principal); + + printf("Enter rate: "); + scanf("%f", &rate); + + printf("Enter time in years: "); + scanf("%f", &year); + + //calculate compound interest + + ci=principal*((pow((1+rate/100),year)-1)); + + printf("Compound interest is: %f\n",ci); + + return 0; +} diff --git a/Check Algorithm.java b/Check Algorithm.java new file mode 100644 index 0000000..07448d2 --- /dev/null +++ b/Check Algorithm.java @@ -0,0 +1,43 @@ +// https://www.facebook.com/abhi.sensharma/posts/1241788872853419 +// Subscribed by Abhishek Sharma + +// Here I have added the Check Algorithm program using Java + +import java.util.Scanner; + +public class Main { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int T = sc.nextInt(); + for (int tc = 0; tc < T; ++tc) { + String S = sc.next(); + + System.out.println(solve(S) ? "YES" : "NO"); + } + + sc.close(); + } + + static boolean solve(String S) { + StringBuilder compressed = new StringBuilder(); + char current = 0; + int count = -1; + for (int i = 0; i <= S.length(); ++i) { + if (i != S.length() && S.charAt(i) == current) { + count++; + } else { + if (count > 0) { + compressed.append(current).append(count); + } + + if (i != S.length()) { + current = S.charAt(i); + count = 1; + } + } + } + + return compressed.length() < S.length(); + } +} diff --git a/Checking if a given year is leap year or not b/Checking if a given year is leap year or not new file mode 100644 index 0000000..971a59e --- /dev/null +++ b/Checking if a given year is leap year or not @@ -0,0 +1,17 @@ +import java.util.Scanner; +public class Main +{ + public static void main(String[] args) + { + //scanner class declaration + Scanner sc=new Scanner(System.in); + //input year from user + System.out.println("Enter a Year"); + int year = sc.nextInt(); + //condition for checking year entered by user is a leap year or not + if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) + System.out.println(year + " is a leap year."); + else + System.out.println(year + " is not a leap year."); + } +} diff --git a/Daily Train.java b/Daily Train.java new file mode 100644 index 0000000..1a950df --- /dev/null +++ b/Daily Train.java @@ -0,0 +1,47 @@ +// https://www.facebook.com/abhi.sensharma/posts/1241788872853419 + +// subcribed by Abhishek Sharma. + +// Daily Train problem solution using Java + +import java.util.Scanner; +import java.util.stream.IntStream; + +public class Main { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int X = sc.nextInt(); + int N = sc.nextInt(); + String[] cars = new String[N]; + for (int i = 0; i < cars.length; i++) { + cars[i] = sc.next(); + } + System.out.println(solve(X, cars)); + + sc.close(); + } + + static int solve(int X, String[] cars) { + int result = 0; + for (String car : cars) { + for (int i = 0; i < 9; i++) { + int freeNum = (int) IntStream.of(i * 4, i * 4 + 1, i * 4 + 2, i * 4 + 3, 53 - i * 2, 52 - i * 2) + .filter(j -> car.charAt(j) == '0').count(); + + if (freeNum >= X) { + result += C(freeNum, X); + } + } + } + return result; + } + + static int C(int n, int m) { + int result = 1; + for (int i = 0; i < m; i++) { + result = result * (n - i) / (i + 1); + } + return result; + } +} diff --git a/Data.java b/Data.java new file mode 100644 index 0000000..8d79433 --- /dev/null +++ b/Data.java @@ -0,0 +1,48 @@ +package data; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +public class Data extends JFrame{ + JLabel rotulo,rotulo2; + int ds,dia,mes,ano; + Calendar data; + String diasemana[]={"Domingo","Segunda - Feira","Terça - Feira","Quarta - Feira", + "Quinta - Feira","Sexta - Feira","Sabado"}; + String meses[]={"Janeiro","Fevereiro","Março","Abril","Maio","Junho", + "Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"}; + + public Data(){ + super("Exemplo da Data"); + Container tela = getContentPane(); + tela.setLayout(null); + rotulo = new JLabel(""); + rotulo2 = new JLabel(""); + + rotulo.setBounds(20,30,280,20); + rotulo2.setBounds(20,60,280,20); + + data = Calendar.getInstance(); + + ds = data.get(Calendar.DAY_OF_WEEK); + dia = data.get(Calendar.DAY_OF_MONTH); + mes = data.get(Calendar.MONTH); + ano = data.get(Calendar.YEAR); + + //Rotulo.setText("Data: "+dia+"/"+(mes+1)+"/"+ano); + + rotulo.setText("Data: "+ds+" "+dia+"/"+(mes+1)+"/"+ano); + rotulo2.setText("Data: "+diasemana[ds-1]+", "+dia+" de "+meses[mes]+" de "+ano); + + //Rotulo.setText("Data: "+dia+" de "+meses[mes]+" de "+ano); + + tela.add(rotulo); + tela.add(rotulo2); + setSize(300, 200); + setVisible(true); + setLocationRelativeTo(null); } + + +} \ No newline at end of file diff --git a/Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) b/Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) new file mode 100644 index 0000000..d53ad22 --- /dev/null +++ b/Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) @@ -0,0 +1,193 @@ +// Java Program for union-find algorithm to detect cycle in a graph + +import java.util.*; + +import java.lang.*; + +import java.io.*; + + + +class Graph +{ + + int V, E; // V-> no. of vertices & E->no.of edges + + Edge edge[]; // /collection of all edges + + + + class Edge + + { + + int src, dest; + + }; + + + + // 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; i0) + { + r=n%2; //finding remainder by dividing the number by 2 + s=dig[r]+s; //adding the remainder to the result and reversing at the same time + n=n/2; + } + return s; + } + + int countOne(String s) // Function to count no of 1's in binary number + { + int c = 0, l = s.length(); + char ch; + for(int i=0; i>= 1; + + while (y-- != 0) + + ans++; + + return ans; + + } + + + + int swap(int a, int b) + + { + + return a; + + } + + + + /* A recursive function to get the minimum value in a given range + + of array indexes. The following are parameters for this function. + + + + st --> Pointer to segment tree + + index --> Index of current node in the segment tree. Initially + + 0 is passed as root is always at index 0 + + ss & se --> Starting and ending indexes of the segment represented + + by current node, i.e., st[index] + + qs & qe --> Starting and ending indexes of query range */ + + int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) + + { + + // If segment of this node is a part of given range, then return + + // the min of the segment + + if (qs <= ss && qe >= se) + + return st.stt[index]; + + + + // If segment of this node is outside the given range + + else if (se < qs || ss > qe) + + return -1; + + + + // If a part of this segment overlaps with the given range + + int mid = (ss + se) / 2; + + + + int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); + + int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); + + + + if (q1 == -1) + + return q2; + + else if (q2 == -1) + + return q1; + + + + return (level[q1] < level[q2]) ? q1 : q2; + + } + + + + // Return minimum of elements in range from index qs (query start) to + + // qe (query end). It mainly uses RMQUtil() + + int RMQ(St_class st, int n, int qs, int qe) + + { + + // Check for erroneous input values + + if (qs < 0 || qe > n - 1 || qs > qe) + + { + + System.out.println("Invalid input"); + + return -1; + + } + + + + return RMQUtil(0, 0, n - 1, qs, qe, st); + + } + + + + // A recursive function that constructs Segment Tree for array[ss..se]. + + // si is index of current node in segment tree st + + void constructSTUtil(int si, int ss, int se, int arr[], St_class st) + + { + + // If there is one element in array, store it in current node of + + // segment tree and return + + if (ss == se) + + st.stt[si] = ss; + + else + + { + + // If there are more than one elements, then recur for left and + + // right subtrees and store the minimum of two values in this node + + int mid = (ss + se) / 2; + + constructSTUtil(si * 2 + 1, ss, mid, arr, st); + + constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); + + + + if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) + + st.stt[si] = st.stt[2 * si + 1]; + + else + + st.stt[si] = st.stt[2 * si + 2]; + + } + + } + + + + /* Function to construct segment tree from given array. This function + + allocates memory for segment tree and calls constructSTUtil() to + + fill the allocated memory */ + + int constructST(int arr[], int n) + + { + + // Allocate memory for segment tree + + // Height of segment tree + + int x = Log2(n) + 1; + + + + // Maximum size of segment tree + + int max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 + + + + sc.stt = new int[max_size]; + + + + // Fill the allocated memory st + + constructSTUtil(0, 0, n - 1, arr, sc); + + + + // Return the constructed segment tree + + return sc.st; + + } + + + + // Recursive version of the Euler tour of T + + void eulerTour(Node node, int l) + + { + + /* if the passed node exists */ + + if (node != null) + + { + + euler[fill] = node.data; // insert in euler array + + level[fill] = l; // insert l in level array + + fill++; // increment index + + + + /* if unvisited, mark first occurrence */ + + if (f_occur[node.data] == -1) + + f_occur[node.data] = fill - 1; + + + + /* tour left subtree if exists, and remark euler + + and level arrays for parent on return */ + + if (node.left != null) + + { + + eulerTour(node.left, l + 1); + + euler[fill] = node.data; + + level[fill] = l; + + fill++; + + } + + + + /* tour right subtree if exists, and remark euler + + and level arrays for parent on return */ + + if (node.right != null) + + { + + eulerTour(node.right, l + 1); + + euler[fill] = node.data; + + level[fill] = l; + + fill++; + + } + + } + + } + + + + // returns LCA of node n1 and n2 assuming they are present in tree + + int findLCA(Node node, int u, int v) + + { + + /* Mark all nodes unvisited. Note that the size of + + firstOccurrence is 1 as node values which vary from + + 1 to 9 are used as indexes */ + + Arrays.fill(f_occur, -1); + + + + /* To start filling euler and level arrays from index 0 */ + + fill = 0; + + + + /* Start Euler tour with root node on level 0 */ + + eulerTour(root, 0); + + + + /* construct segment tree on level array */ + + sc.st = constructST(level, 2 * v - 1); + + + + /* If v before u in Euler tour. For RMQ to work, first + + parameter 'u' must be smaller than second 'v' */ + + if (f_occur[u] > f_occur[v]) + + u = swap(u, u = v); + + + + // Starting and ending indexes of query range + + int qs = f_occur[u]; + + int qe = f_occur[v]; + + + + // query for index of LCA in tour + + int index = RMQ(sc, 2 * v - 1, qs, qe); + + + + /* return LCA node */ + + return euler[index]; + + + + } + + + + // Driver program to test above functions + + public static void main(String args[]) + + { + + BinaryTree tree = new BinaryTree(); + + + + // Let us create the Binary Tree as shown in the diagram. + + 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); + + tree.root.right.left = new Node(6); + + tree.root.right.right = new Node(7); + + tree.root.left.right.left = new Node(8); + + tree.root.left.right.right = new Node(9); + + + + int u = 4, v = 9; + + System.out.println("The LCA of node " + u + " and " + v + " is " + + + tree.findLCA(tree.root, u, v)); + + } + + +} diff --git a/HappyNumber.java b/HappyNumber.java new file mode 100644 index 0000000..dc1c618 --- /dev/null +++ b/HappyNumber.java @@ -0,0 +1,27 @@ +public class HappyNumber +{ + public static int isHappyNumber(int num){ + int rem = 0, sum = 0; + + while(num > 0){ + rem = num%10; + sum = sum + (rem*rem); + num = num/10; + } + return sum; + } + + public static void main(String[] args) { + int num = 82; + int result = num; + + while(result != 1 && result != 4){ + result = isHappyNumber(result); + } + + if(result == 1) + System.out.println(num + " is a happy number"); + else if(result == 4) + System.out.println(num + " is not a happy number"); + } +} diff --git a/Java Program to calculate Compound Interest.java b/Java Program to calculate Compound Interest.java new file mode 100644 index 0000000..9467663 --- /dev/null +++ b/Java Program to calculate Compound Interest.java @@ -0,0 +1,17 @@ +#https://m.facebook.com/story.php?story_fbid=2714895672163155&id=100009282474866 +#subscribe by code house + + +public class JavaExample { + + public void calculate(int p, int t, double r, int n) { + double amount = p * Math.pow(1 + (r / n), n * t); + double cinterest = amount - p; + System.out.println("Compound Interest after " + t + " years: "+cinterest); + System.out.println("Amount after " + t + " years: "+amount); + } + public static void main(String args[]) { + JavaExample obj = new JavaExample(); + obj.calculate(2000, 5, .08, 12); + } +} diff --git a/Java code explaining atan(), ceil(), copySign() method in lang.Math class b/Java code explaining atan(), ceil(), copySign() method in lang.Math class new file mode 100644 index 0000000..e10071c --- /dev/null +++ b/Java code explaining atan(), ceil(), copySign() method in lang.Math class @@ -0,0 +1,76 @@ +// Java program explaining lang.Math class methods +// atan(), ceil(), copySign() + + + +import java.math.*; + +public class NewClass +{ + + public static void main(String[] args) + + { + + // Use of atan() method + + double Atani = Math.atan(0); + + System.out.println("atan value of Atani : "+Atani); + + double x = Math.PI/2; + + + + // Use of toRadian() method + + x = Math.toRadians(x); + + double Atanj = Math.atan(x); + + System.out.println("atan value of Atanj : "+Atanj); + + System.out.println(""); + + + + + + // Use of ceil() method + + double val = 15.34 ,ceilval; + + ceilval = Math.ceil(val); + + System.out.println("ceil value of val : "+ceilval); + + System.out.println(""); + + + + double dblMag = val; + + double dblSign1 = 3; + + double dblSign2 = -3; + + + + + + // Use of copySign() method + + double result1 = Math.copySign(dblMag,dblSign1); + + System.out.println("copySign1 : "+result1); + + + + double result2 = Math.copySign(dblMag,dblSign2); + + System.out.println("copySign2 : "+result2); + + + + } +} diff --git a/Java program to create a doubly linked list of n nodes and count the number of nodes b/Java program to create a doubly linked list of n nodes and count the number of nodes new file mode 100644 index 0000000..806aaff --- /dev/null +++ b/Java program to create a doubly linked list of n nodes and count the number of nodes @@ -0,0 +1,91 @@ +public class CountList { + + //Represent a node of the doubly linked list + + class Node{ + int data; + Node previous; + Node next; + + public Node(int data) { + this.data = data; + } + } + + //Represent the head and tail of the doubly linked list + Node head, tail = null; + + //addNode() will add a node to the list + public void addNode(int data) { + //Create a new node + Node newNode = new Node(data); + + //If list is empty + if(head == null) { + //Both head and tail will point to newNode + head = tail = newNode; + //head's previous will point to null + head.previous = null; + //tail's next will point to null, as it is the last node of the list + tail.next = null; + } + else { + //newNode will be added after tail such that tail's next will point to newNode + tail.next = newNode; + //newNode's previous will point to tail + newNode.previous = tail; + //newNode will become new tail + tail = newNode; + //As it is last node, tail's next will point to null + tail.next = null; + } + } + + //countNodes() will count the nodes present in the list + public int countNodes() { + int counter = 0; + //Node current will point to head + Node current = head; + + while(current != null) { + //Increment the counter by 1 for each node + counter++; + current = current.next; + } + return counter; + } + + //display() will print out the elements of the list + public void display() { + //Node current will point to head + Node current = head; + if(head == null) { + System.out.println("List is empty"); + return; + } + System.out.println("Nodes of doubly linked list: "); + while(current != null) { + //Prints each node by incrementing the pointer. + + System.out.print(current.data + " "); + current = current.next; + } + } + + public static void main(String[] args) { + + CountList dList = new CountList(); + //Add nodes to the list + dList.addNode(1); + dList.addNode(2); + dList.addNode(3); + dList.addNode(4); + dList.addNode(5); + + //Displays the nodes present in the list + dList.display(); + + //Counts the nodes present in the given list + System.out.println("\nCount of nodes present in the list: " + dList.countNodes()); + } +} diff --git a/Java program to find the total number of possible Binary Search Trees with N keys b/Java program to find the total number of possible Binary Search Trees with N keys new file mode 100644 index 0000000..8938a63 --- /dev/null +++ b/Java program to find the total number of possible Binary Search Trees with N keys @@ -0,0 +1,51 @@ +public class BinarySearchTree { + + //Represent the node of binary tree + public static class Node{ + int data; + Node left; + Node right; + + public Node(int data){ + //Assign data to the new node, set left and right children to null + this.data = data; + this.left = null; + this.right = null; + } + } + + //Represent the root of binary tree + public Node root; + + public BinarySearchTree(){ + root = null; + } + + //factorial() will calculate the factorial of given number + public int factorial(int num) { + int fact = 1; + if(num == 0) + return 1; + else { + while(num > 1) { + fact = fact * num; + num--; + } + return fact; + } + } + + //numOfBST() will calculate the total number of possible BST by calculating Catalan Number for given key + public int numOfBST(int key) { + int catalanNumber = factorial(2 * key)/(factorial(key + 1) * factorial(key)); + return catalanNumber; + } + + public static void main(String[] args) { + + BinarySearchTree bt = new BinarySearchTree(); + + //Display total number of possible binary search tree with key 5 + System.out.println("Total number of possible Binary Search Trees with given key: " + bt.numOfBST(5)); + } +} diff --git a/Magic number b/Magic number new file mode 100644 index 0000000..6144e9c --- /dev/null +++ b/Magic number @@ -0,0 +1,32 @@ +import java.util.Scanner; + +public class MagicNumber +{ + public static void main(String[] args) + { + int n, r = 1, num, sum = 0; + Scanner sc = new Scanner(System.in); + System.out.print("Enter number="); + n = sc.nextInt(); + num = n; + while (num > 9) + { + while (num > 0) + { + r = num % 10; + sum = sum + r; + num = num / 10; + } + num = sum; + sum = 0; + } + if (num == 1) + { + System.out.println("Magic Number"); + } + else + { + System.out.println("Not Magic Number"); + } + } +} diff --git a/MapDemo.java b/MapDemo.java new file mode 100644 index 0000000..f17d317 --- /dev/null +++ b/MapDemo.java @@ -0,0 +1,34 @@ +/* Here is given a phone book that consists of people's names and their phone number. +After that I will take some person's name as query. +For each query I print the phone number of that person. */ + +import java.util.*; +import java.io.*; + +class Solution{ + public static void main(String []argh) + { + Scanner in = new Scanner(System.in); + int n=in.nextInt(); + in.nextLine(); + Map m=new HashMap(); + for(int i=0;i0) + { + + char c = sb.charAt(0); + if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') + { + sb.replace(0,1,"z"); + + } + else + { + sb.deleteCharAt(0); + } + if(chance) + a++; + else + b++; + chance = !chance; + } + if(a>b) + System.out.println("A"); + else if(b>a) + System.out.println("B"); + else + System.out.println("D"); + } + + } +} diff --git a/Permutation.java b/Permutation.java new file mode 100644 index 0000000..4e1a9e8 --- /dev/null +++ b/Permutation.java @@ -0,0 +1,22 @@ +/* This code will find all permutations of a given string +Recursion is used here*/ +import java.util.ArrayList; + +public class Permutation1 { +public static void main(String[] args) { + printPer("1234",""); +} + +//this method will find all permutations + public static void printPer(String ques,String ans){ + if(ques.length()==0){ + System.out.println(ans); + return; + } + for(int i=0;i=1) +System.out.println("Entered number is not a prime number"); +else +System.out.println("Entered number is a prime number"); +} +} diff --git a/ReverseString.java b/ReverseString.java index c4708bf..108c825 100644 --- a/ReverseString.java +++ b/ReverseString.java @@ -1,3 +1,28 @@ + +public class Main +{ + public static void main(String[] args) { + String s="I love my India"; + int i=s.length()-1; + String ans=""; + while(i>=0) + { + if(i<0) + break; + while(i>=0 && s.charAt(i)==' ') + i--; + int j=i; + while(i>=0 && s.charAt(i)!=' ') + i--; + if(ans.isEmpty()){ + ans=ans.concat(s.substring(i+1,j+1)); + }else{ + ans=ans.concat(" "+s.substring(i+1,j+1)); + } + } + System.out.println(ans); + } +} // Java program to ReverseString using ByteArray. import java.lang.*; import java.io.*; diff --git a/Reversed Pyramid Star Pattern b/Reversed Pyramid Star Pattern new file mode 100644 index 0000000..6e68dd4 --- /dev/null +++ b/Reversed Pyramid Star Pattern @@ -0,0 +1,25 @@ +import java.util.Scanner; +public class Pattern +{ + public static void main(String[] args) +{ + Scanner sc = new Scanner(System.in); + System.out.println("Enter the number of rows: "); + + int rows = sc.nextInt(); + for (int i= 0; i<= rows-1 ; i++) + { + for (int j=0; j<=i; j++) + { + System.out.print(" "); + } + for (int k=0; k<=rows-1-i; k++) + { + System.out.print("*" + " "); + } + System.out.println(); + } + sc.close(); + +} +} diff --git a/Selection_Sort.java b/Selection_Sort.java new file mode 100644 index 0000000..141fdfc --- /dev/null +++ b/Selection_Sort.java @@ -0,0 +1,49 @@ +//https://www.facebook.com/permalink.php?story_fbid=2750473708542571&id=100007399066161 +//Subscribed by tharindu Rewatha + +class JavaExample +{ + void selectionSort(int arr[]) + { + int len = arr.length; + + for (int i = 0; i < len-1; i++) + { + // Finding the minimum element in the unsorted part of array + int min = i; + for (int j = i+1; j < len; j++) + if (arr[j] < arr[min]) + min = j; + + /* Swapping the found minimum element with the first + * element of the sorted subarray using temp variable + */ + int temp = arr[min]; + arr[min] = arr[i]; + arr[i] = temp; + } + } + + // Displays the array elements + void printArr(int arr[]) + { + for (int i=0; i= 1) + { + System.out.println("First "+n+" prime numbers are:"); + //2 is a known prime number + System.out.println(2); + } + + for ( int i = 2 ; i <=n ; ) + { + for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) + { + if ( num%j == 0 ) + { + status = 0; + break; + } + } + if ( status != 0 ) + { + System.out.println(num); + i++; + } + status = 1; + num++; + } + } +} diff --git a/Sieve of Eratosthenes b/Sieve of Eratosthenes new file mode 100644 index 0000000..f2ef21e --- /dev/null +++ b/Sieve of Eratosthenes @@ -0,0 +1,51 @@ +// { Driver Code Starts +//Initial Template for Java +import java.io.*; +import java.util.*; + +class GFG +{ + public static void main(String args[])throws IOException + { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + while(t-- > 0) + { + int N=sc.nextInt(); + + Solution ob = new Solution(); + ArrayList primes = ob.sieveOfEratosthenes(N); + for(int prime : primes) { + System.out.print(prime+" "); + } + System.out.println(); + } + } +} +// } Driver Code Ends + + +//User function Template for Java +class Solution{ + static ArrayList sieveOfEratosthenes(int N){ + // code here + ArrayList numbers=new ArrayList(); + int i=0; + + + boolean isPrime[]=new boolean[N+1]; + Arrays.fill(isPrime,true); + + for(i=2;i*i<=N;i++){ + if(isPrime[i]){ + for(int j=2*i;j<=N;j=j+i) + isPrime[j]=false; + } + } + for(i=2;i<=N;i++){ + if(isPrime[i]) + numbers.add(i); + } + return numbers; + } +} diff --git a/Sorting LinkedList.java b/Sorting LinkedList.java new file mode 100644 index 0000000..6b70da7 --- /dev/null +++ b/Sorting LinkedList.java @@ -0,0 +1,26 @@ +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedList; +public class LinkedListSorting{ public static void main(String args[]) { + +// Creating and initializing an LinkedList for sorting +LinkedList singlyLinkedList = new LinkedList<>(); +singlyLinkedList.add("Eclipse"); +singlyLinkedList.add("NetBeans"); +singlyLinkedList.add("IntelliJ"); +singlyLinkedList.add("Resharper"); +singlyLinkedList.add("Visual Studio"); +singlyLinkedList.add("notepad"); +System.out.println("LinkedList (before sorting): " + singlyLinkedList); + +//Sorting LinkedList with Collecitons.sort() method in natural order +Collections.sort(singlyLinkedList); + +System.out.println("LinkedList (after sorting in natural): " + singlyLinkedList); + +// Example 2 - Sorting LinkedList using Collection.sort() and Comparator in Java +Collections.sort(singlyLinkedList, new Comparator() { +@Override +public int compare(String s1, String s2) { return s1.length() - s2.length(); } } ); + +System.out.println("LinkedList (after sorting using Comparator): " + singlyLinkedList); } } diff --git a/Sum of array b/Sum of array new file mode 100644 index 0000000..c757c4a --- /dev/null +++ b/Sum of array @@ -0,0 +1,11 @@ +class SumOfArray{ + public static void main(String args[]){ + int[] array = {10, 20, 30, 40, 50, 10}; + int sum = 0; + //Advanced for loop + for( int num : array) { + sum = sum+num; + } + System.out.println("Sum of array elements is:"+sum); + } +} diff --git a/add two binary numbers.java b/add two binary numbers.java new file mode 100644 index 0000000..b50a7db --- /dev/null +++ b/add two binary numbers.java @@ -0,0 +1,43 @@ +//https://www.facebook.com/swati.mallik.180/posts/158104889312424 +//subscribed by swati +import java.util.Scanner; +public class JavaExample { + public static void main(String[] args) + { + //Two variables to hold two input binary numbers + long b1, b2; + int i = 0, carry = 0; + + //This is to hold the output binary number + int[] sum = new int[10]; + + //To read the input binary numbers entered by user + Scanner scanner = new Scanner(System.in); + + //getting first binary number from user + System.out.print("Enter first binary number: "); + b1 = scanner.nextLong(); + //getting second binary number from user + System.out.print("Enter second binary number: "); + b2 = scanner.nextLong(); + + //closing scanner after use to avoid memory leak + scanner.close(); + while (b1 != 0 || b2 != 0) + { + sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2); + carry = (int)((b1 % 10 + b2 % 10 + carry) / 2); + b1 = b1 / 10; + b2 = b2 / 10; + } + if (carry != 0) { + sum[i++] = carry; + } + --i; + System.out.print("Output: "); + while (i >= 0) { + System.out.print(sum[i--]); + } + System.out.print("\n"); + } +} diff --git a/add two date b/add two date new file mode 100644 index 0000000..5ccc406 --- /dev/null +++ b/add two date @@ -0,0 +1,22 @@ +import java.util.Calendar; + +public class AddDates { + + public static void main(String[] args) { + + Calendar c1 = Calendar.getInstance(); + Calendar c2 = Calendar.getInstance(); + Calendar cTotal = (Calendar) c1.clone(); + + cTotal.add(Calendar.YEAR, c2.get(Calendar.YEAR)); + cTotal.add(Calendar.MONTH, c2.get(Calendar.MONTH) + 1); // Zero-based months + cTotal.add(Calendar.DATE, c2.get(Calendar.DATE)); + cTotal.add(Calendar.HOUR_OF_DAY, c2.get(Calendar.HOUR_OF_DAY)); + cTotal.add(Calendar.MINUTE, c2.get(Calendar.MINUTE)); + cTotal.add(Calendar.SECOND, c2.get(Calendar.SECOND)); + cTotal.add(Calendar.MILLISECOND, c2.get(Calendar.MILLISECOND)); + + System.out.format("%s + %s = %s", c1.getTime(), c2.getTime(), cTotal.getTime()); + + } +} diff --git a/airport_algo.java b/airport_algo.java new file mode 100644 index 0000000..28205de --- /dev/null +++ b/airport_algo.java @@ -0,0 +1,94 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +public class DijkstraSingleSourceShortestPath { + + public Integer[][] singleSourceShortestPath(Integer[][] weight,int source){ + //auxiliary constants + final int SIZE = weight.length; + final int EVE = -1;//to indicate no predecessor + final int INFINITY = Integer.MAX_VALUE; + + //declare and initialize pred to EVE and minDist to INFINITY + Integer[] pred = new Integer[SIZE]; + Integer[] minDist = new Integer[SIZE]; + Arrays.fill(pred, EVE); + Arrays.fill(minDist, INFINITY); + + //set minDist[source] =0 because source is 0 distance from itself. + minDist[source] = 0; + + PriorityQueue pq = createPriorityQueue(minDist); + + while (!pq.isEmpty()) { + updatePriorityQueue(pq); + int v = pq.remove()[0]; + for (Integer[] XD : adjacency(weight, pq, v)) { + Integer x = XD[0]; + //triangle inequality + if (null != x && minDist[x] > minDist[v] + weight[v][x]) { + minDist[x] = minDist[v] + weight[v][x]; + pred[XD[0]] = v; + XD[1] = minDist[x];//update pq. + } + } + } + Integer[][] result = {pred, minDist}; + return result; + } + + /********************************************************************* + * Create a priority queue and load it with the vertices sorted by + * minDist. + ********************************************************************/ + private PriorityQueue createPriorityQueue(Integer[] dist) { + PriorityQueue pq = new PriorityQueue(11, + new Comparator() { + public int compare(Integer[] A, Integer[] B) { + return A[1] < B[1] ? -1 : 1; + } + }); + for (int v = 0; v < dist.length; v++) { + pq.add(new Integer[]{v, dist[v]}); + } + return pq; + } + + /****************************************************************** + * Retrieve all the neighbors of vertex v that are + * in the priority queue pq. + *****************************************************************/ + private List adjacency(Integer[][] G, + PriorityQueue pq, int v) { + List result = new ArrayList(); + for (Integer[] ent : pq) {// {u,key[u]} + int u = ent[0]; + if (G[v][u] != null) { + result.add(ent); + } + } + return result; + } + + /***************************************************************** + * Re-prioritize the queue based on changes in the + * minDist array. + * + * Technical Details: Dijktra's algorithm requires a priority queue + * that changes continuously to reflect changes in minDist. + * For Java it does not suffice to simply pass new values to + * the array objects that constitute the queue. The + * PriorityQueue data structure in Java only checks its structure + * when it is adding or removing elements. It is unaware of any + * direct changes to the objects it comprises. Therefore to force + * the queue to re-prioritize, an element is removed and then + * immediately added back. + * + *****************************************************************/ + private void updatePriorityQueue(PriorityQueue pq) { + pq.add(pq.remove()); + } +} diff --git a/binary into decimal b/binary into decimal new file mode 100644 index 0000000..f2f0d40 --- /dev/null +++ b/binary into decimal @@ -0,0 +1,39 @@ + +// Java program to convert +// binary to decimal + +// Function to convert +// binary to decimal +class GFG { + static int binaryToDecimal(int n) + { + int num = n; + int dec_value = 0; + + // Initializing base + // value to 1, i.e 2^0 + int base = 1; + + int temp = num; + while (temp > 0) { + int last_digit = temp % 10; + temp = temp / 10; + + dec_value += last_digit * base; + + base = base * 2; + } + + return dec_value; + } + + // Driver Code + public static void main(String[] args) + { + int num = 10101001; + System.out.println(binaryToDecimal(num)); + } +} + + + diff --git a/bool.java b/bool.java new file mode 100644 index 0000000..2ec8a18 --- /dev/null +++ b/bool.java @@ -0,0 +1,10 @@ +#web.facebook.com/idajo.jeff/posts/128970875635248 +#subscribed by codehouse india +public class MyClass { + public static void main(String[] args) { + boolean isJavaFun = true; + boolean isFishTasty = false; + System.out.println(isJavaFun); + System.out.println(isFishTasty); + } +} diff --git a/check power on a number.java b/check power on a number.java new file mode 100644 index 0000000..a9db6ce --- /dev/null +++ b/check power on a number.java @@ -0,0 +1,20 @@ + +//https://www.facebook.com/swati.mallik.180/posts/158104889312424 +//subscribed by swati +public class JavaExample { + public static void main(String[] args) { + //Here number is the base and p is the exponent + int number = 2, p = 5; + long result = 1; + + //Copying the exponent value to the loop counter + int i = p; + for (;i != 0; --i) + { + result *= number; + } + + //Displaying the output + System.out.println(number+"^"+p+" = "+result); + } +} diff --git a/checkautomorphic.java b/checkautomorphic.java new file mode 100644 index 0000000..43d9e8b --- /dev/null +++ b/checkautomorphic.java @@ -0,0 +1,23 @@ +# https://www.facebook.com/permalink.php?story_fbid=1289077461428963&id=100009801635737 +# subscribed by jay patel +# java program to find automorphic +import java.util.*; +class Automorphic +{ + public static void main(String args[]) throws Exception + { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a Number : "); // Inputting the number + int n = sc.nextInt(); + int sq = n*n; // Finding the square + + String num = Integer.toString(n); // Converting the number to String + String square = Integer.toString(sq); // Converting the square to String + + if(square.endsWith(num)) // If the square ends with the number then it is Automorphic + System.out.print(n+" is an Automorphic Number."); + else + System.out.print(n+" is not an Automorphic Number."); + } +} + diff --git a/complex.java b/complex.java new file mode 100644 index 0000000..7047a0b --- /dev/null +++ b/complex.java @@ -0,0 +1,73 @@ +#https://www.facebook.com/harsha.gupta.1610/posts/2375944699218906 +#subscribed by Harsha Kumari + +import java.util.*; +class Complex { + + int real, imag; + Complex() + { + } + Complex(int tempReal, int tempImag) + { + real = tempReal; + imag = tempImag; + } + Complex(Complex com) + { + real=com.real; + imag=com.imag; + } + void showComplex() + { + System.out.println("Complex number: "+ real + " + "+ imag + "i"); + } + Complex addComplex(Complex C) + { + Complex temp = new Complex(); + temp.real = real + C.real; + temp.imag = imag + C.imag; + return temp; + } + Complex subtractComplex(Complex C) + { + Complex temp = new Complex(); + temp.real = real - C.real; + temp.imag = imag - C.imag; + return temp; + } + Complex multiplyComplex(Complex C) + { + Complex temp = new Complex(); + temp.real = real * C.real; + temp.imag = imag * C.imag; + return temp; + } + +} + + +public class Complexdemo { + public static void main(String[] args) + { + Complex C1 = new Complex(3, 2); + C1.showComplex(); + Complex C2 = new Complex(9, 5); + C2.showComplex(); + Complex C3 = new Complex(); + + System.out.println("Copy constructor called"); + Complex C4 = new Complex(C1); + C4.showComplex(); + + C3 = C1.addComplex(C2); + System.out.print("Sum of "); + C3.showComplex(); + C3 = C1.subtractComplex(C2); + System.out.print("Difference of "); + C3.showComplex(); + C3 = C1.multiplyComplex(C2); + System.out.print("Multiply of "); + C3.showComplex(); + } +} diff --git a/compundinterest.java b/compundinterest.java new file mode 100644 index 0000000..170014f --- /dev/null +++ b/compundinterest.java @@ -0,0 +1,16 @@ +#https://www.facebook.com/suyash.ssp/posts/2629289193987053 +#posted by suyash + +public class JavaExample { + + public void calculate(int p, int t, double r, int n) { + double amount = p * Math.pow(1 + (r / n), n * t); + double cinterest = amount - p; + System.out.println("Compound Interest after " + t + " years: "+cinterest); + System.out.println("Amount after " + t + " years: "+amount); + } + public static void main(String args[]) { + JavaExample obj = new JavaExample(); + obj.calculate(2000, 5, .08, 12); + } +} diff --git a/example of Quicksort Algorithm in java b/example of Quicksort Algorithm in java new file mode 100644 index 0000000..87b9ef2 --- /dev/null +++ b/example of Quicksort Algorithm in java @@ -0,0 +1,58 @@ +// Quick sort in Java + +import java.util.Arrays; + +class QuickSort { + + // Function to partition the array on the basis of pivot element + int partition(int array[], int low, int high) { + + // Select the pivot element + int pivot = array[high]; + int i = (low - 1); + + // Put the elements smaller than pivot on the left and + // greater than pivot on the right of pivot + for (int j = low; j < high; j++) { + if (array[j] <= pivot) { + i++; + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + } + int temp = array[i + 1]; + array[i + 1] = array[high]; + array[high] = temp; + return (i + 1); + } + + void quickSort(int array[], int low, int high) { + if (low < high) { + + // Select pivot position and put all the elements smaller + // than pivot on left and greater than pivot on right + int pi = partition(array, low, high); + + // Sort the elements on the left of pivot + quickSort(array, low, pi - 1); + + // Sort the elements on the right of pivot + quickSort(array, pi + 1, high); + } + } + + // Driver code + public static void main(String args[]) { + int[] data = { 8, 7, 2, 1, 0, 9, 6 }; + int size = data.length; + QuickSort qs = new QuickSort(); + qs.quickSort(data, 0, size - 1); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} +Quicksort Complexity +Time Complexities + + diff --git a/fact.java b/fact.java new file mode 100644 index 0000000..ae621fe --- /dev/null +++ b/fact.java @@ -0,0 +1,14 @@ +public class Factorial { + + public static void main(String[] args) { + + int num = 10; + long factorial = 1; + for(int i = 1; i <= num; ++i) + { + // factorial = factorial * i; + factorial *= i; + } + System.out.printf("Factorial of %d = %d", num, factorial); + } +} diff --git a/fibonaccinum.java b/fibonaccinum.java new file mode 100644 index 0000000..7326348 --- /dev/null +++ b/fibonaccinum.java @@ -0,0 +1,15 @@ +class FibonacciExample1{ +public static void main(String args[]) +{ + int n1=0,n2=1,n3,i,count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + + for(i=2;i numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + + // Using min() + int min = Collections.min(numbers); + System.out.println("Minimum Element: " + min); + + // Using max() + int max = Collections.max(numbers); + System.out.println("Maximum Element: " + max); + } +} diff --git a/palindrome.java b/palindrome.java index 26e957e..cf259b8 100644 --- a/palindrome.java +++ b/palindrome.java @@ -1,17 +1,36 @@ -class PalindromeExample{ - public static void main(String args[]){ - int r,sum=0,temp; - int n=454;//It is the number variable to be checked for palindrome - - temp=n; - while(n>0){ - r=n%10; //getting remainder - sum=(sum*10)+r; - n=n/10; - } - if(temp==sum) - System.out.println("palindrome number "); - else - System.out.println("not palindrome"); -} + +import java.util.Scanner; +class Palindrome +{ + public static void main(String args[]) + { + String original, reverse = ""; // Objects of String class + Scanner sc = new Scanner(System.in); + System.out.println("Enter a string"); + original = sc.nextLine(); + int length = original.length(); + for ( int i = length - 1; i >= 0; i-- ) + reverse = reverse + original.charAt(i); + if (original.equals(reverse)) + System.out.println("Enter string is palindrome."); + else + System.out.println("Enter string is not a palindrome."); + } +} +class PalindromeExample{ + public static void main(String args[]){ + int r,sum=0,temp; + int n=454;//It is the number variable to be checked for palindrome + + temp=n; + while(n>0){ + r=n%10; //getting remainder + sum=(sum*10)+r; + n=n/10; + } + if(temp==sum) + System.out.println("palindrome number "); + else + System.out.println("not palindrome"); +} } \ No newline at end of file diff --git a/pattern b/pattern new file mode 100644 index 0000000..adef3ae --- /dev/null +++ b/pattern @@ -0,0 +1,30 @@ +package Pattern; +import java.util.Scanner; + +public class Pattern { + + public static void main(String[] args) { + Scanner sc= new Scanner(System.in); + int n=sc.nextInt(); + System.out.println("*"); + + + + + for(int i=2;i<=n-1;i++) { + System.out.print("* "); + + for(int j=1;j<=i-2;j++) { + System.out.print(" "); + } + System.out.print("* "); + System.out.println(); + } + + for(int i=1;i<=n;i++) { + System.out.print("* "); + } + + } + +} diff --git a/printnumber b/printnumber new file mode 100644 index 0000000..9fe68b1 --- /dev/null +++ b/printnumber @@ -0,0 +1,15 @@ +public class Printnumber +{ + public static void main(String[] args) + { + //print the result + System.out.println("Output is : "); + + //loop to print 1 to 10. + for(int i = 1; i <= 10; i++) + { + System.out.println(i); + } + } +} + diff --git a/sn.java b/sn.java new file mode 100644 index 0000000..86a26b1 --- /dev/null +++ b/sn.java @@ -0,0 +1,18 @@ +import java.util.ArrayList; + +class Main { + public static void main(String[] args){ + // create ArrayList + ArrayList languages = new ArrayList<>(); + + // add() method without the index parameter + languages.add("Java"); + languages.add("C"); + languages.add("Python"); + System.out.println("ArrayList: " + languages); + + // add() method with the index parameter + languages.add(1, "JavaScript"); + System.out.println("Updated ArrayList: " + languages); + } +} diff --git a/spanning_tree b/spanning_tree new file mode 100644 index 0000000..41964e0 --- /dev/null +++ b/spanning_tree @@ -0,0 +1,27 @@ +ValueGraph spanningTree(ValueGraph graph, boolean minSpanningTree) { + Set edges = graph.edges(); + List edgeList = new ArrayList<>(edges); + + if (minSpanningTree) { + edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get())); + } else { + edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get()))); + } + + int totalNodes = graph.nodes().size(); + CycleDetector cycleDetector = new CycleDetector(totalNodes); + int edgeCount = 0; + + MutableValueGraph spanningTree = ValueGraphBuilder.undirected().build(); + for (EndpointPair edge : edgeList) { + if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) { + continue; + } + spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get()); + edgeCount++; + if (edgeCount == totalNodes - 1) { + break; + } + } + return spanningTree; +} diff --git a/string palindrome b/string palindrome new file mode 100644 index 0000000..407fe15 --- /dev/null +++ b/string palindrome @@ -0,0 +1,42 @@ +#https://www.facebook.com/permalink.php?story_fbid=2439553476338458&id=100008514873543 +# subscibe by Code House +// Java implementation of the approach +public class GFG { + + // Function that returns true if + // str is a palindrome + static boolean isPalindrome(String str) + { + + // Pointers pointing to the beginning + // and the end of the string + int i = 0, j = str.length() - 1; + + // While there are characters toc compare + while (i < j) { + + // If there is a mismatch + if (str.charAt(i) != str.charAt(j)) + return false; + + // Increment first pointer and + // decrement the other + i++; + j--; + } + + // Given string is a palindrome + return true; + } + + // Driver code + public static void main(String[] args) + { + String str = "geeks"; + + if (isPalindrome(str)) + System.out.print("Yes"); + else + System.out.print("No"); + } +} diff --git a/subsets_array.java b/subsets_array.java new file mode 100644 index 0000000..fccae75 --- /dev/null +++ b/subsets_array.java @@ -0,0 +1,45 @@ +import java.io.*; +import java.util.*; + +public class Main{ + +public static void main(String[] args) throws Exception { + // write your code here + Scanner scn = new Scanner(System.in); + int n = scn.nextInt(); + int[] arr = new int[n]; + for(int i= 0;i< n;i++){ + arr[i] = scn.nextInt(); + } + int count = (int)Math.pow(2,n); + for(int i=0;i