diff --git a/0-1pattern.cpp b/0-1pattern.cpp new file mode 100644 index 00000000..89f00eb9 --- /dev/null +++ b/0-1pattern.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int main() +{ + int n; + cin>>n; + + for(int i=1;i<=n;i++){ + for(int j=1;j<=i;j++){ + if((i+j)%2==0){ + cout<<" 1"; + } + else{ + cout<<" 0"; + } + } + cout< &ans) + { + if(root==NULL) + { + return; + } + else + { + ans.push_back(root->val); + preorder(root->left,ans); + preorder(root->right,ans); + } + } +public: + vector preorderTraversal(TreeNode* root) { + vector ans; + preorder(root,ans); + return ans; + } +}; + + + + +Using stack + +class Solution { +public: + vector preorderTraversal(TreeNode* root) { + vector ans; + if(root==NULL) + { + return ans; + } + else + { + stack st; + st.push(root); + while(!st.empty()) + { + TreeNode* node = st.top(); + st.pop(); + if(node->right!=NULL) + { + st.push(node->right); + } + if(node->left!=NULL) + { + st.push(node->left); + } + ans.push_back(node->val); + } + return ans; + } + } +}; \ No newline at end of file diff --git a/1.cpp b/1.cpp new file mode 100644 index 00000000..7e91239f --- /dev/null +++ b/1.cpp @@ -0,0 +1,210 @@ +// +// dsatrial1.cpp +// +// +// Created by Vansh Vatsal on 30/08/22. +// + +#include +using namespace std; + +class SEIT +{ + string name; + int roll; + float sgpa; + +public: + void getdata() + { + string a; + int b; + float c; + cout << "Enter Name : " << endl; + cin >> a; + cout << "Enter Roll No. : " << endl; + cin >> b; + cout << "Enter SGPA : " << endl; + cin >> c; + name = a; + roll = b; + sgpa = c; + } + void putdata() + { + cout << name << endl; + cout << roll << endl; + cout << sgpa << endl; + } + void linearsearch(SEIT s[], int n, float key) + { + bool flag = 1; + for (int i = 0; i < n; i++) + { + if (s[i].sgpa == key) + { + cout << "Object is present at " << i << " index." << endl; + s[i].putdata(); + flag = 0; + } + } + if (flag) + { + cout << "No record found" << endl; + } + } + + void binarysearch(SEIT s[], int n, string nm) + { + + int start = 0; + int end = n - 1; + int mid = (start + end) / 2; + bool flag = 1; + while (start <= end) + { + if (s[mid].name == nm) + { + s[mid].putdata(); + flag = 0; + break; + } + else if (s[mid].name < nm) + { + start = mid + 1; + } + else + { + end = mid - 1; + } + mid = (start + end) / 2; + } + if (flag) + { + cout << "No record found." << endl; + } + } + void bubblesort(SEIT s[], int n) + { + + for (int l = 0; l < n; ++l) + { + + for (int i = 0; i < n -l-1; ++i) + { + + if ( s[i].roll > s[i+1].roll) + { + swap(s[i],s[i+1]); + } + } + } + } + void insertionSort( SEIT s[], int size) { + for (int step = 1; step < size; step++) { + int key = s[step]; + int j = step - 1; + + // Compare key with each element on the left of it until an element smaller than + // it is found. + // For descending order, change keyarray[j]. + while (key < s[j] && j >= 0) { + s[j + 1] = s[j]; + --j; + } + s[j + 1] = key; + } +} + void printArray(SEIT s[], int n) + { + for (int i = 0; i < n; ++i) + { + cout << "roll " << s[i].roll<> n; + SEIT s[n]; + for (int i = 0; i < n; i++) + { + s[i].getdata(); + } + int status; + status = menu(); + while (true) + { + SEIT task; + + if (status == 4) + { + break; + } + else if (status == 1) + { + float key; + cout << "Enter SGPA of the student : " << endl; + cin >> key; + + task.linearsearch(s, n, key); + } + else if (status == 2) + { + string nm; + cout << "Enter the name of the student : " << endl; + cin >> nm; + task.binarysearch(s, n, nm); + } + else if (status == 3) + { + for (int i = 0; i < n; i++) + { + s[i].getdata(); + } + } + else if (status == 5) + { + + task.bubblesort(s, n); + cout << "Sorted Array in Ascending Order:\n"; + task.printArray(s,n); + + } + else if (status==6){ + task.insertionSort(s,size); + cout<<"Insertion Sort"< &ans) + { + if(root==NULL) + { + return; + } + else + { + postorder(root->left,ans); + postorder(root->right,ans); + ans.push_back(root->val); + } + } +public: + vector postorderTraversal(TreeNode* root) { + vector ans; + postorder(root,ans); + return ans; + } +}; + + + + +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + vector ans; + if(root==NULL) + { + return ans; + } + else if(root->left==NULL&root->right==NULL) + { + ans.push_back(root->val); + return ans; + } + else + { + stack st; + TreeNode* curr = root; + TreeNode* temp; + while(curr!=NULL||!st.empty()) + { + if(curr!=NULL) + { + st.push(curr); + curr=curr->left; + } + else + { + temp = st.top()->right; + if(temp==NULL) + { + temp = st.top(); + st.pop(); + ans.push_back(temp->val); + while(!st.empty()&&temp==st.top()->right) + { + temp = st.top(); + st.pop(); + ans.push_back(temp->val); + } + } + else + { + curr = temp; + } + } + } + return ans; + } + } +}; \ No newline at end of file diff --git a/24aug1.cpp b/24aug1.cpp new file mode 100644 index 00000000..9dd09379 --- /dev/null +++ b/24aug1.cpp @@ -0,0 +1,18 @@ +// PATTERN + +#include +using namespace std; +int main() +{ + int i,j,n; + cout<<"Enter any number : \n"; + cin>>n; + for ( i = n; i >= 1; i--) + { + for ( j = i; j>= 1; j--) + { + cout<<"*"; + } + cout<<"\n"; } + +} \ No newline at end of file diff --git a/3.InOrder Using Stack.txt b/3.InOrder Using Stack.txt new file mode 100644 index 00000000..87082442 --- /dev/null +++ b/3.InOrder Using Stack.txt @@ -0,0 +1,82 @@ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { + public: + void inorder(TreeNode* root,vector &ans) + { + if(root==NULL) + { + return; + } + else + { + inorder(root->left,ans); + ans.push_back(root->val); + inorder(root->right,ans); + } + } +public: + vector inorderTraversal(TreeNode* root) { + vector ans; + inorder(root,ans); + return ans; + } +}; + + + + + +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + vector ans; + if(!root) + { + return ans; + } + else if(root->left==NULL&&root->right==NULL) + { + ans.push_back(root->val); + return ans; + } + else + { + stack st; + TreeNode* node = root; + while(true) + { + if(node!=NULL) + { + st.push(node); + node=node->left; + } + else + { + if(st.empty()) + { + break; + } + else + { + node=st.top(); + ans.push_back(node->val); + st.pop(); + node = node->right; + } + } + } + return ans; + } + } +}; \ No newline at end of file diff --git a/31aug6.cpp b/31aug6.cpp new file mode 100644 index 00000000..eb35f71b --- /dev/null +++ b/31aug6.cpp @@ -0,0 +1,36 @@ +// Code to understand the working of the copy constructor. +#include +using namespace std; +class person +{ +private: + string name; + int age; + +public: + person(string person_name, int person_age) + { + cout << "Constructor for both name and age is called" << endl; + name = person_name; + age = person_age; + } + person(const person &obj) + { + cout << "Copy constructor is called" << endl; + name = obj.name; + age = obj.age; + } + void display() + { + cout << "Name of current object : " << name << endl; + cout << "Age of current object : " << age << endl; + cout << endl; + } +}; +int main() +{ + person obj1("First person", 25); + obj1.display(); + person obj2(obj1); + obj2.display(); +}; diff --git a/3D-Array.cpp b/3D-Array.cpp new file mode 100644 index 00000000..42434e9e --- /dev/null +++ b/3D-Array.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +int main(){ + int a, b, c; + cout << "Enter the Size of array\n"; //taking input for the size of array + cin >> a >> b >> c; + int arr[a][b][c]; //array of required size declared + + for (int i = 0; i < a; ++i) //counter for first dimension + { + for (int j = 0; j < b; ++j) //counter for second dimension + { + for (int k = 0; k < c; ++k) //counter for third dimension + { + cout << "\nEnter value at position[" << i << "]" << "[" << j << "]" << "[" << k << "]"; + + cin >> arr[i][j][k]; //taking input in the set counter + } + } + } + + for (int i = 0; i < a; ++i) //printing the array values as set + { + for (int j = 0; j < b; ++j) + { + for (int k = 0; k < c; ++k) + { + cout << "\nValue at position[" << i << "]" << "[" << j << "]" << "[" << k << "]= " << arr[i][j][k]; + } + } + } + return 0; +} diff --git a/3rd.cpp b/3rd.cpp new file mode 100644 index 00000000..1529f414 --- /dev/null +++ b/3rd.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; + +int main(){ + + int n; + cin>>n; + + int sum=0; + for(int counter=1;counter<=n;counter++){ + sum=sum+counter; + } + cout<= withdraw) + { + //remove the withdrawl amount from the total balance + balance = balance - withdraw; + System.out.println("Please collect your money"); + } + else + { + //show custom error message + System.out.println("Insufficient Balance"); + } + System.out.println(""); + break; + + case 2: + + System.out.print("Enter money to be deposited:"); + + //get deposite amount from te user + deposit = sc.nextInt(); + + //add the deposit amount to the total balanace + balance = balance + deposit; + System.out.println("Your Money has been successfully depsited"); + System.out.println(""); + break; + + case 3: + //displaying the total balance of the user + System.out.println("Balance : "+balance); + System.out.println(""); + break; + + case 4: + //exit from the menu + System.exit(0); + } + } + } +} diff --git a/ATM machine.java b/ATM machine.java new file mode 100644 index 00000000..dcfb829f --- /dev/null +++ b/ATM machine.java @@ -0,0 +1,75 @@ +//import required classes and packages +import java.util.Scanner; + +//create ATMExample class to implement the ATM functionality +public class ATMExample +{ + //main method starts + public static void main(String args[] ) + { + //declare and initialize balance, withdraw, and deposit + int balance = 100000, withdraw, deposit; + + //create scanner class object to get choice of user + Scanner sc = new Scanner(System.in); + + while(true) + { + System.out.println("Automated Teller Machine"); + System.out.println("Choose 1 for Withdraw"); + System.out.println("Choose 2 for Deposit"); + System.out.println("Choose 3 for Check Balance"); + System.out.println("Choose 4 for EXIT"); + System.out.print("Choose the operation you want to perform:"); + + //get choice from user + int choice = sc.nextInt(); + switch(choice) + { + case 1: + System.out.print("Enter money to be withdrawn:"); + + //get the withdrawl money from user + withdraw = sc.nextInt(); + + //check whether the balance is greater than or equal to the withdrawal amount + if(balance >= withdraw) + { + //remove the withdrawl amount from the total balance + balance = balance - withdraw; + System.out.println("Please collect your money"); + } + else + { + //show custom error message + System.out.println("Insufficient Balance"); + } + System.out.println(""); + break; + + case 2: + + System.out.print("Enter money to be deposited:"); + + //get deposite amount from te user + deposit = sc.nextInt(); + + //add the deposit amount to the total balanace + balance = balance + deposit; + System.out.println("Your Money has been successfully depsited"); + System.out.println(""); + break; + + case 3: + //displaying the total balance of the user + System.out.println("Balance : "+balance); + System.out.println(""); + break; + + case 4: + //exit from the menu + System.exit(0); + } + } + } +} diff --git a/ATM.java b/ATM.java new file mode 100644 index 00000000..dcfb829f --- /dev/null +++ b/ATM.java @@ -0,0 +1,75 @@ +//import required classes and packages +import java.util.Scanner; + +//create ATMExample class to implement the ATM functionality +public class ATMExample +{ + //main method starts + public static void main(String args[] ) + { + //declare and initialize balance, withdraw, and deposit + int balance = 100000, withdraw, deposit; + + //create scanner class object to get choice of user + Scanner sc = new Scanner(System.in); + + while(true) + { + System.out.println("Automated Teller Machine"); + System.out.println("Choose 1 for Withdraw"); + System.out.println("Choose 2 for Deposit"); + System.out.println("Choose 3 for Check Balance"); + System.out.println("Choose 4 for EXIT"); + System.out.print("Choose the operation you want to perform:"); + + //get choice from user + int choice = sc.nextInt(); + switch(choice) + { + case 1: + System.out.print("Enter money to be withdrawn:"); + + //get the withdrawl money from user + withdraw = sc.nextInt(); + + //check whether the balance is greater than or equal to the withdrawal amount + if(balance >= withdraw) + { + //remove the withdrawl amount from the total balance + balance = balance - withdraw; + System.out.println("Please collect your money"); + } + else + { + //show custom error message + System.out.println("Insufficient Balance"); + } + System.out.println(""); + break; + + case 2: + + System.out.print("Enter money to be deposited:"); + + //get deposite amount from te user + deposit = sc.nextInt(); + + //add the deposit amount to the total balanace + balance = balance + deposit; + System.out.println("Your Money has been successfully depsited"); + System.out.println(""); + break; + + case 3: + //displaying the total balance of the user + System.out.println("Balance : "+balance); + System.out.println(""); + break; + + case 4: + //exit from the menu + System.exit(0); + } + } + } +} diff --git a/AVLTreeJava.java b/AVLTreeJava.java new file mode 100644 index 00000000..0491737e --- /dev/null +++ b/AVLTreeJava.java @@ -0,0 +1,192 @@ +// AVL tree implementation in Java + +// Create node +class Node { + int item, height; + Node left, right; + + Node(int d) { + item = d; + height = 1; + } +} + +// Tree class +class AVLTreeJava { + Node root; + + int height(Node N) { + if (N == null) + return 0; + return N.height; + } + + int max(int a, int b) { + return (a > b) ? a : b; + } + + Node rightRotate(Node y) { + Node x = y.left; + Node T2 = x.right; + x.right = y; + y.left = T2; + y.height = max(height(y.left), height(y.right)) + 1; + x.height = max(height(x.left), height(x.right)) + 1; + return x; + } + + Node leftRotate(Node x) { + Node y = x.right; + Node T2 = y.left; + y.left = x; + x.right = T2; + x.height = max(height(x.left), height(x.right)) + 1; + y.height = max(height(y.left), height(y.right)) + 1; + return y; + } + + // Get balance factor of a node + int getBalanceFactor(Node N) { + if (N == null) + return 0; + return height(N.left) - height(N.right); + } + + // Insert a node + Node insertNode(Node node, int item) { + + // Find the position and insert the node + if (node == null) + return (new Node(item)); + if (item < node.item) + node.left = insertNode(node.left, item); + else if (item > node.item) + node.right = insertNode(node.right, item); + else + return node; + + // Update the balance factor of each node + // And, balance the tree + node.height = 1 + max(height(node.left), height(node.right)); + int balanceFactor = getBalanceFactor(node); + if (balanceFactor > 1) { + if (item < node.left.item) { + return rightRotate(node); + } else if (item > node.left.item) { + node.left = leftRotate(node.left); + return rightRotate(node); + } + } + if (balanceFactor < -1) { + if (item > node.right.item) { + return leftRotate(node); + } else if (item < node.right.item) { + node.right = rightRotate(node.right); + return leftRotate(node); + } + } + return node; + } + + Node nodeWithMimumValue(Node node) { + Node current = node; + while (current.left != null) + current = current.left; + return current; + } + + // Delete a node + Node deleteNode(Node root, int item) { + + // Find the node to be deleted and remove it + if (root == null) + return root; + if (item < root.item) + root.left = deleteNode(root.left, item); + else if (item > root.item) + root.right = deleteNode(root.right, item); + else { + if ((root.left == null) || (root.right == null)) { + Node temp = null; + if (temp == root.left) + temp = root.right; + else + temp = root.left; + if (temp == null) { + temp = root; + root = null; + } else + root = temp; + } else { + Node temp = nodeWithMimumValue(root.right); + root.item = temp.item; + root.right = deleteNode(root.right, temp.item); + } + } + if (root == null) + return root; + + // Update the balance factor of each node and balance the tree + root.height = max(height(root.left), height(root.right)) + 1; + int balanceFactor = getBalanceFactor(root); + if (balanceFactor > 1) { + if (getBalanceFactor(root.left) >= 0) { + return rightRotate(root); + } else { + root.left = leftRotate(root.left); + return rightRotate(root); + } + } + if (balanceFactor < -1) { + if (getBalanceFactor(root.right) <= 0) { + return leftRotate(root); + } else { + root.right = rightRotate(root.right); + return leftRotate(root); + } + } + return root; + } + + void preOrder(Node node) { + if (node != null) { + System.out.print(node.item + " "); + preOrder(node.left); + preOrder(node.right); + } + } + + // Print the tree + private void printTree(Node currPtr, String indent, boolean last) { + if (currPtr != null) { + System.out.print(indent); + if (last) { + System.out.print("R----"); + indent += " "; + } else { + System.out.print("L----"); + indent += "| "; + } + System.out.println(currPtr.item); + printTree(currPtr.left, indent, false); + printTree(currPtr.right, indent, true); + } + } + + // Driver code + public static void main(String[] args) { + AVLTree tree = new AVLTree(); + tree.root = tree.insertNode(tree.root, 33); + tree.root = tree.insertNode(tree.root, 13); + tree.root = tree.insertNode(tree.root, 53); + tree.root = tree.insertNode(tree.root, 9); + tree.root = tree.insertNode(tree.root, 21); + tree.root = tree.insertNode(tree.root, 61); + tree.root = tree.insertNode(tree.root, 8); + tree.root = tree.insertNode(tree.root, 11); + tree.printTree(tree.root, "", true); + tree.root = tree.deleteNode(tree.root, 13); + System.out.println("After Deletion: "); + tree.printTree(tree.root, "", true); + } +} \ No newline at end of file diff --git a/AVLTreeProgram.java b/AVLTreeProgram.java new file mode 100644 index 00000000..0491737e --- /dev/null +++ b/AVLTreeProgram.java @@ -0,0 +1,192 @@ +// AVL tree implementation in Java + +// Create node +class Node { + int item, height; + Node left, right; + + Node(int d) { + item = d; + height = 1; + } +} + +// Tree class +class AVLTreeJava { + Node root; + + int height(Node N) { + if (N == null) + return 0; + return N.height; + } + + int max(int a, int b) { + return (a > b) ? a : b; + } + + Node rightRotate(Node y) { + Node x = y.left; + Node T2 = x.right; + x.right = y; + y.left = T2; + y.height = max(height(y.left), height(y.right)) + 1; + x.height = max(height(x.left), height(x.right)) + 1; + return x; + } + + Node leftRotate(Node x) { + Node y = x.right; + Node T2 = y.left; + y.left = x; + x.right = T2; + x.height = max(height(x.left), height(x.right)) + 1; + y.height = max(height(y.left), height(y.right)) + 1; + return y; + } + + // Get balance factor of a node + int getBalanceFactor(Node N) { + if (N == null) + return 0; + return height(N.left) - height(N.right); + } + + // Insert a node + Node insertNode(Node node, int item) { + + // Find the position and insert the node + if (node == null) + return (new Node(item)); + if (item < node.item) + node.left = insertNode(node.left, item); + else if (item > node.item) + node.right = insertNode(node.right, item); + else + return node; + + // Update the balance factor of each node + // And, balance the tree + node.height = 1 + max(height(node.left), height(node.right)); + int balanceFactor = getBalanceFactor(node); + if (balanceFactor > 1) { + if (item < node.left.item) { + return rightRotate(node); + } else if (item > node.left.item) { + node.left = leftRotate(node.left); + return rightRotate(node); + } + } + if (balanceFactor < -1) { + if (item > node.right.item) { + return leftRotate(node); + } else if (item < node.right.item) { + node.right = rightRotate(node.right); + return leftRotate(node); + } + } + return node; + } + + Node nodeWithMimumValue(Node node) { + Node current = node; + while (current.left != null) + current = current.left; + return current; + } + + // Delete a node + Node deleteNode(Node root, int item) { + + // Find the node to be deleted and remove it + if (root == null) + return root; + if (item < root.item) + root.left = deleteNode(root.left, item); + else if (item > root.item) + root.right = deleteNode(root.right, item); + else { + if ((root.left == null) || (root.right == null)) { + Node temp = null; + if (temp == root.left) + temp = root.right; + else + temp = root.left; + if (temp == null) { + temp = root; + root = null; + } else + root = temp; + } else { + Node temp = nodeWithMimumValue(root.right); + root.item = temp.item; + root.right = deleteNode(root.right, temp.item); + } + } + if (root == null) + return root; + + // Update the balance factor of each node and balance the tree + root.height = max(height(root.left), height(root.right)) + 1; + int balanceFactor = getBalanceFactor(root); + if (balanceFactor > 1) { + if (getBalanceFactor(root.left) >= 0) { + return rightRotate(root); + } else { + root.left = leftRotate(root.left); + return rightRotate(root); + } + } + if (balanceFactor < -1) { + if (getBalanceFactor(root.right) <= 0) { + return leftRotate(root); + } else { + root.right = rightRotate(root.right); + return leftRotate(root); + } + } + return root; + } + + void preOrder(Node node) { + if (node != null) { + System.out.print(node.item + " "); + preOrder(node.left); + preOrder(node.right); + } + } + + // Print the tree + private void printTree(Node currPtr, String indent, boolean last) { + if (currPtr != null) { + System.out.print(indent); + if (last) { + System.out.print("R----"); + indent += " "; + } else { + System.out.print("L----"); + indent += "| "; + } + System.out.println(currPtr.item); + printTree(currPtr.left, indent, false); + printTree(currPtr.right, indent, true); + } + } + + // Driver code + public static void main(String[] args) { + AVLTree tree = new AVLTree(); + tree.root = tree.insertNode(tree.root, 33); + tree.root = tree.insertNode(tree.root, 13); + tree.root = tree.insertNode(tree.root, 53); + tree.root = tree.insertNode(tree.root, 9); + tree.root = tree.insertNode(tree.root, 21); + tree.root = tree.insertNode(tree.root, 61); + tree.root = tree.insertNode(tree.root, 8); + tree.root = tree.insertNode(tree.root, 11); + tree.printTree(tree.root, "", true); + tree.root = tree.deleteNode(tree.root, 13); + System.out.println("After Deletion: "); + tree.printTree(tree.root, "", true); + } +} \ No newline at end of file diff --git a/ActivitySelection.java b/ActivitySelection.java new file mode 100644 index 00000000..ab37a377 --- /dev/null +++ b/ActivitySelection.java @@ -0,0 +1,51 @@ +import java.util.ArrayList; +import java.util.Collections; + +public class ActivitySelection { + + static class Activity { + int start; + int end; + + public Activity(int start, int end) { + this.start = start; + this.end = end; + } + + @Override + public String toString(){ + return "[" + this.start + ", " + this.end + "]"; + } + } + + public static void maxActivities(ArrayList activities){ + + //sort the activities in ascending order of meeting finish time + System.out.println("Given Activities: " + activities); + Collections.sort(activities, (o1, o2) -> o1.end - o2.end); + + ArrayList selectedActivities = new ArrayList<>(); + int currentEnd = -1; + for (int i = 0; i currentEnd){ + selectedActivities.add(currentActivity); + currentEnd = currentActivity.end; + } + } + + //print selected activities + System.out.println("Selected Activities: " + selectedActivities); + } + + public static void main(String[] args) { + ArrayList activities = new ArrayList<>(); + activities.add(new Activity(1, 3)); + activities.add(new Activity(2, 5)); + activities.add(new Activity(0, 7)); + activities.add(new Activity(6, 8)); + activities.add(new Activity(9, 11)); + activities.add(new Activity(10, 12)); + maxActivities(activities); + } +} \ No newline at end of file diff --git a/AdvancedCalculator.java b/AdvancedCalculator.java new file mode 100644 index 00000000..ee9f81fa --- /dev/null +++ b/AdvancedCalculator.java @@ -0,0 +1,33 @@ +class Calculator { + int add(int a , int b) + { + return a + b; + } + + int sub(int a , int b) + { + return a - b; + } +} + +public class AdvancedCalculator extends Calculator { + int mult(int a , int b) + { + return a * b; + } + + int div(int a , int b) + { + return a / b; + } + + public static void main(String args[]) + { + AdvancedCalculator cal = new AdvancedCalculator(); + + System.out.println( cal.add(1, 2) ); + System.out.println( cal.sub(1, 2) ); + System.out.println( cal.mult(1, 2) ); + System.out.println( cal.div(1, 2) ); + } +} \ No newline at end of file diff --git a/AllFactors.java b/AllFactors.java new file mode 100644 index 00000000..d91885f9 --- /dev/null +++ b/AllFactors.java @@ -0,0 +1,27 @@ +import java.util.*; + +public class AllFactors +{ + public static void main(String[] args) + { + System.out.print("Enter a Number : "); + Scanner sc = new Scanner(System.in); + + int num = sc.nextInt(); + + boolean flag = false; + for(int i=2; i close) { + str[pos] = '}'; + _printParenthesis(str, pos + 1, n, open, + close + 1); + } + if (open < n) { + str[pos] = '{'; + _printParenthesis(str, pos + 1, n, open + 1, + close); + } + } + } + + static void printParenthesis(char str[], int n) { + if (n > 0) + _printParenthesis(str, 0, n, 0, 0); + return; + } + + public static void main(String[] args) { + int n = 3; + char[] str = new char[2 * n]; + printParenthesis(str, n); + } +} diff --git a/Animal_Guessing_Game.py b/Animal_Guessing_Game.py new file mode 100644 index 00000000..0ddbd400 --- /dev/null +++ b/Animal_Guessing_Game.py @@ -0,0 +1,54 @@ +# *********************** Animal Guessing Game ******************* + +# Importing Libraries +import random +import time +from datetime import datetime + +# Initial Steps to invite in the game: +print("\nWelcome to ANIMAL GUESSING game by Sachin Dabhade\n") +name = input("Enter your name: ") +print("Hello " + name.capitalize() + "! Best of Luck!") +time.sleep(1) +print("\nThe game is about to start!\n Let's play and win!\n\n") +time.sleep(1) + +# This will record all the activities in the game +def record(): + with open("record.txt", "a") as f: + f.write(f"The ANIMAL GUESSING game is played by {name} on {datetime.now()}\n") + +if __name__ == '__main__': + + # Initializing the variables + chance = 5 + score = 0 + attempt = 0 + animal_list = ("Tiger", "Lion", "Giraffe", "Cheeta", "Rabbit") + print(f"\t\tANIMAL GUESSING GAME\n\n\t\t !...GOOD LUCK...!") + + while chance > attempt: + + # updating the variables and geting the inputs + animal = random.choice(animal_list) + attempt = attempt + 1 + print(f"\nYou need at least 2 score to won the game") + x = input("Guess the animal (Tiger, Lion, Giraffe, Cheeta, Rabbit):") + + # Checking the user input and the computer guess + if x.capitalize() == animal: + score = score + 1 + print("Congratulation... Your guess is absolutely correct...!") + + elif x.capitalize() in animal_list: + print("Sorry but you can do it! Keep trying...!") + + else: + print("Invalid input...!") + + print(f"The computer guess is {animal} and your guess is {x.capitalize()}") + print(f"Your score is {score} and you have {chance - attempt} attempt remaining.") + continue + +print("Thanks For Playing!\nWe expect you will back again and enjoy our game...!\n") +record() \ No newline at end of file diff --git a/ApplicationExceptionHandler.java b/ApplicationExceptionHandler.java new file mode 100644 index 00000000..7406053b --- /dev/null +++ b/ApplicationExceptionHandler.java @@ -0,0 +1,35 @@ +package com.simactivation.advice; + + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class ApplicationExceptionHandler { + + + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + public Map handleInvalidArgument(MethodArgumentNotValidException ex) { + Map errorMap = new HashMap<>(); + ex.getBindingResult().getFieldErrors().forEach(error -> { + errorMap.put(error.getField(), error.getDefaultMessage()); + }); + return errorMap; + } + +// @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) +// @ExceptionHandler(UserNotFoundException.class) +// public Map handleBusinessException(UserNotFoundException ex) { +// Map errorMap = new HashMap<>(); +// errorMap.put("errorMessage", ex.getMessage()); +// return errorMap; +// } + +} diff --git a/Area of triangle b/Area of triangle new file mode 100644 index 00000000..41390036 --- /dev/null +++ b/Area of triangle @@ -0,0 +1,9 @@ + Uncomment below to take inputs from the user + a = float(input('Enter first side: ')) + b = float(input('Enter second side: ')) + c = float(input('Enter third side: ')) + +s = (a + b + c) / 2 + +area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 +print('The area of the triangle is %0.2f' %area) diff --git a/Armstrong number in Java b/Armstrong number in Java new file mode 100644 index 00000000..8945cfc2 --- /dev/null +++ b/Armstrong number in Java @@ -0,0 +1,49 @@ +import java.util.Scanner; +import java.lang.Math; +public class ArmstsrongNumberExample +{ +//function to check if the number is Armstrong or not +static boolean isArmstrong(int n) +{ +int temp, digits=0, last=0, sum=0; +//assigning n into a temp variable +temp=n; +//loop execute until the condition becomes false +while(temp>0) +{ +temp = temp/10; +digits++; +} +temp = n; +while(temp>0) +{ +//determines the last digit from the number +last = temp % 10; +//calculates the power of a number up to digit times and add the resultant to the sum variable +sum += (Math.pow(last, digits)); +//removes the last digit +temp = temp/10; +} +//compares the sum with n +if(n==sum) +//returns if sum and n are equal +return true; +//returns false if sum and n are not equal +else return false; +} +//driver code +public static void main(String args[]) +{ +int num; +Scanner sc= new Scanner(System.in); +System.out.print("Enter the limit: "); +//reads the limit from the user +num=sc.nextInt(); +System.out.println("Armstrong Number up to "+ num + " are: "); +for(int i=0; i<=num; i++) +//function calling +if(isArmstrong(i)) +//prints the armstrong numbers +System.out.print(i+ ", "); +} +} diff --git a/Armstrong.java b/Armstrong.java new file mode 100644 index 00000000..9ee6eaf5 --- /dev/null +++ b/Armstrong.java @@ -0,0 +1,22 @@ +import java.util.Scanner; +public class ArmstrongNum { + static int number, originalNumber, remainder, result = 0; + public static void main(String[] args) { + Scanner s=new Scanner(System.in); + ArmstrongNum num = new ArmstrongNum(); + System.out.println("Enter the Number : "); + number = s.nextInt(); + originalNumber=number; + while (originalNumber != 0) + { + remainder = originalNumber % 10; + result += Math.pow(remainder, 3); + originalNumber /= 10; + } + + if(result == number) + System.out.println(number + " is an Armstrong number."); + else + System.out.println(number + " is not an Armstrong number."); + } +} diff --git a/Armstrong_Funtion.java b/Armstrong_Funtion.java new file mode 100644 index 00000000..f7d6c555 --- /dev/null +++ b/Armstrong_Funtion.java @@ -0,0 +1,40 @@ +import java.io.*; +class Armstrong_Funtion +{ + public int Number(int n) + { + int r,a=0,ano=n,flag=0; + while(n>0) + { + r = n%10; + a = a + (r*r*r); + n = (n-r)/10; + } + if(ano==a) + flag = 1; + else + flag = 0; + return(flag); + } + public static void main(String args[]) throws IOException + { + System.out.println("Armstrong Number"); + System.out.println("****************"); + System.out.println(""); + InputStreamReader isr=new InputStreamReader(System.in); + BufferedReader br=new BufferedReader(isr); + int d,p; + System.out.print("Enter Number : "); + d = Integer.parseInt(br.readLine()); + System.out.println(""); + Armstrong_Funtion ob = new Armstrong_Funtion(); + p = ob.Number(d); + if(p==1) + System.out.println("Number is Armstrong"); + else + System.out.println("Number is Not Armstrong"); + } +} + + + diff --git a/Armstrongnum.java b/Armstrongnum.java new file mode 100644 index 00000000..60db6b39 --- /dev/null +++ b/Armstrongnum.java @@ -0,0 +1,51 @@ +import java.util.Scanner; +import java.lang.Math; +public class ArmstsrongNumber +{ +//function to check if the number is Armstrong or not +static boolean isArmstrong(int n) +{ +int temp, digits=0, last=0, sum=0; +//assigning n into a temp variable +temp=n; +//loop execute until the condition becomes false +while(temp>0) +{ +temp = temp/10; +digits++; +} +temp = n; +while(temp>0) +{ +//determines the last digit from the number +last = temp % 10; +//calculates the power of a number up to digit times and add the resultant to the sum variable +sum += (Math.pow(last, digits)); +//removes the last digit +temp = temp/10; +} +//compares the sum with n +if(n==sum) +//returns if sum and n are equal +return true; +//returns false if sum and n are not equal +else return false; +} +//driver code +public static void main(String args[]) +{ +int num; +Scanner sc= new Scanner(System.in); +System.out.print("Enter the number: "); +//reads the limit from the user +num=sc.nextInt(); +if(isArmstrong(num)) +{ +System.out.print("Armstrong "); +} +else +{ +System.out.print("Not Armstrong "); +} +} +} diff --git a/ArrayList.java/Adding Elements.txt b/ArrayList.java/Adding Elements.txt new file mode 100644 index 00000000..28c3920b --- /dev/null +++ b/ArrayList.java/Adding Elements.txt @@ -0,0 +1,27 @@ +// Java Program to Add elements to An ArrayList + +// Importing all utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String args[]) + { + // Creating an Array of string type + ArrayList al = new ArrayList<>(); + + // Adding elements to ArrayList + // Custom inputs + al.add("one"); + al.add("three"); + + // Here we are mentioning the index + // at which it is to be added + al.add(1, "two"); + + // Printing all the elements in an ArrayList + System.out.println(al); + } +} diff --git a/ArrayList.java/Changing Elements.txt b/ArrayList.java/Changing Elements.txt new file mode 100644 index 00000000..52c21fb1 --- /dev/null +++ b/ArrayList.java/Changing Elements.txt @@ -0,0 +1,32 @@ +// Java Program to Change elements in ArrayList + +// Importing all utility classes +import java.util.*; + +// main class +class GFG { + + // Main driver method + public static void main(String args[]) + { + // Creating an Arraylist object of string type + ArrayList al = new ArrayList<>(); + + // Adding elements to Arraylist + // Custom input elements + al.add("one"); + al.add("three"); + + // Adding specifying the index to be added + al.add(1, "two"); + + // Printing the Arraylist elements + System.out.println("Initial ArrayList " + al); + + // Setting element at 1st index + al.set(1, "four"); + + // Printing the updated Arraylist + System.out.println("Updated ArrayList " + al); + } +} diff --git a/ArrayList.java/Removing Elements.txt b/ArrayList.java/Removing Elements.txt new file mode 100644 index 00000000..eb4ad22f --- /dev/null +++ b/ArrayList.java/Removing Elements.txt @@ -0,0 +1,38 @@ +// Java program to Remove Elements in ArrayList + +// Importing all utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String args[]) + { + // Creating an object of arraylist class + ArrayList al = new ArrayList<>(); + + // Adding elements to ArrayList + // Custom addition + al.add("one"); + al.add("three"); + // Adding element at specific index + al.add(1, "two"); + + // Printing all elements of ArrayList + System.out.println("Initial ArrayList " + al); + + // Removing element from above ArrayList + al.remove(1); + + // Printing the updated Arraylist elements + System.out.println("After the Index Removal " + al); + + // Removing this word element in ArrayList + al.remove("one"); + + // Now printing updated ArrayList + System.out.println("After the Object Removal " + + al); + } +} diff --git a/ArrayList.java/Size_Given.txt b/ArrayList.java/Size_Given.txt new file mode 100644 index 00000000..a30c53f6 --- /dev/null +++ b/ArrayList.java/Size_Given.txt @@ -0,0 +1,38 @@ +// Java program to demonstrate the +// working of ArrayList in Java + +import java.io.*; +import java.util.*; + +class ArrayListExample { + public static void main(String[] args) + { + // Size of the + // ArrayList + int n = 5; + + // Declaring the ArrayList with + // initial size n + ArrayList arrli + = new ArrayList(n); + + // Appending new elements at + // the end of the list + for (int i = 1; i <= n; i++) + arrli.add(i); + + // Printing elements + System.out.println(arrli); + + // Remove element at index 3 + arrli.remove(3); + + // Displaying the ArrayList + // after deletion + System.out.println(arrli); + + // Printing elements one by one + for (int i = 0; i < arrli.size(); i++) + System.out.print(arrli.get(i) + " "); + } +} diff --git a/ArrayList.java/Without_Size.txt b/ArrayList.java/Without_Size.txt new file mode 100644 index 00000000..aa8f1aa0 --- /dev/null +++ b/ArrayList.java/Without_Size.txt @@ -0,0 +1,33 @@ +// Java program to demonstrate the +// working of ArrayList in Java + +import java.io.*; +import java.util.*; + +class ArrayListExample { + public static void main(String[] args) + { + + // Declaring the ArrayList without mentioned its size + ArrayList arrli = new ArrayList<>(); + + // Appending new elements at + // the end of the list + for (int i = 1; i <= n; i++) + arrli.add(i); + + // Printing elements + System.out.println(arrli); + + // Remove element at index 3 + arrli.remove(3); + + // Displaying the ArrayList + // after deletion + System.out.println(arrli); + + // Printing elements one by one + for (int i = 0; i < arrli.size(); i++) + System.out.print(arrli.get(i) + " "); + } +} diff --git a/ArrayLists.java b/ArrayLists.java new file mode 100644 index 00000000..c2aa0319 --- /dev/null +++ b/ArrayLists.java @@ -0,0 +1,40 @@ +import java.util.*; + +class ArrayLists { + public static void main(String args[]) { + ArrayList list = new ArrayList(); + ArrayList list2 = new ArrayList(); + ArrayList list3 = new ArrayList(); + // add elements + list.add(1); + list.add(3); + list.add(4); + list.add(5); + System.out.println(list); + // to get an element + int element = list.get(0); // 0 is the index + System.out.println(element); + // add element in between + list.add(1, 2); // 1 is the index and 2 is the element to be added + System.out.println(list); + // set element + list.set(0, 0); + System.out.println(list); + // delete elements + list.remove(0); // 0 is the index + System.out.println(list); + // size of list + int size = list.size(); + System.out.println(size); + // Loops on lists + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i) + " "); + } + System.out.println(); + // Sorting the list + list.add(0); + Collections.sort(list); + System.out.println(list); + } +} + diff --git a/Assignment/Assets/entry.png b/Assignment/Assets/entry.png index 11d9bf30..5e712908 100644 Binary files a/Assignment/Assets/entry.png and b/Assignment/Assets/entry.png differ diff --git a/Assignment/Assets/error.png b/Assignment/Assets/error.png index f0fd445a..e5042a30 100644 Binary files a/Assignment/Assets/error.png and b/Assignment/Assets/error.png differ diff --git a/Assignment/Assets/full.png b/Assignment/Assets/full.png index f772a1ac..7b2cca58 100644 Binary files a/Assignment/Assets/full.png and b/Assignment/Assets/full.png differ diff --git a/Assignment/Assets/submit.png b/Assignment/Assets/submit.png index 56245ba4..7fe1dc70 100644 Binary files a/Assignment/Assets/submit.png and b/Assignment/Assets/submit.png differ diff --git a/Assignment/C++.4cpp b/Assignment/C++.4cpp new file mode 100644 index 00000000..15679559 --- /dev/null +++ b/Assignment/C++.4cpp @@ -0,0 +1,20 @@ +# include +using namespace std; + +int main() { + + int n, reversed_number = 0, remainder; + + cout << "Enter an integer: "; + cin >> n; + + while(n != 0) { + remainder = n % 10; + reversed_number = reversed_number * 10 + remainder; + n /= 10; + } + + cout << "Reversed Number = " << reversed_number; + + return 0; +} diff --git a/Assignment/tables.cpp b/Assignment/tables.cpp new file mode 100644 index 00000000..c48a4ba9 --- /dev/null +++ b/Assignment/tables.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() +{ + int n; + + cout << "Enter a positive integer: "; + cin >> n; + + for (int i = 1; i <= 10; ++i) { + cout << n << " * " << i << " = " << n * i << endl; + } + + return 0; +} diff --git a/BLOG.png b/BLOG.png new file mode 100644 index 00000000..67c3bb06 Binary files /dev/null and b/BLOG.png differ diff --git a/BTree.java b/BTree.java new file mode 100644 index 00000000..b106227b --- /dev/null +++ b/BTree.java @@ -0,0 +1,127 @@ +// Inserting a key on a B-tree in Java + +public class BTree { + + private int T; + + public class Node { + int n; + int key[] = new int[2 * T - 1]; + Node child[] = new Node[2 * T]; + boolean leaf = true; + + public int Find(int k) { + for (int i = 0; i < this.n; i++) { + if (this.key[i] == k) { + return i; + } + } + return -1; + }; + } + + public BTree(int t) { + T = t; + root = new Node(); + root.n = 0; + root.leaf = true; + } + + private Node root; + + private void split(Node x, int pos, Node y) { + Node z = new Node(); + z.leaf = y.leaf; + z.n = T - 1; + for (int j = 0; j < T - 1; j++) { + z.key[j] = y.key[j + T]; + } + if (!y.leaf) { + for (int j = 0; j < T; j++) { + z.child[j] = y.child[j + T]; + } + } + y.n = T - 1; + for (int j = x.n; j >= pos + 1; j--) { + x.child[j + 1] = x.child[j]; + } + x.child[pos + 1] = z; + + for (int j = x.n - 1; j >= pos; j--) { + x.key[j + 1] = x.key[j]; + } + x.key[pos] = y.key[T - 1]; + x.n = x.n + 1; + } + + public void insert(final int key) { + Node r = root; + if (r.n == 2 * T - 1) { + Node s = new Node(); + root = s; + s.leaf = false; + s.n = 0; + s.child[0] = r; + split(s, 0, r); + _insert(s, key); + } else { + _insert(r, key); + } + } + + final private void _insert(Node x, int k) { + + if (x.leaf) { + int i = 0; + for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) { + x.key[i + 1] = x.key[i]; + } + x.key[i + 1] = k; + x.n = x.n + 1; + } else { + int i = 0; + for (i = x.n - 1; i >= 0 && k < x.key[i]; i--) { + } + ; + i++; + Node tmp = x.child[i]; + if (tmp.n == 2 * T - 1) { + split(x, i, tmp); + if (k > x.key[i]) { + i++; + } + } + _insert(x.child[i], k); + } + + } + + public void display() { + display(root); + } + + private void display(Node x) { + assert (x == null); + for (int i = 0; i < x.n; i++) { + System.out.print(x.key[i] + " "); + } + if (!x.leaf) { + for (int i = 0; i < x.n + 1; i++) { + display(x.child[i]); + } + } + } + + public static void main(String[] args) { + BTree b = new BTree(3); + b.insert(8); + b.insert(9); + b.insert(10); + b.insert(11); + b.insert(15); + b.insert(20); + b.insert(17); + + b.display(); + } +} \ No newline at end of file diff --git a/BUBBLE SORT IN JAVA (1).docx b/BUBBLE SORT IN JAVA (1).docx new file mode 100644 index 00000000..9bdd14a1 Binary files /dev/null and b/BUBBLE SORT IN JAVA (1).docx differ diff --git a/BellmanFord.java b/BellmanFord.java new file mode 100644 index 00000000..e552da31 --- /dev/null +++ b/BellmanFord.java @@ -0,0 +1,45 @@ +import java.util.*; +public class Main { + public static void main(String[] args) { + Scanner scn = new Scanner(System.in); + int n = scn.nextInt(); + int m = scn.nextInt(); + int[][] matrix = new int[m][3]; + for (int i = 0; i + < m; i++) { + int u = scn.nextInt(); + int v = scn.nextInt(); + int w = scn.nextInt(); + matrix[i][0] = u - 1; + matrix[i][1] = v - 1; + matrix[i][2] = w; + } + int[] path = new int[n]; + Arrays.fill(path, Integer.MAX_VALUE); + path[0] = 0; + scn.close(); + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j + < m; j++) { + int u = matrix[j][0]; + int v = matrix[j][1]; + int w = matrix[j][2]; + if (path[u] == Integer.MAX_VALUE) { + continue; + } + if (path[u] + w < path[v]) { + path[v] = path[u] + w; + } + } + } + for (int i = 1; i < path.length; i++) { + if (path[i] == Integer.MAX_VALUE) + { + System.out.print( "1000000000" + " " ); + } + else { + System.out.print(path[i] + " " ); + } + } + } +} \ No newline at end of file diff --git a/BelmanFord.java b/BelmanFord.java new file mode 100644 index 00000000..657dcf7d --- /dev/null +++ b/BelmanFord.java @@ -0,0 +1,138 @@ +// A Java program for Bellman-Ford's single source shortest +// path algorithm. + +import java.io.*; +import java.lang.*; +import java.util.*; + +// A class to represent a connected, directed and weighted +// graph +class Graph { + + // A class to represent a weighted edge in graph + class Edge { + int src, dest, weight; + Edge() { src = dest = weight = 0; } + }; + + int V, E; + Edge edge[]; + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[e]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // The main function that finds shortest distances from + // src to all other vertices using Bellman-Ford + // algorithm. The function also detects negative weight + // cycle + void BellmanFord(Graph graph, int src) + { + int V = graph.V, E = graph.E; + int dist[] = new int[V]; + + // Step 1: Initialize distances from src to all + // other vertices as INFINITE + for (int i = 0; i < V; ++i) + dist[i] = Integer.MAX_VALUE; + dist[src] = 0; + + // Step 2: Relax all edges |V| - 1 times. A simple + // shortest path from src to any other vertex can + // have at-most |V| - 1 edges + for (int i = 1; i < V; ++i) { + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE + && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + + // Step 3: check for negative-weight cycles. The + // above step guarantees shortest distances if graph + // doesn't contain negative weight cycle. If we get + // a shorter path, then there is a cycle. + for (int j = 0; j < E; ++j) { + int u = graph.edge[j].src; + int v = graph.edge[j].dest; + int weight = graph.edge[j].weight; + if (dist[u] != Integer.MAX_VALUE + && dist[u] + weight < dist[v]) { + System.out.println( + "Graph contains negative weight cycle"); + return; + } + } + printArr(dist, V); + } + + // A utility function used to print the solution + void printArr(int dist[], int V) + { + System.out.println("Vertex Distance from Source"); + for (int i = 0; i < V; ++i) + System.out.println(i + "\t\t" + dist[i]); + } + + // Driver's code + public static void main(String[] args) + { + int V = 5; // Number of vertices in graph + int E = 8; // Number of edges in graph + + Graph graph = new Graph(V, E); + + // add edge 0-1 (or A-B in above figure) + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = -1; + + // add edge 0-2 (or A-C in above figure) + graph.edge[1].src = 0; + graph.edge[1].dest = 2; + graph.edge[1].weight = 4; + + // add edge 1-2 (or B-C in above figure) + graph.edge[2].src = 1; + graph.edge[2].dest = 2; + graph.edge[2].weight = 3; + + // add edge 1-3 (or B-D in above figure) + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 2; + + // add edge 1-4 (or B-E in above figure) + graph.edge[4].src = 1; + graph.edge[4].dest = 4; + graph.edge[4].weight = 2; + + // add edge 3-2 (or D-C in above figure) + graph.edge[5].src = 3; + graph.edge[5].dest = 2; + graph.edge[5].weight = 5; + + // add edge 3-1 (or D-B in above figure) + graph.edge[6].src = 3; + graph.edge[6].dest = 1; + graph.edge[6].weight = 1; + + // add edge 4-3 (or E-D in above figure) + graph.edge[7].src = 4; + graph.edge[7].dest = 3; + graph.edge[7].weight = -3; + + // Function call + graph.BellmanFord(graph, 0); + } +} +// Contributed by Aakash Hasija diff --git a/Binary Search.java b/Binary Search.java new file mode 100644 index 00000000..70f62dd5 --- /dev/null +++ b/Binary Search.java @@ -0,0 +1,24 @@ + +public class Solution { + + public static int binarySearch(int[] arr, int x) { + int start = 0; + int end = arr.length - 1; + + while (start <= end){ + int mid = (start + end)/2; + if (x == arr[mid]){ + return mid; + } else if (x < mid){ + end = mid - 1; + } if (x > mid){ + end = mid + 1; + } + + + } + return -1; + + } + +} diff --git a/Binary.java b/Binary.java new file mode 100644 index 00000000..c4f2e115 --- /dev/null +++ b/Binary.java @@ -0,0 +1,41 @@ +import java.util.Scanner; +import java.time.Duration; +import java.time.Instant; + + +public class Binary { + public static int binary_search(int[]A,int target){ + int lo=0; + int hi=A.length-1; + + while(lo<=hi) +{ + int mid=lo+(hi-lo)/2; + if(A[mid]==target) + return mid; + else if(A[mid] +using namespace std; +int binarySearch(int arr[], int l, int r, int x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + return binarySearch(arr, mid + 1, r, x); + } + return -1; +} + +int main(void) +{ + int arr[] = { 2, 3, 4, 10, 40 }; + int x = 10; + int n = sizeof(arr) / sizeof(arr[0]); + int result = binarySearch(arr, 0, n - 1, x); + (result == -1) + ? cout << "Element is not present in array" + : cout << "Element is present at index " << result; + return 0; +} diff --git a/BinarySearch.java b/BinarySearch.java index eeffdf12..62c47ed7 100644 --- a/BinarySearch.java +++ b/BinarySearch.java @@ -1,65 +1,34 @@ -import java.util.Scanner; -/* - * Java Program to implement binary search without using recursion - */ public class BinarySearch { public static void main(String[] args) { - - Scanner commandReader = new Scanner(System.in); - System.out.println("Welcome to Java Program to perform - binary search on int array"); - System.out.println("Enter total number of elements : "); - int length = commandReader.nextInt(); - int[] input = new int[length]; - - System.out.printf("Enter %d integers %n", length); - for (int i = 0; i < length; i++) { - input[i] = commandReader.nextInt(); - } - - System.out.println("Please enter number to be searched in array - (sorted order)"); - int key = commandReader.nextInt(); - - int index = performBinarySearch(input, key); - - if (index == -1) { - System.out.printf("Sorry, %d is not found in array %n", key); - } else { - System.out.printf("%d is found in array at index %d %n", key, - index); - } - - commandReader.close(); - + int[] arr = { -18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89 }; + int target = 22; + int ans = binarySearch(arr, target); + System.out.println(ans); } - /** - * Java method to perform binary search. It accept an integer array and a - * number and return the index of number in the array. If number doesn't - * exists in array then it return -1 - * - * @param input - * @param number - * @return index of given number in array or -1 if not found - */ - public static int performBinarySearch(int[] input, int number) { - int low = 0; - int high = input.length - 1; - - while (high >= low) { - int middle = (low + high) / 2; - if (input[middle] == number) { - return middle; - } else if (input[middle] < number) { - low = middle + 1; - } else if (input[middle] > number) { - high = middle - 1; + // return the index + // return -1 if it does not exist + static int binarySearch(int[] arr, int target) { + int start = 0; + int end = arr.length - 1; + + while (start <= end) { + // find the middle element + // int mid = (start + end) / 2; // might be possible that (start + end) exceeds + // the range of int in java + int mid = start + (end - start) / 2; + + if (target < arr[mid]) { + end = mid - 1; + } else if (target > arr[mid]) { + start = mid + 1; + } else { + // ans found + return mid; } } return -1; } - -} +} \ No newline at end of file diff --git a/BinaryTree.java b/BinaryTree.java new file mode 100644 index 00000000..db71cbb0 --- /dev/null +++ b/BinaryTree.java @@ -0,0 +1,66 @@ +public class BinaryTree { + + //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 BinaryTree(){ + root = null; + } + + //findHeight() will determine the maximum height of the binary tree + public int findHeight(Node temp){ + //Check whether tree is empty + if(root == null) { + System.out.println("Tree is empty"); + return 0; + } + else { + int leftHeight = 0, rightHeight = 0; + + //Calculate the height of left subtree + if(temp.left != null) + leftHeight = findHeight(temp.left); + + //Calculate the height of right subtree + if(temp.right != null) + rightHeight = findHeight(temp.right); + + //Compare height of left subtree and right subtree + //and store maximum of two in variable max + int max = (leftHeight > rightHeight) ? leftHeight : rightHeight; + + //Calculate the total height of tree by adding height of root + return (max + 1); + } + } + + public static void main(String[] args) { + + BinaryTree bt = new BinaryTree(); + //Add nodes to the binary tree + bt.root = new Node(1); + bt.root.left = new Node(2); + bt.root.right = new Node(3); + bt.root.left.left = new Node(4); + bt.root.right.left = new Node(5); + bt.root.right.right = new Node(6); + bt.root.right.right.right= new Node(7); + bt.root.right.right.right.right = new Node(8); + + //Display the maximum height of the given binary tree + System.out.println("Maximum height of given binary tree: " + bt.findHeight(bt.root)); + } +} \ No newline at end of file diff --git a/BinaryTreeCode.java b/BinaryTreeCode.java new file mode 100644 index 00000000..ef407440 --- /dev/null +++ b/BinaryTreeCode.java @@ -0,0 +1,59 @@ +class Node { + + int data; + Node left, right; + + Node(int d) { + data = d; + left = right = null; + } +} + +// Calculate height +class Height { + int height = 0; +} + +class BinaryTreeCode { + + Node root; + + // Check height balance + boolean checkHeightBalance(Node root, Height height) { + + // Check for emptiness + if (root == null) { + height.height = 0; + return true; + } + + Height leftHeighteight = new Height(), rightHeighteight = new Height(); + boolean l = checkHeightBalance(root.left, leftHeighteight); + boolean r = checkHeightBalance(root.right, rightHeighteight); + int leftHeight = leftHeighteight.height, rightHeight = rightHeighteight.height; + + height.height = (leftHeight > rightHeight ? leftHeight : rightHeight) + 1; + + if ((leftHeight - rightHeight >= 2) || (rightHeight - leftHeight >= 2)) + return false; + + else + return l && r; + } + + public static void main(String args[]) { + Height height = new Height(); + + 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); + tree.root.left.right = new Node(5); + + if (tree.checkHeightBalance(tree.root, height)) + System.out.println("The tree is balanced"); + else + System.out.println("The tree is not balanced"); + } +} \ No newline at end of file diff --git a/Binary_Search.java b/Binary_Search.java new file mode 100644 index 00000000..147c9e97 --- /dev/null +++ b/Binary_Search.java @@ -0,0 +1,35 @@ +import java.util.*; +class Main{ + public static void main(String args[]){ + int numArray[] = {5,10,15,20,25,30,35}; + System.out.println("The input array: " + Arrays.toString(numArray)); + + int key = 20; + System.out.println("\nKey to be searched=" + key); + + int first = 0; + + int last=numArray.length-1; + + int mid = (first + last)/2; + + while( first <= last ){ + + if ( numArray[mid] < key ){ + first = mid + 1; + }else if ( numArray[mid] == key ){ + + System.out.println("Element is found at index: " + mid); + break; + }else{ + + last = mid - 1; + } + mid = (first + last)/2; + } + + if ( first > last ){ + System.out.println("Element is not found!"); + } + } +} diff --git a/Brainfuck.txt b/Brainfuck.txt new file mode 100644 index 00000000..3df2cda8 --- /dev/null +++ b/Brainfuck.txt @@ -0,0 +1,121 @@ +import java.util.*; + +class BrainFuck +{ + private static Scanner ob = new Scanner(System.in); + private static int ptr; // Data pointer + + // Max memory limit. It is the highest number which + // can be represented by an unsigned 16-bit binary + // number. Many computer programming environments + // beside brainfuck may have predefined + // constant values representing 65535. + private static int length = 65535; + + // Array of byte type simulating memory of max + // 65535 bits from 0 to 65534. + private static byte memory[] = new byte[length]; + + // Interpreter function which accepts the code + // a string parameter + private static void interpret(String s) + { + int c = 0; + + // Parsing through each character of the code + for (int i = 0; i < s.length(); i++) + { + // BrainFuck is a tiny language with only + // eight instructions. In this loop we check + // and execute all those eight instructions + + + // > moves the pointer to the right + if (s.charAt(i) == '>') + { + if (ptr == length - 1)//If memory is full + ptr = 0;//pointer is returned to zero + else + ptr ++; + } + + // < moves the pointer to the left + else if (s.charAt(i) == '<') + { + if (ptr == 0) // If the pointer reaches zero + + // pointer is returned to rightmost memory + // position + ptr = length - 1; + else + ptr --; + } + + // + increments the value of the memory + // cell under the pointer + else if (s.charAt(i) == '+') + memory[ptr] ++; + + // - decrements the value of the memory cell + // under the pointer + else if (s.charAt(i) == '-') + memory[ptr] --; + + // . outputs the character signified by the + // cell at the pointer + else if (s.charAt(i) == '.') + System.out.print((char)(memory[ptr])); + + // , inputs a character and store it in the + // cell at the pointer + else if (s.charAt(i) == ',') + memory[ptr] = (byte)(ob.next().charAt(0)); + + // [ jumps past the matching ] if the cell + // under the pointer is 0 + else if (s.charAt(i) == '[') + { + if (memory[ptr] == 0) + { + i++; + while (c > 0 || s.charAt(i) != ']') + { + if (s.charAt(i) == '[') + c++; + else if (s.charAt(i) == ']') + c--; + i ++; + } + } + } + + // ] jumps back to the matching [ if the + // cell under the pointer is nonzero + else if (s.charAt(i) == ']') + { + if (memory[ptr] != 0) + { + i --; + while (c > 0 || s.charAt(i) != '[') + { + if (s.charAt(i) == ']') + c ++; + else if (s.charAt(i) == '[') + c --; + i --; + } + i --; + } + } + } + } + + // Driver code + public static void main(String args[]) + { + System.out.println("Enter the code:"); + String code = ob.nextLine(); + System.out.println("Output:"); + interpret(code); + } +} diff --git a/BreadthFirstSearch.java b/BreadthFirstSearch.java new file mode 100644 index 00000000..2f155cff --- /dev/null +++ b/BreadthFirstSearch.java @@ -0,0 +1,67 @@ +import java.io.*; +import java.util.*; + +class Graph +{ + private int V; + private LinkedList adj[]; + + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + + s = queue.poll(); + System.out.print(s+" "); + + Iterator i = adj[s].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + { + visited[n] = true; + queue.add(n); + } + } + } + } + + + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +} \ No newline at end of file diff --git a/BubbleSort.java b/BubbleSort.java index ae1ceaaa..44c4ab61 100644 --- a/BubbleSort.java +++ b/BubbleSort.java @@ -1,35 +1,44 @@ -public class BubbleSortExample { - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } -} \ No newline at end of file +import java.util.Scanner; + +public class BubbleSort { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + int[] a = new int[5]; + System.out.println("Enter the elements of the array: "); + for (int i = 0; i a[j+1]){ + int temp = a[j+1]; + a[j+1] = a[j]; + a[j] = temp; + flag++; + } + } + if (flag == 0){ + break; + } + } + } +} diff --git a/BubbleSortAlgorithmEx.java b/BubbleSortAlgorithmEx.java new file mode 100644 index 00000000..d94179de --- /dev/null +++ b/BubbleSortAlgorithmEx.java @@ -0,0 +1,32 @@ +public class BubbleSortAlgorithmEx { + public static void main(String[] args) { + int[] array ={6,10,1,8,7,5,2}; + + System.out.println("Bubble Sort Algorithm"); + System.out.println("----------------------"); + System.out.println("All elements in the array : "); + for (int j : array) { + System.out.print(j + " "); + } + System.out.println(); + bubbleSort(array); + + System.out.println("Sorted Array : "); + for (int j : array) { + System.out.print(j + " "); + } + } + static void bubbleSort(int[] array) { + int n = array.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(array[j-1] > array[j]){ + temp = array[j-1]; + array[j-1] = array[j]; + array[j] = temp; + } + } + } + } +} \ No newline at end of file diff --git a/BubbleSortExample.java b/BubbleSortExample.java new file mode 100644 index 00000000..c716ce04 --- /dev/null +++ b/BubbleSortExample.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/BubbleSt.java b/BubbleSt.java new file mode 100644 index 00000000..463a05f0 --- /dev/null +++ b/BubbleSt.java @@ -0,0 +1,35 @@ +public class BubbleSt { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/Bubblesort.cpp b/Bubblesort.cpp new file mode 100644 index 00000000..e75cc9b8 --- /dev/null +++ b/Bubblesort.cpp @@ -0,0 +1,45 @@ +#include +void swap(int *p1, int *p2) +{ +int temp = *p1; +*p1 = *p2; +*p2 = temp; +} +// This is an optimised code for the bubble sort +void bSort(int arrnumbers[], int n) +{ +int i, j; +bool check; +for (i = 0; i < n-1; i++) +{ +check = false; +for (j = 0; j < n-i-1; j++) +{ +if (arrnumbers[j] > arrnumbers[j+1]) +{ +swap(&arrnumbers[j], &arrnumbers[j+1]); +check = true; +} +} +// We are breaking from the loop in case two elements were not swapped by inner loop. +if (check == false) +break; +} +} +//This function is to print the array sequence as final output after sorting +void print(int arrnumbers[], int sizeofarray) +{ +int i; +for (i=0; i < sizeofarray; i++) +printf("%d ", arrnumbers[i]); +} +// This the main program from where the execution will start +int main() +{ +int arrnumbers[] = {5, 6, 1, 0, 2, 9}; +int n = sizeof(arrnumbers)/sizeof(arrnumbers[0]); +bSort(arrnumbers, n); +printf("Sorted array: \n"); +print(arrnumbers, n); +return 0; +} diff --git a/Bucketsort.java b/Bucketsort.java new file mode 100644 index 00000000..8742f346 --- /dev/null +++ b/Bucketsort.java @@ -0,0 +1,60 @@ +// Java program to sort an array +// using bucket sort +import java.util.*; +import java.util.Collections; + +class GFG { + + // Function to sort arr[] of size n + // using bucket sort + static void bucketSort(float arr[], int n) + { + if (n <= 0) + return; + + // 1) Create n empty buckets + @SuppressWarnings("unchecked") + Vector[] buckets = new Vector[n]; + + for (int i = 0; i < n; i++) { + buckets[i] = new Vector(); + } + + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) { + float idx = arr[i] * n; + buckets[(int)idx].add(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) { + Collections.sort(buckets[i]); + } + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < buckets[i].size(); j++) { + arr[index++] = buckets[i].get(j); + } + } + } + + // Driver code + public static void main(String args[]) + { + float arr[] = { (float)0.897, (float)0.565, + (float)0.656, (float)0.1234, + (float)0.665, (float)0.3434 }; + + int n = arr.length; + bucketSort(arr, n); + + System.out.println("Sorted array is "); + for (float el : arr) { + System.out.print(el + " "); + } + } +} + +// This code is contributed by Himangshu Shekhar Jha diff --git a/C Calculator b/C Calculator new file mode 100644 index 00000000..54cd1968 --- /dev/null +++ b/C Calculator @@ -0,0 +1,39 @@ +#include +#include +#include +#include + + +int main(int argc, char *argv[]) +{ + float valueOne; + float valueTwo; + char operator; + float answer; + + printf("Enter calculation:\n"); + scanf("%f %c %f", &valueOne, &operator, & valueTwo); + + switch(operator) + { + case '/': answer = valueOne/valueTwo; + break; + case '*': answer = valueOne*valueTwo; + break; + case '+': answer = valueOne+valueTwo; + break; + case '-': answer = valueOne-valueTwo; + break; + case '^': answer = pow(valueOne,valueTwo); + break; + case ' ': answer = sqrt(valueTwo); + break; + default: goto fail; + } + printf("%.9g%c%.9g = %.6g\n\n",valueOne,operator, valueTwo, answer); + goto exit; + fail: + printf("Fail.\n"); + exit: + return 0; +} diff --git a/C to F Python.py b/C to F Python.py new file mode 100644 index 00000000..e7897f9a --- /dev/null +++ b/C to F Python.py @@ -0,0 +1,8 @@ +# Python Program to convert temperature in celsius to fahrenheit + +# change this value for a different result +celsius = 37.5 + +# calculate fahrenheit +fahrenheit = (celsius * 1.8) + 32 +print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) \ No newline at end of file diff --git a/C++ program to implement + operator overloading to add two timestamps.cpp b/C++ program to implement + operator overloading to add two timestamps.cpp new file mode 100644 index 00000000..bc29dd3f --- /dev/null +++ b/C++ program to implement + operator overloading to add two timestamps.cpp @@ -0,0 +1,70 @@ +// C++ program to implement + operator +// overloading to add two timestamps + +#include +using namespace std; + +// Time class template +class Time { +private: + int HR, MIN, SEC; + + // Defining functions +public: + // Functions to set the time + // in the Time class template + void setTime(int x, int y, int z) + { + HR = x; + MIN = y; + SEC = z; + } + + // Function to print the time + // in HH:MM:SS format + void showTime() + { + cout << endl + << HR << ":" << MIN << ":" << SEC; + } + + // Function to normalize the resultant + // time in standard form + void normalize() + { + MIN = MIN + SEC / 60; + SEC = SEC % 60; + HR = HR + MIN / 60; + MIN = MIN % 60; + } + + // + Operator overloading + // to add the time t1 and t2 + Time operator+(Time t) + { + Time temp; + temp.SEC = SEC + t.SEC; + temp.MIN = MIN + t.MIN; + temp.HR = HR + t.HR; + temp.normalize(); + return (temp); + } +}; + +// Driver code +int main() +{ + Time t1, t2, t3; + t1.setTime(5, 50, 30); + t2.setTime(7, 20, 34); + + // Operator overloading + t3 = t1 + t2; + + // Printing results + t1.showTime(); + t2.showTime(); + t3.showTime(); + + return 0; +} diff --git a/C++34.cpp b/C++34.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/C++34.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/C++45.cpp b/C++45.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/C++45.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/Calculator.java b/Calculator.java new file mode 100644 index 00000000..1b6faadb --- /dev/null +++ b/Calculator.java @@ -0,0 +1,54 @@ +import java.util.Scanner; + +public class JavaExample { + + public static void main(String[] args) { + + double num1, num2; + Scanner scanner = new Scanner(System.in); + System.out.print("Enter first number:"); + + /* We are using data type double so that user + * can enter integer as well as floating point + * value + */ + num1 = scanner.nextDouble(); + System.out.print("Enter second number:"); + num2 = scanner.nextDouble(); + + System.out.print("Enter an operator (+, -, *, /): "); + char operator = scanner.next().charAt(0); + + scanner.close(); + double output; + + switch(operator) + { + case '+': + output = num1 + num2; + break; + + case '-': + output = num1 - num2; + break; + + case '*': + output = num1 * num2; + break; + + case '/': + output = num1 / num2; + break; + + /* If user enters any other operator or char apart from + * +, -, * and /, then display an error message to user + * + */ + default: + System.out.printf("You have entered wrong operator"); + return; + } + + System.out.println(num1+" "+operator+" "+num2+": "+output); + } +} diff --git a/Cellpadding And Cellspacing Attributes.txt b/Cellpadding And Cellspacing Attributes.txt new file mode 100644 index 00000000..ccbe9a7b --- /dev/null +++ b/Cellpadding And Cellspacing Attributes.txt @@ -0,0 +1,21 @@ + + +HTML TABLE + + + + + + + + + + + + + +
Name +Age +
ANKUSH25
Raman35
+ + \ No newline at end of file diff --git a/CocktailSort.java b/CocktailSort.java new file mode 100644 index 00000000..85463e9d --- /dev/null +++ b/CocktailSort.java @@ -0,0 +1,69 @@ + +public class CocktailSort +{ + void cocktailSort(int a[]) + { + boolean swapped = true; + int start = 0; + int end = a.length; + + while (swapped == true) + { + + swapped = false; + + for (int i = start; i < end - 1; ++i) + { + if (a[i] > a[i + 1]) { + int temp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = temp; + swapped = true; + } + } + + + if (swapped == false) + break; + + + swapped = false; + + + end = end - 1; + + + for (int i = end - 1; i >= start; i--) + { + if (a[i] > a[i + 1]) + { + int temp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = temp; + swapped = true; + } + } + + + start = start + 1; + } + } + + + void printArray(int a[]) + { + int n = a.length; + for (int i = 0; i < n; i++) + System.out.print(a[i] + " "); + System.out.println(); + } + + public static void main(String[] args) + { + CocktailSort ob = new CocktailSort(); + int a[] = { 5, 1, 4, 2, 8, 0, 2 }; + ob.cocktailSort(a); + System.out.println("Sorted array"); + ob.printArray(a); + } +} diff --git a/Code.txt b/Code.txt new file mode 100644 index 00000000..a61a2782 --- /dev/null +++ b/Code.txt @@ -0,0 +1,125 @@ +Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. + +A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. + +For example, "ace" is a subsequence of "abcde". +A common subsequence of two strings is a subsequence that is common to both strings. + + + +Example 1: + +Input: text1 = "abcde", text2 = "ace" +Output: 3 +Explanation: The longest common subsequence is "ace" and its length is 3. +Example 2: + +Input: text1 = "abc", text2 = "abc" +Output: 3 +Explanation: The longest common subsequence is "abc" and its length is 3. +Example 3: + +Input: text1 = "abc", text2 = "def" +Output: 0 +Explanation: There is no such common subsequence, so the result is 0. + + +Constraints: + +1 <= text1.length, text2.length <= 1000 +text1 and text2 consist of only lowercase English characters. + + +Solution 1 Top Down + +class Solution { +public: + int f(int i,int j,string &si,string &sj,vector> &dp) + { + if(i<0||j<0) + { + return 0; + } + else if(si[i]==sj[j]) + { + return (1 + f(i-1,j-1,si,sj,dp)); + } + else if(dp[i][j]!=-1) + { + return dp[i][j]; + } + else + { + return dp[i][j] = max(f(i-1,j,si,sj,dp),f(i,j-1,si,sj,dp)); + } + } +public: + int longestCommonSubsequence(string text1, string text2) { + int l1 = text1.length(); + int l2 = text2.length(); + vector> dp(l1,vector(l2,-1)); + return f(l1-1,l2-1,text1,text2,dp); + } +}; + + + + +Solution 2 Bottom Up (with shifted coordinates make changes in i and j for the string only,not int the dp and make size of dp l1+1*l2+1) +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int l1=text1.length(); + int l2=text2.length(); + vector> dp(l1+1,vector(l2+1,0)); + for(int i=1;i<=l1;i++) + { + for(int j=1;j<=l2;j++) + { + if(text1[i-1]==text2[j-1]) + { + dp[i][j] = 1 + dp[i-1][j-1]; + } + else + { + dp[i][j] = max(dp[i-1][j],dp[i][j-1]); + } + } + } + return dp[l1][l2]; + } +}; + + + +Solution 3 : Space optimisation + +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int l1=text1.length(); + int l2=text2.length(); + vector curr(l2+1,0); + vector prev(l2+1,0); + for(int i=1;i<=l1;i++) + { + for(int j=1;j<=l2;j++) + { + if(text1[i-1]==text2[j-1]) + { + curr[j] = 1 + prev[j-1]; + } + else + { + curr[j] = max(prev[j],curr[j-1]); + } + } + prev=curr; + } + return prev[l2]; + } +}; + + + + diff --git a/CombSortInJave.java b/CombSortInJave.java new file mode 100644 index 00000000..4f0623a1 --- /dev/null +++ b/CombSortInJave.java @@ -0,0 +1,67 @@ + +class CombSort +{ + // To find gap between elements + int getNextGap(int gap) + { + // Shrink gap by Shrink factor + gap = (gap*10)/13; + if (gap < 1) + return 1; + return gap; + } + + // Function to sort arr[] using Comb Sort + void sort(int arr[]) + { + int n = arr.length; + + // initialize gap + int gap = n; + + // Initialize swapped as true to make sure that + // loop runs + boolean swapped = true; + + // Keep running while gap is more than 1 and last + // iteration caused a swap + while (gap != 1 || swapped == true) + { + // Find next gap + gap = getNextGap(gap); + + // Initialize swapped as false so that we can + // check if swap happened or not + swapped = false; + + // Compare all elements with current gap + for (int i=0; i arr[i+gap]) + { + // Swap arr[i] and arr[i+gap] + int temp = arr[i]; + arr[i] = arr[i+gap]; + arr[i+gap] = temp; + + // Set swapped + swapped = true; + } + } + } + } + + // Driver method + public static void main(String args[]) + { + CombSort ob = new CombSort(); + int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; + ob.sort(arr); + + System.out.println("sorted array"); + for (int i=0; i arr[i+gap]) + { + // Swap arr[i] and arr[i+gap] + int temp = arr[i]; + arr[i] = arr[i+gap]; + arr[i+gap] = temp; + + // Set swapped + swapped = true; + } + } + } + } + + // Driver method + public static void main(String args[]) + { + CombSort ob = new CombSort(); + int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; + ob.sort(arr); + + System.out.println("sorted array"); + for (int i=0; i> Vectors = new Vector<>(); + Vectors = compress.getVectors(matrix, img.getHeight(), img.getWidth(), VectorHeight, VectorWidth); + + Vector> QuantizeVector = new Vector<>(); + compress.Split(codeBlockSize, Vectors, QuantizeVector); + + Vector NumberOfCodeBlocks = compress.NearFromCodeBlock(Vectors, QuantizeVector); + + FileWriter myWriter = new FileWriter("DataInput.txt"); + myWriter.write("VectorWidth is :" + VectorWidth + "\n"); + myWriter.write("VectorHegiht is :" + VectorHeight + "\n"); + myWriter.write("codeBlockSize is :" + codeBlockSize + "\n"); + myWriter.write("hegihtimg is :" + img.getHeight() + "\n"); + myWriter.write("Widthimg is :" + img.getWidth() + "\n"); + + myWriter.close(); + + FileOutputStream fileOut = new FileOutputStream("NumberOfCodeBlocks.txt"); + ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); + + objectOut.writeObject(NumberOfCodeBlocks); + objectOut.close(); + + FileOutputStream fileOut2 = new FileOutputStream("QuantizedCode.txt"); + ObjectOutputStream objectOut2 = new ObjectOutputStream(fileOut2); + + objectOut2.writeObject(QuantizeVector); + objectOut2.close(); + + input.close(); + } + + public Vector> getVectors(int[][] img, int hegiht, int width, int VectorHeight, int VectorWidth) { + Vector> tempVectors = new Vector<>(); + for (int i = 0; i < hegiht; i += VectorHeight) { + for (int j = 0; j < width; j += VectorWidth) { + tempVectors.add(new Vector<>()); + for (int k = i; k < i + VectorHeight; k++) { + for (int l = j; l < j + VectorWidth; l++) { + if (k < hegiht && l < width) + tempVectors.lastElement().add(img[k][l]); + } + } + } + } + return tempVectors; + } + + private Vector CalculateAverage(Vector> Vectors) { + int[] SumElements = new int[Vectors.get(0).size()]; + for (Vector vector : Vectors) + for (int i = 0; i < vector.size(); i++) + SumElements[i] += vector.get(i); + Vector AvgVector = new Vector<>(); + for (int i = 0; i < SumElements.length; i++) + AvgVector.add(SumElements[i] / Vectors.size()); + return AvgVector; + } + + private void Split(int CodeBook, Vector> Vectors, Vector> Quantized) { + if (Vectors.size() == 0) + return; + if (CodeBook == 1) { + Quantized.add(CalculateAverage(Vectors)); + return; + } + Vector> leftVectors = new Vector<>(); + Vector> rightVectors = new Vector<>(); + Vector AvgVector = CalculateAverage(Vectors); + for (Vector vec : Vectors) { + int right = NearstFrom(vec, AvgVector, 1); + int left = NearstFrom(vec, AvgVector, -1); + if (right >= left) + leftVectors.add(vec); + else + rightVectors.add(vec); + } + Split(CodeBook / 2, leftVectors, Quantized); + Split(CodeBook / 2, rightVectors, Quantized); + } + + private int NearstFrom(Vector vec, Vector Qun, int Spliting) { + int distance = 0; + for (int i = 0; i < vec.size(); i++) + distance += Math.pow(vec.get(i) - Qun.get(i) + Spliting, 2); + return distance; + } + + private Vector NearFromCodeBlock(Vector> Vectors, Vector> Quantized) { + Vector NumberofCodeBlock = new Vector<>(); + for (Vector vector : Vectors) { + int tempDestance = NearstFrom(vector, Quantized.get(0), 0); + int NearFrom = 0; + for (int i = 1; i < Quantized.size(); i++) { + int tempDestance2 = NearstFrom(vector, Quantized.get(i), 0); + if (tempDestance2 < tempDestance) { + tempDestance = tempDestance2; + NearFrom = i; + } + } + NumberofCodeBlock.add(NearFrom); + } + return NumberofCodeBlock; + } +} \ No newline at end of file diff --git a/ConversionBinary.java b/ConversionBinary.java new file mode 100644 index 00000000..fa1bcd63 --- /dev/null +++ b/ConversionBinary.java @@ -0,0 +1,29 @@ +import java.util.Scanner; +public class ConversionBinary { + + public static void main(String args[]) + { + int dec_num, quot, i=1, j; + int bin_num[] = new int[100]; + Scanner scan = new Scanner(System.in); + + System.out.print("Input a Decimal Number : "); + dec_num = scan.nextInt(); + + quot = dec_num; + + while(quot != 0) + { + bin_num[i++] = quot%2; + quot = quot/2; + } + + System.out.print("Binary number is: "); + for(j=i-1; j>0; j--) + { + System.out.print(bin_num[j]); + } + System.out.print("\n"); + } +} + diff --git a/Count the number of words in a string using HashMap.java b/Count the number of words in a string using HashMap.java new file mode 100644 index 00000000..8097cd78 --- /dev/null +++ b/Count the number of words in a string using HashMap.java @@ -0,0 +1,23 @@ +import java.util.HashMap; + +public class FinalCountWords { + + public static void main(String[] args) { + // TODO Auto-generated method stub + String str = "You are doing this Code"; + String[] split = str.split(" "); + + HashMap map = new HashMap(); + for (int i=0; i max) + max = array[i]; + } + int[] count = new int[max + 1]; + + // Initialize count array with all zeros + for (int i = 0; i < max; ++i) { + count[i] = 0; + } + + // Store the count of each element + for (int i = 0; i < size; i++) { + count[array[i]]++; + } + + // Store the cummulative count of each array + for (int i = 1; i <= max; i++) { + count[i] += count[i - 1]; + } + + // Find the index of each element of the original array in count array, and + // place the elements in output array + for (int i = size - 1; i >= 0; i--) { + output[count[array[i]] - 1] = array[i]; + count[array[i]]--; + } + + // Copy the sorted elements into original array + for (int i = 0; i < size; i++) { + array[i] = output[i]; + } + } + + // Driver code for the above code + public static void main(String args[]) { + int[] data = { 4, 2, 2, 8, 3, 3, 1 }; + int size = data.length; + CountingSort cs = new CountingSort(); + cs.countSort(data, size); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} diff --git a/Counting_Sort.java b/Counting_Sort.java new file mode 100644 index 00000000..a4a6b4ae --- /dev/null +++ b/Counting_Sort.java @@ -0,0 +1,45 @@ + +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + char output[] = new char[n]; + + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + // store count of each character + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + // Build the output character array + for (int i = 0; i < n; ++i) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + // Driver method + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} + diff --git a/CreateList.java b/CreateList.java new file mode 100644 index 00000000..1e2c686a --- /dev/null +++ b/CreateList.java @@ -0,0 +1,60 @@ +public class CreateList { + + public class Node{ + int data; + Node next; + public Node(int data) { + this.data = data; + } + } + + + public Node head = null; + public Node tail = null; + + public void add(int data){ + + Node newNode = new Node(data); + + if(head == null) { + + head = newNode; + tail = newNode; + newNode.next = head; + } + else { + + tail.next = newNode; + tail = newNode; + tail.next = head; + } + } + + + public void display() { + Node current = head; + if(head == null) { + System.out.println("List is empty"); + } + else { + System.out.println("Nodes of the circular linked list: "); + do{ + + System.out.print(" "+ current.data); + current = current.next; + }while(current != head); + System.out.println(); + } + } + + public static void main(String[] args) { + CreateList cl = new CreateList(); + + cl.add(1); + cl.add(2); + cl.add(3); + cl.add(4); + + cl.display(); + } +} diff --git a/Create_pyramid_pattern.cpp b/Create_pyramid_pattern.cpp new file mode 100644 index 00000000..398ee2c2 --- /dev/null +++ b/Create_pyramid_pattern.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +int main() +{ + int rows; + + cout << "Enter number of rows: "; + cin >> rows; + + for(int i = 1; i <= rows; ++i) + { + for(int j = 1; j <= i; ++j) + { + cout << "* "; + } + cout << "\n"; + } + return 0; +} \ No newline at end of file diff --git a/CrossProduct.cpp b/CrossProduct.cpp new file mode 100644 index 00000000..76fe9d41 --- /dev/null +++ b/CrossProduct.cpp @@ -0,0 +1,66 @@ +#include +using namespace std; +template + +class vector +{ +public: + T *arr; + int size; + vector(int m) + { + size = m; + arr = new T[size]; + } + T crossproduct(vector &v /*,vector &v3*/) + { + int a; + for (int i = 0; i < size; i++) + { + + + a= ((arr[i + 1] * v.arr[i + 2]) - (arr[i + 2] * v.arr[i + 1])); + + a = ((arr[i + 2] * v.arr[i + 0]) - (arr[i + 0] * v.arr[i + 0])); + + a= ((arr[i + 0] * v.arr[i + 1]) - (arr[i + 1] * v.arr[i + 0])); + + } + return a; + } + void display() + { + int d[size]= crossproduct(); + return d; + } +}; + +int main() +{ + vector v1(3), v2(3); + + v1.arr[0] = 1; + v1.arr[1] = 2; + v1.arr[2] = 3; + + v2.arr[0] = 3; + v2.arr[1] = 2; + v2.arr[2] = 1; + + v1.crossproduct(v2); + v1.display(); + + //int d[size] = v1.crossproduct(v2); + //for(int j=0;j<3;j++) + //{ + // + // cout<> adj; + + public Graph(int V) + { + this.V = V; + adj = new ArrayList<>(V); + + for (int i = 0; i < V; i++) + adj.add(new LinkedList<>()); + } + + // This function is a variation of DFSUtil() in + // https://www.geeksforgeeks.org/archives/18212 + private boolean isCyclicUtil(int i, boolean[] visited, + boolean[] recStack) + { + + // Mark the current node as visited and + // part of recursion stack + if (recStack[i]) + return true; + + if (visited[i]) + return false; + + visited[i] = true; + + recStack[i] = true; + List children = adj.get(i); + + for (Integer c: children) + if (isCyclicUtil(c, visited, recStack)) + return true; + + recStack[i] = false; + + return false; + } + + private void addEdge(int source, int dest) { + adj.get(source).add(dest); + } + + // Returns true if the graph contains a + // cycle, else false. + // This function is a variation of DFS() in + // https://www.geeksforgeeks.org/archives/18212 + private boolean isCyclic() + { + + // Mark all the vertices as not visited and + // not part of recursion stack + boolean[] visited = new boolean[V]; + boolean[] recStack = new boolean[V]; + + + // Call the recursive helper function to + // detect cycle in different DFS trees + for (int i = 0; i < V; i++) + if (isCyclicUtil(i, visited, recStack)) + return true; + + return false; + } + + // Driver code + public static void main(String[] args) + { + Graph graph = new Graph(4); + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 2); + graph.addEdge(2, 0); + graph.addEdge(2, 3); + graph.addEdge(3, 3); + + if(graph.isCyclic()) + System.out.println("Graph contains cycle"); + else + System.out.println("Graph doesn't " + + "contain cycle"); + } +} + +// This code is contributed by Sagar Shah. diff --git a/Cycle Sort b/Cycle Sort new file mode 100644 index 00000000..f665db9a --- /dev/null +++ b/Cycle Sort @@ -0,0 +1,52 @@ +// java program to check implement cycle sort +import java.util.*; +public class MissingNumber { + public static void main(String[] args) + { + int[] arr = { 3, 2, 4, 5, 1 }; + int n = arr.length; + System.out.println("Before sort :"); + System.out.println(Arrays.toString(arr)); + CycleSort(arr, n); + + } + + static void CycleSort(int[] arr, int n) + { + int i = 0; + while (i < n) { + // as array is of 1 based indexing so the + // correct position or index number of each + // element is element-1 i.e. 1 will be at 0th + // index similarly 2 correct index will 1 so + // on... + int correctpos = arr[i] - 1; + if (arr[i] < n && arr[i] != arr[correctpos]) { + // if array element should be lesser than + // size and array element should not be at + // its correct position then only swap with + // its correct position or index value + swap(arr, i, correctpos); + } + else { + // if element is at its correct position + // just increment i and check for remaining + // array elements + i++; + } + } + System.out.println("After sort : "); + System.out.print(Arrays.toString(arr)); + + + } + + static void swap(int[] arr, int i, int correctpos) + { + // swap elements with their correct indexes + int temp = arr[i]; + arr[i] = arr[correctpos]; + arr[correctpos] = temp; + } +} +// this code is contributed by devendra solunke diff --git a/DEINWHIL.CPP b/DEINWHIL.CPP new file mode 100644 index 00000000..6b61d980 --- /dev/null +++ b/DEINWHIL.CPP @@ -0,0 +1,31 @@ +#include +#include +main() +{ +int i=4,j; +clrscr(); +while(i>=1) +{ +j=1; +while(j<=i) +{ +cout<<"\2"; +j++; +} +cout<<"\n"; +i--; +} +i=2; +while(i<=4) +{ +j=1; +while(j<=i) +{ +cout<<"\2"; +j++; +} +cout<<"\n"; +i++; +} +getch(); +} diff --git a/DNFSort.java b/DNFSort.java new file mode 100644 index 00000000..daaacc4b --- /dev/null +++ b/DNFSort.java @@ -0,0 +1,49 @@ +public class DNFSort { + + // Sort the input array, the array is assumed to + // have values in {0, 1, 2} + static void sort012(int a[], int arr_size) { + int low = 0; + int high = arr_size - 1; + int mid = 0, temp = 0; + while (mid <= high) { + switch (a[mid]) { + case 0: { + temp = a[low]; + a[low] = a[mid]; + a[mid] = temp; + low++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[high]; + a[high] = temp; + high--; + break; + } + } + } + } + + /* Utility function to print array arr[] */ + static void printArray(int arr[], int arr_size) { + for (int i = 0; i < arr_size; i++) { + System.out.print(arr[i] + " "); + } + System.out.println(""); + } + + /*Driver function to check for above functions*/ + public static void main(String[] args) { + int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; + int arr_size = arr.length; + sort012(arr, arr_size); + System.out.println("Array after seggregation "); + printArray(arr, arr_size); + } +} diff --git a/Date_and_time.java b/Date_and_time.java new file mode 100644 index 00000000..e6ce5e07 --- /dev/null +++ b/Date_and_time.java @@ -0,0 +1,32 @@ +// Java program to convert 24 hour +// time format to 12 hour format + +// Importing specific date class libraries +import java.util.Date; +import java.text.SimpleDateFormat; + +public class GFG { + +// Main driver method + public static void main(String[] args) + { + // Getting the current current time + Date date = new Date(); + + + System.out.println("Current Time is : " + date); + + // set format in 12 hours + SimpleDateFormat formatTime = new SimpleDateFormat("hh.mm aa"); + // hh = hours in 12hr format + // mm = minutes + // aa = am/pm + + String time = formatTime.format( + date); // changing the format of 'date' + + // display time as per format + System.out.println( + "Current Time in AM/PM Format is : " + time); + } +} diff --git a/Delete given node.java b/Delete given node.java new file mode 100644 index 00000000..f3f976fd --- /dev/null +++ b/Delete given node.java @@ -0,0 +1,67 @@ +import java.util.*; +class Node { + int num; + Node next; + Node(int a) { + num = a; + next = null; + } +} +class Delete{ +//function to insert node at the end of the list +static Node insertNode(Node head,int val) { + Node newNode = new Node(val); + if(head == null) { + head = newNode; + return head; + } + Node temp = head; + while(temp.next != null) temp = temp.next; + temp.next = newNode; + return head; +} +//function to get reference of the node to delete +static Node getNode(Node head,int val) { + if(head==null) + return null; + while(head.num != val) head = head.next; + + return head; +} +//delete function as per the question +static void deleteNode(Node t) { + if(t==null) + return; + t.num = t.next.num; + t.next = t.next.next; + return; +} +//printing the list function +static void printList(Node head) { + if(head==null) + return; + while(head.next!=null ) { + System.out.print(head.num+"->"); + head = head.next; + } + System.out.println(head.num); +} + +public static void main(String args[]) { + Node head = null; + //inserting node + head=insertNode(head,1); + head=insertNode(head,4); + head=insertNode(head,2); + head=insertNode(head,3); + //printing given list + System.out.println("Given Linked List: "); + printList(head); + Node t = getNode(head,2); + //delete node + deleteNode(t); + //list after deletion operation + System.out.println("Linked List after deletion: "); + printList(head); +} +} diff --git a/Dequeue- basics/Double-End Queue.pdf b/Dequeue- basics/Double-End Queue.pdf new file mode 100644 index 00000000..60102607 Binary files /dev/null and b/Dequeue- basics/Double-End Queue.pdf differ diff --git a/Determinant_of_Matrix.java b/Determinant_of_Matrix.java new file mode 100644 index 00000000..bf856b9a --- /dev/null +++ b/Determinant_of_Matrix.java @@ -0,0 +1,94 @@ +// Java program to find Determinant of a matrix +class GFG { + + // Dimension of input square matrix + static final int N = 4; + + // Function to get determinant of matrix + static int determinantOfMatrix(int mat[][], int n) + { + int num1, num2, det = 1, index, + total = 1; // Initialize result + + // temporary array for storing row + int[] temp = new int[n + 1]; + + // loop for traversing the diagonal elements + for (int i = 0; i < n; i++) { + index = i; // initialize the index + + // finding the index which has non zero value + while (mat[index][i] == 0 && index < n) { + index++; + } + if (index == n) // if there is non zero element + { + // the determinant of matrix as zero + continue; + } + if (index != i) { + // loop for swaping the diagonal element row + // and index row + for (int j = 0; j < n; j++) { + swap(mat, index, j, i, j); + } + // determinant sign changes when we shift + // rows go through determinant properties + det = (int)(det * Math.pow(-1, index - i)); + } + + // storing the values of diagonal row elements + for (int j = 0; j < n; j++) { + temp[j] = mat[i][j]; + } + + // traversing every row below the diagonal + // element + for (int j = i + 1; j < n; j++) { + num1 = temp[i]; // value of diagonal element + num2 = mat[j] + [i]; // value of next row element + + // traversing every column of row + // and multiplying to every row + for (int k = 0; k < n; k++) { + // multiplying to make the diagonal + // element and next row element equal + mat[j][k] = (num1 * mat[j][k]) + - (num2 * temp[k]); + } + total = total * num1; // Det(kA)=kDet(A); + } + } + + // multiplying the diagonal elements to get + // determinant + for (int i = 0; i < n; i++) { + det = det * mat[i][i]; + } + return (det / total); // Det(kA)/k=Det(A); + } + + static int[][] swap(int[][] arr, int i1, int j1, int i2, + int j2) + { + int temp = arr[i1][j1]; + arr[i1][j1] = arr[i2][j2]; + arr[i2][j2] = temp; + return arr; + } + + // Driver code + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 2, -1 }, + { 3, 0, 0, 5 }, + { 2, 1, 4, -3 }, + { 1, 0, 5, 0 } }; + + // Function call + System.out.printf( + "Determinant of the matrix is : %d", + determinantOfMatrix(mat, N)); + } +} diff --git a/Dijkstra.java b/Dijkstra.java new file mode 100644 index 00000000..7df3767d --- /dev/null +++ b/Dijkstra.java @@ -0,0 +1,52 @@ +public class Dijkstra { + + public static void dijkstra(int[][] graph, int source) { + int count = graph.length; + boolean[] visitedVertex = new boolean[count]; + int[] distance = new int[count]; + for (int i = 0; i < count; i++) { + visitedVertex[i] = false; + distance[i] = Integer.MAX_VALUE; + } + + // Distance of self loop is zero + distance[source] = 0; + for (int i = 0; i < count; i++) { + + // Update the distance between neighbouring vertex and source vertex + int u = findMinDistance(distance, visitedVertex); + visitedVertex[u] = true; + + // Update all the neighbouring vertex distances + for (int v = 0; v < count; v++) { + if (!visitedVertex[v] && graph[u][v] != 0 && (distance[u] + graph[u][v] < distance[v])) { + distance[v] = distance[u] + graph[u][v]; + } + } + } + for (int i = 0; i < distance.length; i++) { + System.out.println(String.format("Distance from %s to %s is %s", source, i, distance[i])); + } + + } + + // Finding the minimum distance + private static int findMinDistance(int[] distance, boolean[] visitedVertex) { + int minDistance = Integer.MAX_VALUE; + int minDistanceVertex = -1; + for (int i = 0; i < distance.length; i++) { + if (!visitedVertex[i] && distance[i] < minDistance) { + minDistance = distance[i]; + minDistanceVertex = i; + } + } + return minDistanceVertex; + } + + public static void main(String[] args) { + int graph[][] = new int[][] { { 0, 0, 1, 2, 0, 0, 0 }, { 0, 0, 2, 0, 0, 3, 0 }, { 1, 2, 0, 1, 3, 0, 0 }, + { 2, 0, 1, 0, 0, 0, 1 }, { 0, 0, 3, 0, 0, 2, 0 }, { 0, 3, 0, 0, 2, 0, 1 }, { 0, 0, 0, 1, 0, 1, 0 } }; + Dijkstra T = new Dijkstra(); + T.dijkstra(graph, 0); + } +} \ No newline at end of file diff --git a/DijkstraAlgorithm.java b/DijkstraAlgorithm.java new file mode 100644 index 00000000..757d0289 --- /dev/null +++ b/DijkstraAlgorithm.java @@ -0,0 +1,57 @@ + +import java.util.Scanner; +public class DijkstraAlgorithm { + private static void dijkstra(int[][] adjacencyMatrix) { + int v = adjacencyMatrix.length; + boolean visited[] = new boolean[v]; + int distance[] = new int[v]; + distance[0] = 0; + for (int i = 1; i < v; i++) { + distance[i] = Integer.MAX_VALUE; + } + for (int i = 0; i < v - 1; i++) { + + int minVertex = findMinVertex(distance, visited); + visited[minVertex] = true; + + for (int j = 0; j < v; j++) { + if (adjacencyMatrix[minVertex][j] != 0 && !visited[j] && + distance[minVertex] != Integer.MAX_VALUE) { + int newDist = distance[minVertex] + + adjacencyMatrix[minVertex][j]; + if (newDist < distance[j]) { + distance[j] = newDist; + } + } + } + } + + for (int i = 0; i < v; i++) { + System.out.println(i + " " + distance[i]); + } + } + private static int findMinVertex(int[] distance, boolean visited[]) { + int minVertex = -1; + for (int i = 0; i < distance.length; i++) { + if (!visited[i] && (minVertex == -1 || distance[i] < + distance[minVertex])) { + minVertex = i; + } + } + return minVertex; + } + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + int v = s.nextInt(); + int e = s.nextInt(); + int adjacencyMatrix[][] = new int[v][v]; + for (int i = 0; i < e; i++) { + int v1 = s.nextInt(); + int v2 = s.nextInt(); + int weight = s.nextInt(); + adjacencyMatrix[v1][v2] = weight; + adjacencyMatrix[v2][v1] = weight; + } + dijkstra(adjacencyMatrix); + } +} \ No newline at end of file diff --git "a/Dijkstra\342\200\231s Shortest Path Algorithm" "b/Dijkstra\342\200\231s Shortest Path Algorithm" new file mode 100644 index 00000000..75de8446 --- /dev/null +++ "b/Dijkstra\342\200\231s Shortest Path Algorithm" @@ -0,0 +1,109 @@ +// A Java program for Dijkstra's single source shortest path +// algorithm. The program is for adjacency matrix +// representation of the graph +import java.io.*; +import java.lang.*; +import java.util.*; + +class ShortestPath { + // A utility function to find the vertex with minimum + // distance value, from the set of vertices not yet + // included in shortest path tree + static final int V = 9; + int minDistance(int dist[], Boolean sptSet[]) + { + // Initialize min value + int min = Integer.MAX_VALUE, min_index = -1; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) { + min = dist[v]; + min_index = v; + } + + return min_index; + } + + // A utility function to print the constructed distance + // array + void printSolution(int dist[]) + { + System.out.println( + "Vertex \t\t Distance from Source"); + for (int i = 0; i < V; i++) + System.out.println(i + " \t\t " + dist[i]); + } + + // Function that implements Dijkstra's single source + // shortest path algorithm for a graph represented using + // adjacency matrix representation + void dijkstra(int graph[][], int src) + { + int dist[] = new int[V]; // The output array. + // dist[i] will hold + // the shortest distance from src to i + + // sptSet[i] will true if vertex i is included in + // shortest path tree or shortest distance from src + // to i is finalized + Boolean sptSet[] = new Boolean[V]; + + // Initialize all distances as INFINITE and stpSet[] + // as false + for (int i = 0; i < V; i++) { + dist[i] = Integer.MAX_VALUE; + sptSet[i] = false; + } + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set + // of vertices not yet processed. u is always + // equal to src in first iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of + // the picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, + // there is an edge from u to v, and total + // weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] != 0 + && dist[u] != Integer.MAX_VALUE + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist); + } + + // Driver's code + public static void main(String[] args) + { + /* Let us create the example graph discussed above + */ + int graph[][] + = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + ShortestPath t = new ShortestPath(); + + // Function call + t.dijkstra(graph, 0); + } +} diff --git a/Disarium.java b/Disarium.java new file mode 100644 index 00000000..20966b3f --- /dev/null +++ b/Disarium.java @@ -0,0 +1,21 @@ +import java.util.*; +public class Disarium{ + boolean isDisarium(int n){ + byte c=0; + int b=0; + for(int i=n;i>0;c+=1,i/=10); + for(int i=n;i>0;b=b+(int)Math.pow(i%10,c--),i/=10); + if(n==b) + return true; + return false; + } + + public static void main(String args[]) + { + System.out.println("Enter a number:"); + if(new Disarium().isDisarium(new Scanner(System.in).nextInt())) + System.out.println("Disarium number"); + else + System.out.println("Not an Disarium number."); + } +} \ No newline at end of file diff --git a/Duplicatefind.java b/Duplicatefind.java new file mode 100644 index 00000000..267cc597 --- /dev/null +++ b/Duplicatefind.java @@ -0,0 +1,33 @@ + + +public class DuplicateElement { + + public static void main(String[] args) { + + + + //Initialize array + + int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3}; + + + + System.out.println("Duplicate elements in given array: "); + + //Searches for duplicate element + + for(int i = 0; i < arr.length; i++) { + + for(int j = i + 1; j < arr.length; j++) { + + if(arr[i] == arr[j]) + + System.out.println(arr[j]); + + } + + } + + } + +} diff --git a/Electricitybill.java b/Electricitybill.java new file mode 100644 index 00000000..8792ab88 --- /dev/null +++ b/Electricitybill.java @@ -0,0 +1,26 @@ +class ElectricityBillExample1 +{ + // main() method start + public static void main(String args[]) + { + // declare and initialize variable units + int units = 380; + // variable to calculate electricity bill to pay + double billToPay = 0; + // check whether units are less than 100 + if(units < 100) + { + billToPay = units * 1.20; + } + // check whether the units are less than 300 + else if(units < 300){ + billToPay = 100 * 1.20 + (units - 100) * 2; + } + // check whether the units are greater than 300 + else if(units > 300) + { + billToPay = 100 * 1.20 + 200 * 2 + (units - 300) * 3; + } + System.out.println("The electricity bill for " +units+ " is : " + billToPay); + } +} diff --git a/EvenOdd.java b/EvenOdd.java new file mode 100644 index 00000000..21eb8518 --- /dev/null +++ b/EvenOdd.java @@ -0,0 +1,22 @@ +import java.util.*; + +public class EvenOdd { + public static void main(String[] args) { + int v=0,c=0; + Scanner sc = new Scanner(System.in); + + System.out.println("Enter String : "); + String a = sc.nextLine(); + + for (i=0; i<=a.length; i++){ + if(String.charAt[i]=='a' || String.charAt[i]=='e'||String.charAt[i]=='i'||String.charAt[i]=='o'||String.charAt[i]=='u'){ + v++; + } + else{ + c++; + } + } + System.out.println("Vowels: "+ v); + System.out.println("Consonents: "+ c); + } +} diff --git a/FactorialProgram.java b/FactorialProgram.java new file mode 100644 index 00000000..de1ecbc9 --- /dev/null +++ b/FactorialProgram.java @@ -0,0 +1,31 @@ +import java.util.Scanner; + +class Abc +{ + public int f=1,i=0; + + public void fact(int n) + { + for(i=1; i<=n; i++) + { + f = f*i; + } + + System.out.println(n + " Factorial is : " + f); + } +} + +class factorial +{ + public static void main(String arr[]) + { + Scanner m = new Scanner(System.in); + + System.out.print("Enter Elemnt TO find Factorial : "); + int n = m.nextInt(); + + Abc a1 = new Abc(); + a1.fact(n); + + } +} diff --git a/Factorialusingrecursion.cpp b/Factorialusingrecursion.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/Factorialusingrecursion.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/FibonacciSeries.java b/FibonacciSeries.java new file mode 100644 index 00000000..4e6629ef --- /dev/null +++ b/FibonacciSeries.java @@ -0,0 +1,15 @@ +class Fibonacci{ +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 ans = new Vector<>(); + + // Traversal + for (int i = n - 1; i >= 0; i--) + { + // Find denominations + while (V >= deno[i]) + { + V -= deno[i]; + ans.add(deno[i]); + } + } + + // Printing result + for (int i = 0; i < ans.size(); i++) + { + System.out.print( + " " + ans.elementAt(i)); + } + } + + public static void main(String[] args) + { + int n = 93; + System.out.print( + "Following is minimum number " + +"of change for " + n + ": "); + findMin(n); + } +} + + diff --git a/FirstMissingPositive.java b/FirstMissingPositive.java new file mode 100644 index 00000000..0934d78b --- /dev/null +++ b/FirstMissingPositive.java @@ -0,0 +1,41 @@ +// First Missing Positive +// URL : https://leetcode.com/problems/first-missing-positive/ + +package com.akshat; + +public class FirstMissingPositive { + + public static void main(String[] args) { + + int[] nums = {7, 8, 9, 11, 12}; + + System.out.println(firstMissingPositive(nums)); + + } + + static int firstMissingPositive(int[] nums){ + int i = 0; + while (i < nums.length){ + int correct = nums[i] - 1; + if (nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[correct]){ + swap(nums, i, correct); + } + else{ + i++; + } + } + for (int index=0; index< nums.length; index++){ + if (nums[index] != index+1){ + return index+1; + } + } + return nums.length+1; + } + + static void swap(int[] nums, int first, int second){ + int temp = nums[first]; + nums[first] = nums[second]; + nums[second] = temp; + } + +} diff --git a/FloydTrg.java b/FloydTrg.java new file mode 100644 index 00000000..f28d7091 --- /dev/null +++ b/FloydTrg.java @@ -0,0 +1,17 @@ +import java.io.*; +public class FloydTrg{ + void gen(int n){ + int c=0; + for(int i=1;i<=n;i++){ + for(int j=1;j<=i;j++) + System.out.print(++c+" "); + System.out.println(); + } + } + + public static void main(String args[])throws IOException + { + System.out.println("Enter the line numbers:"); + new FloydTrg().gen(Integer.parseInt(new BufferedReader(new InputStreamReader(System.in)).readLine())); + } +} \ No newline at end of file diff --git a/GCD of two numbers b/GCD of two numbers new file mode 100644 index 00000000..83037367 --- /dev/null +++ b/GCD of two numbers @@ -0,0 +1,11 @@ +def hcf(a, b): + if(b == 0): + return a + else: + return hcf(b, a % b) + +a = 60 +b = 48 + +print("The gcd of 60 and 48 is : ", end="") +print(hcf(60, 48)) diff --git a/GCD.java b/GCD.java new file mode 100644 index 00000000..284b6649 --- /dev/null +++ b/GCD.java @@ -0,0 +1,29 @@ +/** + * Java program to find Greatest Common Divisor or GCD of + * two numbers using Euclid’s method.*/ + import java.util.*; +public class GCD{ + + public static void main(String args[]){ + + //Enter two number whose GCD needs to be calculated. + Scanner sc = new Scanner(System.in); + System.out.println("Please enter first number to find GCD"); + int num1 = sc.nextInt(); + System.out.println("Please enter second number to find GCD"); + int num2 = sc.nextInt(); + + System.out.println("GCD of two numbers " + num1 +" and " + + num2 +" is :" + GCD(num1,num2)); + + + } + private static int GCD(int num1, int num2) { + //base case + if(num2 == 0){ + return num1; + } + return GCD(num2, num1%num2); + } + +} \ No newline at end of file diff --git a/GOLDEN RATIO(VA)1.cpp b/GOLDEN RATIO(VA)1.cpp new file mode 100644 index 00000000..35b4ea36 --- /dev/null +++ b/GOLDEN RATIO(VA)1.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +int main() { + int n, t1 = 0, t2 = 1, nextTerm = 0; + + cout << "Enter the number of terms: "; + cin >> n; + + cout << "Fibonacci Series: "; + + for (int i = 1; i <= n; ++i) { + // Prints the first two terms. + if(i == 1) { + cout << t1 << ", "; + continue; + } + if(i == 2) { + cout << t2 << ", "; + continue; + } + nextTerm = t1 + t2; + t1 = t2; + t2 = nextTerm; + + cout << nextTerm << ", "; + } + return 0; +} diff --git a/Gcd.java b/Gcd.java new file mode 100644 index 00000000..df4c4b9b --- /dev/null +++ b/Gcd.java @@ -0,0 +1,33 @@ +import java.util.*; +class Gcd +{ + public static int gcd(int n1,int n2) + { + while(n1!=n2) + { + if(n1>n2) + { + n1=n1-n2; + } + else + { + n2=n2-n1; + } + } + return n1; + + } + public static void main(String args[]) + { + int n1,n2; + Scanner Sc = new Scanner(System.in); + System.out.print("enter n1:"); + n1=Sc.nextInt(); + System.out.print("enter n2:"); + n2=Sc.nextInt(); + System.out.println("gcd of "+n1+" and "+n2+" is "+gcd(n1,n2)); + } + +} + + diff --git a/Greatest Number b/Greatest Number new file mode 100644 index 00000000..499e3bc2 --- /dev/null +++ b/Greatest Number @@ -0,0 +1,12 @@ +num1 = float(input("Enter first number: ")) +num2 = float(input("Enter second number: ")) +num3 = float(input("Enter third number: ")) + +if (num1 >= num2) and (num1 >= num3): + largest = num1 +elif (num2 >= num1) and (num2 >= num3): + largest = num2 +else: + largest = num3 + +print("The largest number is", largest) diff --git a/GuessNumber.java b/GuessNumber.java new file mode 100644 index 00000000..674d8e6a --- /dev/null +++ b/GuessNumber.java @@ -0,0 +1,45 @@ +package com.company; +import java.util.Random; +import java.util.Scanner; +public class GuessNumber +{ + + + + public static void main(String[] args) { + System.out.printf("***Welcome Guess Number game ****\n"); + + Random ra = new Random(); + int gen = ra.nextInt(10); + System.out.printf("Guess ? \n"); + int number ; + System.out.printf("Enter the number to guess between 0 to 9 \n"); + Scanner scan = new Scanner(System.in); + number = scan.nextInt(); + + do { + if (number>gen) + { + System.out.printf("Please try again Number %d > ? \n",number); + number = scan.nextInt(); + } + + else + { + + System.out.printf("Please try again Number %d < ? \n",number); + + number = scan.nextInt(); + + + } + + }while ( number!=gen); + + + System.out.println("Great you won " + " number is " + gen ); + + } + + +} diff --git a/GuessTheNumber.java b/GuessTheNumber.java new file mode 100644 index 00000000..4d41c789 --- /dev/null +++ b/GuessTheNumber.java @@ -0,0 +1,72 @@ +// This is a fun game program of guessing the number +// User can run the program and ask for a number +// He has to guess the number in minimum number of attempts +// Also the Random Number will be generated by the program + +package org; + +import java.util.Random; +import java.util.Scanner; + +class GuessTheNumber{ + private int actual; + private int guessed; + private int noOfGuesses; + + public GuessTheNumber(){ + Random r = new Random(); + actual = r.nextInt(100); + // or ThreadLocalRandom.current().nextInt(Min, Max + 1); //Min=1 max = 100 + } + + public void setnoOfGuesses(int n) { + this.noOfGuesses = n; + } + + public int getnoOfGuesses() { + return this.noOfGuesses; + } + + public int UserInput(){ + System.out.println("Enter a Number between 0-100: "); + Scanner sc = new Scanner(System.in); + guessed = sc.nextInt(); + return guessed; + } + + public boolean isCorrect(int inp) { + this.guessed = inp; + if(guessed>actual) { + System.out.println("The number is too High"); + return false; + } + else if(guessedcc) + { + System.out.println("This number is greater than computer's.\nTry again :"); + } + } + } +} \ No newline at end of file diff --git a/Hackfest.cpp b/Hackfest.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/Hackfest.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/Hacktoberfest-2022 b/Hacktoberfest-2022 new file mode 100644 index 00000000..73d802bb --- /dev/null +++ b/Hacktoberfest-2022 @@ -0,0 +1,12 @@ +class Bike8{ + int speed; + + Bike8(){System.out.println("constructor is invoked");} + + {System.out.println("instance initializer block invoked");} + + public static void main(String args[]){ + Bike8 b1=new Bike8(); + Bike8 b2=new Bike8(); + } +} diff --git a/Hacktoberfest-2022https:/github.com/ajitkumar1264/java-algorithms b/Hacktoberfest-2022https:/github.com/ajitkumar1264/java-algorithms new file mode 100644 index 00000000..f7f0b9e1 --- /dev/null +++ b/Hacktoberfest-2022https:/github.com/ajitkumar1264/java-algorithms @@ -0,0 +1,19 @@ +public class PrimeExample{ + public static void main(String args[]){ + int i,m=0,flag=0; + int n=3;//it is the number to be checked + m=n/2; + if(n==0||n==1){ + System.out.println(n+" is not prime number"); + }else{ + for(i=2;i<=m;i++){ + if(n%i==0){ + System.out.println(n+" is not prime number"); + flag=1; + break; + } + } + if(flag==0) { System.out.println(n+" is prime number"); } + }//end of else +} +} diff --git a/Harshpreet Singh3 b/Harshpreet Singh3 new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/Harshpreet Singh3 @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/HashMap.java/Create Hashmap.txt b/HashMap.java/Create Hashmap.txt new file mode 100644 index 00000000..72b306bb --- /dev/null +++ b/HashMap.java/Create Hashmap.txt @@ -0,0 +1,43 @@ +// Java program to illustrate HashMap class of java.util +// package + +// Importing HashMap class +import java.util.HashMap; + +// Main class +public class GFG { + + // Main driver method + public static void main(String[] args) + { + // Create an empty hash map by declaring object + // of string and integer type + HashMap map = new HashMap<>(); + + // Adding elements to the Map + // using standard put() method + map.put("vishal", 10); + map.put("sachin", 30); + map.put("vaibhav", 20); + + // Print size and content of the Map + System.out.println("Size of map is:- " + + map.size()); + + // Printing elements in object of Map + System.out.println(map); + + // Checking if a key is present and if + // present, print value by passing + // random element + if (map.containsKey("vishal")) { + + // Mapping + Integer a = map.get("vishal"); + + // Printing value for the corresponding key + System.out.println("value for key" + + " \"vishal\" is:- " + a); + } + } +} diff --git a/HashMap.java/Operations in HashMap/Adding Elements.txt b/HashMap.java/Operations in HashMap/Adding Elements.txt new file mode 100644 index 00000000..ee461226 --- /dev/null +++ b/HashMap.java/Operations in HashMap/Adding Elements.txt @@ -0,0 +1,33 @@ +// Java program to add elements +// to the HashMap + +import java.io.*; +import java.util.*; + +class AddElementsToHashMap { + public static void main(String args[]) + { + // No need to mention the + // Generic type twice + HashMap hm1 = new HashMap<>(); + + // Initialization of a HashMap + // using Generics + HashMap hm2 + = new HashMap(); + + // Add Elements using put method + hm1.put(1, "Element1"); + hm1.put(2, "Element2"); + hm1.put(3, "Element3"); + + hm2.put(1, "Element1"); + hm2.put(2, "Element2"); + hm2.put(3, "Element3"); + + System.out.println("Mappings of HashMap hm1 are : " + + hm1); + System.out.println("Mapping of HashMap hm2 are : " + + hm2); + } +} diff --git a/HashMap.java/Operations in HashMap/Changing Elements.txt b/HashMap.java/Operations in HashMap/Changing Elements.txt new file mode 100644 index 00000000..28d5955d --- /dev/null +++ b/HashMap.java/Operations in HashMap/Changing Elements.txt @@ -0,0 +1,25 @@ +// Java program to change +// elements of HashMap + +import java.io.*; +import java.util.*; +class ChangeElementsOfHashMap { + public static void main(String args[]) + { + + // Initialization of a HashMap + HashMap hm + = new HashMap(); + + // Change Value using put method + hm.put(1, "Geeks"); + hm.put(2, "Geeks"); + hm.put(3, "Geeks"); + + System.out.println("Initial Map " + hm); + + hm.put(2, "For"); + + System.out.println("Updated Map " + hm); + } +} diff --git a/HashMap.java/Operations in HashMap/Removing Elements.txt b/HashMap.java/Operations in HashMap/Removing Elements.txt new file mode 100644 index 00000000..1972d53c --- /dev/null +++ b/HashMap.java/Operations in HashMap/Removing Elements.txt @@ -0,0 +1,31 @@ +// Java program to remove +// elements from HashMap + +import java.io.*; +import java.util.*; +class RemoveElementsOfHashMap{ + public static void main(String args[]) + { + // Initialization of a HashMap + Map hm + = new HashMap(); + + // Add elements using put method + hm.put(1, "Geeks"); + hm.put(2, "For"); + hm.put(3, "Geeks"); + hm.put(4, "For"); + + // Initial HashMap + System.out.println("Mappings of HashMap are : " + + hm); + + // remove element with a key + // using remove method + hm.remove(4); + + // Final HashMap + System.out.println("Mappings after removal are : " + + hm); + } +} diff --git a/HashMap.java/Operations in HashMap/Traversal of HashMap.txt b/HashMap.java/Operations in HashMap/Traversal of HashMap.txt new file mode 100644 index 00000000..748e51b5 --- /dev/null +++ b/HashMap.java/Operations in HashMap/Traversal of HashMap.txt @@ -0,0 +1,24 @@ +// Java program to traversal a +// Java.util.HashMap + +import java.util.HashMap; +import java.util.Map; + +public class TraversalTheHashMap { + public static void main(String[] args) + { + // initialize a HashMap + HashMap map = new HashMap<>(); + + // Add elements using put method + map.put("vishal", 10); + map.put("sachin", 30); + map.put("vaibhav", 20); + + // Iterate the map using + // for-each loop + for (Map.Entry e : map.entrySet()) + System.out.println("Key: " + e.getKey() + + " Value: " + e.getValue()); + } +} diff --git a/HeapSort.java b/HeapSort.java index fb34021e..3330fdf3 100644 --- a/HeapSort.java +++ b/HeapSort.java @@ -1,72 +1,59 @@ -public class HeapSort { - public void sort(int arr[]) - { - int N = arr.length; - - // Build heap (rearrange array) - for (int i = N / 2 - 1; i >= 0; i--) - heapify(arr, N, i); - - // One by one extract an element from heap - for (int i = N - 1; i > 0; i--) { - // Move current root to end - int temp = arr[0]; - arr[0] = arr[i]; - arr[i] = temp; - - // call max heapify on the reduced heap - heapify(arr, i, 0); - } - } - - // To heapify a subtree rooted with node i which is - // an index in arr[]. n is size of heap - void heapify(int arr[], int N, int i) - { - int largest = i; // Initialize largest as root - int l = 2 * i + 1; // left = 2*i + 1 - int r = 2 * i + 2; // right = 2*i + 2 - - // If left child is larger than root - if (l < N && arr[l] > arr[largest]) - largest = l; - - // If right child is larger than largest so far - if (r < N && arr[r] > arr[largest]) - largest = r; - - // If largest is not root - if (largest != i) { - int swap = arr[i]; - arr[i] = arr[largest]; - arr[largest] = swap; - - // Recursively heapify the affected sub-tree - heapify(arr, N, largest); - } - } - - /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int N = arr.length; - - for (int i = 0; i < N; ++i) - System.out.print(arr[i] + " "); - System.out.println(); - } - - // Driver's code - public static void main(String args[]) - { - int arr[] = { 12, 11, 13, 5, 6, 7 }; - int N = arr.length; - - // Function call - HeapSort ob = new HeapSort(); - ob.sort(arr); - - System.out.println("Sorted array is"); - printArray(arr); - } -} \ No newline at end of file +class HeapSort +{ +/* function to heapify a subtree. Here 'i' is the +index of root node in array a[], and 'n' is the size of heap. */ +static void heapify(int a[], int n, int i) +{ + int largest = i; // Initialize largest as root + int left = 2 * i + 1; // left child + int right = 2 * i + 2; // right child + // If left child is larger than root + if (left < n && a[left] > a[largest]) + largest = left; + // If right child is larger than root + if (right < n && a[right] > a[largest]) + largest = right; + // If root is not largest + if (largest != i) { + // swap a[i] with a[largest] + int temp = a[i]; + a[i] = a[largest]; + a[largest] = temp; + + heapify(a, n, largest); + } +} +/*Function to implement the heap sort*/ +static void heapSort(int a[], int n) +{ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(a, n, i); + + // One by one extract an element from heap + for (int i = n - 1; i >= 0; i--) { + /* Move current root element to end*/ + // swap a[0] with a[i] + int temp = a[0]; + a[0] = a[i]; + a[i] = temp; + + heapify(a, i, 0); + } +} +/* function to print the array elements */ +static void printArr(int a[], int n) +{ + for (int i = 0; i < n; ++i) + System.out.print(a[i] + " "); +} +public static void main(String args[]) +{ + int a[] = {45, 7, 20, 40, 25, 23, -2}; + int n = a.length; + System.out.print("Before sorting array elements are - \n"); + printArr(a, n); + heapSort(a, n); + System.out.print("\nAfter sorting array elements are - \n"); + printArr(a, n); +} +} \ No newline at end of file diff --git a/Heap_Sort.java b/Heap_Sort.java new file mode 100644 index 00000000..f9800d72 --- /dev/null +++ b/Heap_Sort.java @@ -0,0 +1,70 @@ +public class HeapSort +{ + public void sort(int arr[]) + { + int n = arr.length; + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + + void heapify(int arr[], int n, int i) + { + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + + if (l < n && arr[l] > arr[largest]) + largest = l; + + + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + + heapify(arr, n, largest); + } + } + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i2){ + li[a]=n; + } + li1=new int[li.length]; + for(int i=0; i9){ + while(li[i]!=0){ + int rem=li[i]%10; + sum+=rem; + li[i]/=10; + } + } + else { + sum += li[i]; + } + } + } + return sum; + } + +} + +public class Hoax_No { + public static void main(String[] args) { + int a; + Scanner sc=new Scanner(System.in); + a= sc.nextInt(); + Hoax s=new Hoax(a); +// int[] li=s.factors(); +// for(int i=0; i q + = new PriorityQueue(n, new MyComparator()); + + for (int i = 0; i < n; i++) { + + // creating a Huffman node object + // and add it to the priority queue. + HuffmanNode hn = new HuffmanNode(); + + hn.c = charArray[i]; + hn.data = charfreq[i]; + + hn.left = null; + hn.right = null; + + // add functions adds + // the huffman node to the queue. + q.add(hn); + } + + // create a root node + HuffmanNode root = null; + + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. + while (q.size() > 1) { + + // first min extract. + HuffmanNode x = q.peek(); + q.poll(); + + // second min extract. + HuffmanNode y = q.peek(); + q.poll(); + + // new node f which is equal + HuffmanNode f = new HuffmanNode(); + + // to the sum of the frequency of the two nodes + // assigning values to the f node. + f.data = x.data + y.data; + f.c = '-'; + + // first extracted node as left child. + f.left = x; + + // second extracted node as the right child. + f.right = y; + + // marking the f node as the root node. + root = f; + + // add this node to the priority-queue. + q.add(f); + } + + // print the codes by traversing the tree + printCode(root, ""); + } +} + +// node class is the basic structure +// of each node present in the Huffman - tree. +class HuffmanNode { + + int data; + char c; + + HuffmanNode left; + HuffmanNode right; +} + +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. +class MyComparator implements Comparator { + public int compare(HuffmanNode x, HuffmanNode y) + { + + return x.data - y.data; + } +} + +// This code is contributed by Rishabh Verma diff --git a/I1.png b/I1.png new file mode 100644 index 00000000..2699f11d Binary files /dev/null and b/I1.png differ diff --git a/Inheritance-in-java.java b/Inheritance-in-java.java new file mode 100644 index 00000000..24ae16f6 --- /dev/null +++ b/Inheritance-in-java.java @@ -0,0 +1,74 @@ +// Java program to illustrate the +// concept of inheritance + +// base class +class Bicycle { + // the Bicycle class has two fields + public int gear; + public int speed; + + // the Bicycle class has one constructor + public Bicycle(int gear, int speed) + { + this.gear = gear; + this.speed = speed; + } + + // the Bicycle class has three methods + public void applyBrake(int decrement) + { + speed -= decrement; + } + + public void speedUp(int increment) + { + speed += increment; + } + + // toString() method to print info of Bicycle + public String toString() + { + return ("No of gears are " + gear + "\n" + + "speed of bicycle is " + speed); + } +} + +// derived class +class MountainBike extends Bicycle { + + // the MountainBike subclass adds one more field + public int seatHeight; + + // the MountainBike subclass has one constructor + public MountainBike(int gear, int speed, + int startHeight) + { + // invoking base-class(Bicycle) constructor + super(gear, speed); + seatHeight = startHeight; + } + + // the MountainBike subclass adds one more method + public void setHeight(int newValue) + { + seatHeight = newValue; + } + + // overriding toString() method + // of Bicycle to print more info + @Override public String toString() + { + return (super.toString() + "\nseat height is " + + seatHeight); + } +} + +// driver class +public class Test { + public static void main(String args[]) + { + + MountainBike mb = new MountainBike(3, 100, 25); + System.out.println(mb.toString()); + } +} diff --git a/Inheritance.java b/Inheritance.java new file mode 100644 index 00000000..21b5e517 --- /dev/null +++ b/Inheritance.java @@ -0,0 +1,103 @@ +import java.util.Scanner; + +class Player +{ + static int age,total; + static String name; + static String type; + static String role; +} + +class CricketPlayer extends Player +{ + public int c = 0; + + void getData() + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Player Name : "); + name = meet.nextLine(); + + System.out.print("Enter Player Age : "); + age = meet.nextInt(); + + System.out.print("Enter Player Type (Batsman or Bowler) : "); + type = meet.next(); + + if(type == "Bowler" || type == "bowler") + { + c++; + } + } + + void Bowler_Info() + { + if(c>0) + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Bowler Player Type (Fast / Spin / Medium) : "); + role = meet.next(); + } + + } +} + +class batsman extends CricketPlayer +{ + void getCar() + { + Scanner meet = new Scanner(System.in); + + System.out.print("Enter Player Carrer Total Match : "); + total = meet.nextInt(); + + } + + void print1() + { + System.out.println("Player Type : " + type); + System.out.println("Carrer Total Match : " + total); + } + +} + +class Bowler extends CricketPlayer +{ + + void print() + { + System.out.println("Player Name : " + name); + System.out.println("Player Age : " + age); + + if(c == 1) + { + System.out.println("Player Boling Type : " + role); + } + + } + +} + +class Inheri { + + public static void main(String arr[]) + { + Bowler b1 = new Bowler(); + batsman c1 = new batsman(); + + b1.getData(); + c1.getCar(); + b1.Bowler_Info(); + + System.out.print("\n------------------------------------------------\n"); + + b1.print(); + c1.print1(); + + System.out.println("------------------------------------------------"); + + } + +} diff --git a/Insertion Sort b/Insertion Sort new file mode 100644 index 00000000..d1940b42 --- /dev/null +++ b/Insertion Sort @@ -0,0 +1,30 @@ +public class InsertionSortExample { + public static void insertionSort(int array[]) { + int n = array.length; + for (int j = 1; j < n; j++) { + int key = array[j]; + int i = j-1; + while ( (i > -1) && ( array [i] > key ) ) { + array [i+1] = array [i]; + i--; + } + array[i+1] = key; + } + } + + public static void main(String a[]){ + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Insertion Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + System.out.println(); + + insertionSort(arr1);//sorting array using insertion sort + + System.out.println("After Insertion Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + } +} diff --git a/InsertionSort.java b/InsertionSort.java index ad17d3eb..c30fc087 100644 --- a/InsertionSort.java +++ b/InsertionSort.java @@ -1,38 +1,42 @@ -import java.util.Arrays; - -public class InsertionSort { - - //Função para o Insertion Sort - public static void sort(int[] vetor) { - int aux, j; - //Laço de repetição para percorrer a lista - for (int i = 1; i < vetor.length; i++) { - //Auxiliar para melhor leitura - aux = vetor[i]; - //Indice do vetor - j = i - 1; - - //Enquanto as 2 opções forem Verdadeiras - while(j >= 0 && aux < vetor[j]) { - //O num q estava na posição j+1 vai ocupar a posição j - vetor[j+1] = vetor[j]; - //Caso o aux precise andar mais de uma casa para esquerda - j--; - } - vetor[j+1] = aux; - } - } - - - //Função Principal - public static void main(String[] args) { - //Criação lista 0 1 2 3 4 - int[] vetor = { 3, 4, 1, 2, 5 }; - - //Função para ordenar a lista - sort(vetor); - - //Imprimindo a lista Ordenada - System.out.println(Arrays.toString(vetor)); - } -} +// Java program for implementation of Insertion Sort +class InsertionSort { + /*Function to sort array using insertion sort*/ + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} \ No newline at end of file diff --git a/Intersection of Two Arrays II.java b/Intersection of Two Arrays II.java new file mode 100644 index 00000000..23f98978 --- /dev/null +++ b/Intersection of Two Arrays II.java @@ -0,0 +1,15 @@ + +public class Solution{ + + public static void intersections(int arr1[], int arr2[]) { + for (int i = 0; i < arr1.length; i++){ + for (int j = 0; j < arr2.length; j++){ + if (arr1[i] == arr2[j]){ + System.out.print(arr1[i] + " "); + arr2[j] = Integer.MIN_VALUE; + break; + } + } + } + } +} diff --git a/Java program to find maximum product of.java b/Java program to find maximum product of.java new file mode 100644 index 00000000..b61b9f7b --- /dev/null +++ b/Java program to find maximum product of.java @@ -0,0 +1,78 @@ +// Java program to find maximum product of +// a subset. +class Array { + + static int minProductSubset(int a[], int n) + { + if (n == 1) + return a[0]; + + // Find count of negative numbers, + // count of zeros, maximum valued + // negative number, minimum valued + // positive number and product of + // non-zero numbers + int negmax = Integer.MIN_VALUE; + int posmin = Integer.MAX_VALUE; + int count_neg = 0, count_zero = 0; + int product = 1; + + for (int i = 0; i < n; i++) { + + // if number is zero,count it + // but dont multiply + if (a[i] == 0) { + count_zero++; + continue; + } + + // count the negative numbers + // and find the max negative number + if (a[i] < 0) { + count_neg++; + negmax = Math.max(negmax, a[i]); + } + + // find the minimum positive number + if (a[i] > 0 && a[i] < posmin) + posmin = a[i]; + + product *= a[i]; + } + + // if there are all zeroes + // or zero is present but no + // negative number is present + if (count_zero == n + || (count_neg == 0 && count_zero > 0)) + return 0; + + // If there are all positive + if (count_neg == 0) + return posmin; + + // If there are even number except + // zero of negative numbers + if (count_neg % 2 == 0 && count_neg != 0) { + + // Otherwise result is product of + // all non-zeros divided by maximum + // valued negative. + product = product / negmax; + } + + return product; + } + + // main function + public static void main(String[] args) + { + + int a[] = { -1, -1, -2, 4, 3 }; + int n = 5; + + System.out.println(minProductSubset(a, n)); + } +} + +// This code is contributed by Arnab Kundu. diff --git a/Java3.0 b/Java3.0 new file mode 100644 index 00000000..1b84e909 --- /dev/null +++ b/Java3.0 @@ -0,0 +1,37 @@ +// Factorial of n = 1*2*3*...*n + +#include + +using namespace std; + +int factorial(int); + +int main() { + + int n, result; + + cout << "Enter a non-negative number: "; + + cin >> n; + + result = factorial(n); + + cout << "Factorial of " << n << " = " << result; + + return 0; + +} + +int factorial(int n) { + + if (n > 1) { + + return n * factorial(n - 1); + + } else { + + return 1; + + } + +} diff --git a/JavaAlgo.java b/JavaAlgo.java new file mode 100644 index 00000000..743d6711 --- /dev/null +++ b/JavaAlgo.java @@ -0,0 +1,35 @@ +public class JumpSearchAlgorithm { + + public static void main(String[] args) { + int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90}; + int ele = 60; + + int foundIndex = jumpSearch(arr, ele); + System.out.println(foundIndex > 0 ? "Found at index : " + foundIndex : "Element Not Found"); + } + + public static int jumpSearch(int[] arr, int ele) { + + int prev = 0; + int n = arr.length; + int step = (int) Math.floor(Math.sqrt(n)); + + //loop until current element is less than the given search element + while (arr[Math.min(step, n) - 1] < ele) { + prev = step; + step += (int) Math.floor(Math.sqrt(n)); + if (prev >= n) return -1; + } + + //perform linear search prev index element to given element + while (arr[prev] < ele) { + prev++; + if (prev == Math.min(step, n)) return -1; + } + + // Return index if element is found + if (arr[prev] == ele) return prev; + + return -1; + } +} diff --git a/JavaAlgo4 b/JavaAlgo4 new file mode 100644 index 00000000..56dfae16 --- /dev/null +++ b/JavaAlgo4 @@ -0,0 +1,23 @@ +#include +using namespace std; + +int factorial(int n); + +int main() { + + int n; + + cout << "Enter a positive integer: "; + cin >> n; + + cout << "Factorial of " << n << " = " << factorial(n); + + return 0; +} + +int factorial(int n) { + if(n > 1) + return n * factorial(n - 1); + else + return 1; +} diff --git a/Javaalgo1.java b/Javaalgo1.java new file mode 100644 index 00000000..efb481a3 --- /dev/null +++ b/Javaalgo1.java @@ -0,0 +1,34 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + // Using reverse() + Collections.reverse(numbers); + System.out.println("Reversed ArrayList1: " + numbers); + + // Using swap() + Collections.swap(numbers, 0, 1); + System.out.println("ArrayList1 using swap(): " + numbers); + + ArrayList newNumbers = new ArrayList<>(); + + // Using addAll + newNumbers.addAll(numbers); + System.out.println("ArrayList2 using addAll(): " + newNumbers); + + // Using fill() + Collections.fill(numbers, 0); + System.out.println("ArrayList1 using fill(): " + numbers); + + // Using copy() + Collections.copy(newNumbers, numbers); + System.out.println("ArrayList2 using copy(): " + newNumbers); + } +} diff --git a/K closest elements b/K closest elements new file mode 100644 index 00000000..2d0ee550 --- /dev/null +++ b/K closest elements @@ -0,0 +1,25 @@ +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + Map> map = new TreeMap<>(); + List result = new ArrayList<>(); + + for(int i=0; i vals = map.getOrDefault(diff,new ArrayList<>()); + vals.add(arr[i]); + map.put(diff,vals); + } + + + for(Map.Entry> entry : map.entrySet()){ + for(Integer num : entry.getValue()){ + if(k>0){ + result.add(num); + k--; + } + } + } + Collections.sort(result); + return result; + } +} diff --git a/Kadane.java b/Kadane.java new file mode 100644 index 00000000..261aae7e --- /dev/null +++ b/Kadane.java @@ -0,0 +1,24 @@ + +public class Kadane { + public static void main(String[] args) { + System.out.println(kadaneAlgo(new int[]{1,2,3,4,-10, 11, -1})); + } + + public static int kadaneAlgo(int[] arr){ + int max = arr[0], sum = 0; + int len = 0; + for (int i = 0; i < arr.length; i++) { + + sum+=arr[i]; + len++; + if (sum > max) { + max = sum; + } + if (sum <= 0) { + sum = 0; + len = 0; + } + } + return max; + } +} diff --git a/Kadane_Algorithm.java b/Kadane_Algorithm.java new file mode 100644 index 00000000..fc3b9e3e --- /dev/null +++ b/Kadane_Algorithm.java @@ -0,0 +1,30 @@ +// Java program to print largest contiguous array sum +import java.io.*; +import java.util.*; + +class Kadane_Algorithm { + // Driver Code + public static void main(String[] args) + { + int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + // Function Call + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here + = 0; + + for (int i = 0; i < size; i++) { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} diff --git a/Kadane_algorithm.py b/Kadane_algorithm.py new file mode 100644 index 00000000..6620c2d0 --- /dev/null +++ b/Kadane_algorithm.py @@ -0,0 +1,40 @@ +''' +Problem - + Given an array arr of N integers. Find the contiguous sub-array with maximum sum. + Expected Time Complexity: O(N) + Expected Auxiliary Space: O(1) + +Example - + Input: + N = 5 + arr[] = {1,2,3,-2,5} + Output: + 9 +''' + + +# Function to find sub array using kadane algorithm +def sub(arr): + l = len(arr) + i = 0 + sum = 0 + max_sum = 0 + + while i < l: + sum = sum + arr[i] + if sum > max_sum: + max_sum = sum + if sum < 0: + sum = 0 + i +=1 + return max_sum + + +# Main Code +n = int(input("Enter Size of Array : ")) +arr = []*n +arr = list(map(int, input("Enter Array Elements : ").split())) + +max_sum = sub(arr) + +print("sum is : " + str(max_sum)) diff --git a/Keshavg.cpp b/Keshavg.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/Keshavg.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/Krushkal-Algorithm.java b/Krushkal-Algorithm.java new file mode 100644 index 00000000..a56c4117 --- /dev/null +++ b/Krushkal-Algorithm.java @@ -0,0 +1,198 @@ +// Java program for Kruskal's algorithm to +// find Minimum Spanning Tree of a given +// connected, undirected and weighted graph + +import java.io.*; +import java.lang.*; +import java.util.*; + +class Graph { + + // A class to represent a graph edge + class Edge implements Comparable { + int src, dest, weight; + + // Comparator function used for + // sorting edgesbased on their weight + public int compareTo(Edge compareEdge) + { + return this.weight - compareEdge.weight; + } + }; + + // A class to represent a subset for + // union-find + class subset { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // A utility function to find set of an + // element i (uses path compression technique) + int find(subset subsets[], int i) + { + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent + = find(subsets, subsets[i].parent); + + return subsets[i].parent; + } + + // A function that does union of two sets + // of x and y (uses union by rank) + void Union(subset subsets[], int x, int y) + { + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root + // of high rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as + // root and increment its rank by one + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's + // algorithm + void KruskalMST() + { + // This will store the resultant MST + Edge result[] = new Edge[V]; + + // An index variable, used for result[] + int e = 0; + + // An index variable, used for sorted edges + int i = 0; + for (i = 0; i < V; ++i) + result[i] = new Edge(); + + // Step 1: Sort all the edges in non-decreasing + // order of their weight. If we are not allowed to + // change the given graph, we can create a copy of + // array of edges + Arrays.sort(edge); + + // Allocate memory for creating V subsets + subset subsets[] = new subset[V]; + for (i = 0; i < V; ++i) + subsets[i] = new subset(); + + // Create V subsets with single elements + for (int v = 0; v < V; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + } + + i = 0; // Index used to pick next edge + + // Number of edges to be taken is equal to V-1 + while (e < V - 1) { + // Step 2: Pick the smallest edge. And increment + // the index for next iteration + Edge next_edge = edge[i++]; + + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + result[e++] = next_edge; + Union(subsets, x, y); + } + // Else discard the next_edge + } + + // print the contents of result[] to display + // the built MST + System.out.println("Following are the edges in " + + "the constructed MST"); + int minimumCost = 0; + for (i = 0; i < e; ++i) { + System.out.println(result[i].src + " -- " + + result[i].dest + + " == " + result[i].weight); + minimumCost += result[i].weight; + } + System.out.println("Minimum Cost Spanning Tree " + + minimumCost); + } + + // Driver's Code + public static void main(String[] args) + { + + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + Graph graph = new Graph(V, E); + + // add edge 0-1 + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = 10; + + // add edge 0-2 + graph.edge[1].src = 0; + graph.edge[1].dest = 2; + graph.edge[1].weight = 6; + + // add edge 0-3 + graph.edge[2].src = 0; + graph.edge[2].dest = 3; + graph.edge[2].weight = 5; + + // add edge 1-3 + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 15; + + // add edge 2-3 + graph.edge[4].src = 2; + graph.edge[4].dest = 3; + graph.edge[4].weight = 4; + + // Function call + graph.KruskalMST(); + } +} +// OutPut +""" +Following are the edges in the constructed MST +2 -- 3 == 4 +0 -- 3 == 5 +0 -- 1 == 10 +Minimum Cost Spanning Tree: 19 + +""" \ No newline at end of file diff --git a/Kruskal.java b/Kruskal.java new file mode 100644 index 00000000..5ac3d581 --- /dev/null +++ b/Kruskal.java @@ -0,0 +1,120 @@ +import java.util.*; + +class Kruskal { + class Edge implements Comparable { + int src, dest, weight; + + public int compareTo(Edge compareEdge) { + return this.weight - compareEdge.weight; + } + }; + + // Union + class subset { + int parent, rank; + }; + + int vertices, edges; + Edge edge[]; + + // Graph creation + Graph(int v, int e) { + vertices = v; + edges = e; + edge = new Edge[edges]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + int find(subset subsets[], int i) { + if (subsets[i].parent != i) + subsets[i].parent = find(subsets, subsets[i].parent); + return subsets[i].parent; + } + + void Union(subset subsets[], int x, int y) { + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // Applying Krushkal Algorithm + void KruskalAlgo() { + Edge result[] = new Edge[vertices]; + int e = 0; + int i = 0; + for (i = 0; i < vertices; ++i) + result[i] = new Edge(); + + // Sorting the edges + Arrays.sort(edge); + subset subsets[] = new subset[vertices]; + for (i = 0; i < vertices; ++i) + subsets[i] = new subset(); + + for (int v = 0; v < vertices; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + } + i = 0; + while (e < vertices - 1) { + Edge next_edge = new Edge(); + next_edge = edge[i++]; + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); + if (x != y) { + result[e++] = next_edge; + Union(subsets, x, y); + } + } + for (i = 0; i < e; ++i) + System.out.println(result[i].src + " - " + result[i].dest + ": " + result[i].weight); + } + + public static void main(String[] args) { + int vertices = 6; // Number of vertices + int edges = 8; // Number of edges + Graph G = new Graph(vertices, edges); + + G.edge[0].src = 0; + G.edge[0].dest = 1; + G.edge[0].weight = 4; + + G.edge[1].src = 0; + G.edge[1].dest = 2; + G.edge[1].weight = 4; + + G.edge[2].src = 1; + G.edge[2].dest = 2; + G.edge[2].weight = 2; + + G.edge[3].src = 2; + G.edge[3].dest = 3; + G.edge[3].weight = 3; + + G.edge[4].src = 2; + G.edge[4].dest = 5; + G.edge[4].weight = 2; + + G.edge[5].src = 2; + G.edge[5].dest = 4; + G.edge[5].weight = 4; + + G.edge[6].src = 3; + G.edge[6].dest = 4; + G.edge[6].weight = 3; + + G.edge[7].src = 5; + G.edge[7].dest = 4; + G.edge[7].weight = 3; + G.KruskalAlgo(); + } +} \ No newline at end of file diff --git a/Kth Element using HEAP (Priority queue).java b/Kth Element using HEAP (Priority queue).java new file mode 100644 index 00000000..2e7ad92f --- /dev/null +++ b/Kth Element using HEAP (Priority queue).java @@ -0,0 +1,80 @@ +// Java code for k largest/ smallest elements in an array +import java.util.*; + +class GFG { + + // Function to find k largest array element + static void kLargest(int a[], int n, int k) + { + // Implementation using + // a Priority Queue + PriorityQueue pq + = new PriorityQueue(); + + for (int i = 0; i < n; ++i) { + + // Insert elements into + // the priority queue + pq.add(a[i]); + + // If size of the priority + // queue exceeds k + if (pq.size() > k) { + pq.poll(); + } + } + + // Print the k largest element + while (!pq.isEmpty()) { + System.out.print(pq.peek() + " "); + pq.poll(); + } + System.out.println(); + } + + // Function to find k smallest array element + static void kSmallest(int a[], int n, int k) + { + // Implementation using + // a Priority Queue + PriorityQueue pq + = new PriorityQueue( + Collections.reverseOrder()); + + for (int i = 0; i < n; ++i) { + + // Insert elements into + // the priority queue + pq.add(a[i]); + + // If size of the priority + // queue exceeds k + if (pq.size() > k) { + pq.poll(); + } + } + + // Print the k largest element + while (!pq.isEmpty()) { + System.out.print(pq.peek() + " "); + pq.poll(); + } + } + + // Driver Code + public static void main(String[] args) + { + int a[] + = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; + int n = a.length; + int k = 3; + System.out.print(k + " largest elements are : "); + // Function Call + kLargest(a, n, k); + System.out.print(k + " smallest elements are : "); + // Function Call + kSmallest(a, n, k); + } +} + +// This code is contributed by Harsh diff --git a/Lab4ComplexNum.cpp b/Lab4ComplexNum.cpp new file mode 100644 index 00000000..c11fce31 --- /dev/null +++ b/Lab4ComplexNum.cpp @@ -0,0 +1,81 @@ +/* Implement a class complex which represent the complex number data type.Implement the following operations: +1)Default Constuctor (including a default constuctor which creates the complex number 0+0i) +2)Paramatrised Constuctor (3+5i) +3)Copy Constuctor : use this to display the same complex number as of part 2 */ + +#include +using namespace std; +class complex +{ + int real,imaginary; + public: + complex() + { + real=imaginary=0; + } + void display() + { + cout< +using namespace std; +class complex +{ + int real,imaginary; + public: + complex(int r,int i) + { + real=3; + imaginary=5; + } + void display() + { + cout< +using namespace std; +class complex +{ + int real,imaginary; + public: + complex(int r,int i) + { + real=r; + imaginary=i; + } + complex(complex &c) + { + real=c.real; + imaginary=c.imaginary; + } + void display() + { + cout< num = new LinkedHashSet<>(); + + num.add(9); + num.add(2); + num.add(4); + System.out.println("LinkedHashSet: " + num); + + LinkedHashSet numbers = new LinkedHashSet<>(); + + numbers.addAll(num); + numbers.add(8); + System.out.println("New LinkedHashSet: " + numbers); + } +} diff --git a/LinkedListInsertion.java b/LinkedListInsertion.java new file mode 100644 index 00000000..63d9b17f --- /dev/null +++ b/LinkedListInsertion.java @@ -0,0 +1,43 @@ +package com.example.demo; + +import java.util.*; + +class example{ + public static void main(String[] args){ + + // create linkedlist + LinkedList ll = new LinkedList<>(); + Scanner sc = new Scanner(System.in); + + // Add elements to LinkedList + System.out.println("Options:"); + System.out.println("1. Enter element.\n2. Exit."); + System.out.println("Enter choice: "); + int ch = 1; + ch = Integer.parseInt(sc.nextLine()); + do{ + switch(ch){ + case 1: + //insert the element. + System.out.println("Enter the element: "); + String element = sc.nextLine(); + ll.add(element); + break; + + case 2: + //exit the loop, + ch=2; + System.out.println("Ending insertion into linked list..."); + break; + + default: + //invalid choice: + System.out.println("Enter a valid input!"); + break; + } + System.out.println("Enter choice: "); + ch = Integer.parseInt(sc.nextLine()); + }while(ch!=2); + System.out.println("LinkedList: " + ll); + } +} \ No newline at end of file diff --git a/LinkedListInsertions.java b/LinkedListInsertions.java new file mode 100644 index 00000000..d0cb10ad --- /dev/null +++ b/LinkedListInsertions.java @@ -0,0 +1,97 @@ +package com.anurag; + +public class LL { + + private Node head; + private Node tail; + + private int size; + + public LL() { + this.size = 0; + } + + + //-------------------INSERTION---------------->>>>>>>>> + //INSERT ELEMENT AT FIRST + public void insertFirst(int val){ + Node node = new Node(val); + node.next = head; + head = node; + + if(tail == null){ //if it's true it means that first element is being added + tail = head; + } + + size += 1; + } + + //INSERT ELEMENT AT LAST + public void insertLast(int val){ + if(tail == null){ //IF LIST IS EMPTY INSERT AT FIRST + insertFirst(val); + return; + } + Node node = new Node(val); + tail.next = node; + tail = node; + + size++; + } + + //INSERT ELEMENT AT A PARTICULAR INDEX + public void insert(int val, int index){ + if(index == 0){ + insertFirst(val); + return; + } + + if(index == size){ + insertLast(val); + return; + } + + Node temp = head; + for (int i = 1; i < index; i++) { + temp = temp.next; + } + + Node node = new Node(val, temp.next); //pass the value of new node and it's next element will be current.next i.e. temp.next + temp.next = node; + + size++; + } + + + //QUESTION 1 + //INSERT USING RECURSION + public void insertRec(int val, int index){ + head = insertRec(val, index, head); + } + private Node insertRec(int val, int index, Node node){ + if(index == 0){ + Node temp = new Node(val, node); //next of the temp node will be the current node + size++; + return temp; + } + + node.next = insertRec(val, index-1, node.next); + return node; + } + + private class Node{ + private int value; + private Node next; + + public Node(int value) { + this.value = value; + } + + public Node(int value, Node next){ + this.value = value; + this.next = next; + } + + } + +} diff --git a/ListIterator.java b/ListIterator.java new file mode 100644 index 00000000..cc00ff56 --- /dev/null +++ b/ListIterator.java @@ -0,0 +1,23 @@ +import java.util.ArrayList; +import java.util.ListIterator; + +class Main { + public static void main(String[] args) { + + ArrayList nums = new ArrayList<>(); + nums.add(5); + nums.add(6); + nums.add(7); + System.out.println("ArrayList: " + nums); + + ListIterator iterate = nums.listIterator(); + + int num1 = iterate.next(); + System.out.println("Next Element: " + num1); + + int index1 = iterate.nextIndex(); + System.out.println("Position of Next Element: " + index1); + + System.out.println("Is there any next element? " + iterate.hasNext()); + } +} diff --git a/Longest_Common_Subsequence.java b/Longest_Common_Subsequence.java new file mode 100644 index 00000000..f5482106 --- /dev/null +++ b/Longest_Common_Subsequence.java @@ -0,0 +1,45 @@ +/*package whatever //do not write package name here */ +import java.io.*; + +class Solution +{ + +// A Top-Down DP implementation of LCS problem + +// Returns length of LCS for X[0..m-1], Y[0..n-1] +static int lcs(String X,String Y,int m,int n,int[][] dp){ + + if (m == 0 || n == 0) + return 0; + + if (dp[m][n] != -1) + return dp[m][n]; + + if(X.charAt(m - 1) == Y.charAt(n - 1)){ + dp[m][n] = 1 + lcs(X, Y, m - 1, n - 1, dp); + return dp[m][n]; + } + + dp[m][n] = Math.max(lcs(X, Y, m, n - 1, dp),lcs(X, Y, m - 1, n, dp)); + return dp[m][n]; +} + +// Drivers code +public static void main(String args[]){ + + String X = "AGGTAB"; + String Y = "GXTXAYB"; + + int m = X.length(); + int n = Y.length(); + int[][] dp = new int[m + 1][n + 1]; + for(int i=0;i= n || j < 0 || j >= n) + return 0; + + if (dp[i][j] != -1) + return dp[i][j]; + + int x = Integer.MIN_VALUE, y = Integer.MIN_VALUE, + z = Integer.MIN_VALUE, w = Integer.MIN_VALUE; + + if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) + x = dp[i][j] = 1 + + findLongestFromACell(i, j + 1, mat, dp); + + if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) + y = dp[i][j] = 1 + + findLongestFromACell(i, j - 1, mat, dp); + + if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) + z = dp[i][j] = 1 + + findLongestFromACell(i - 1, j, mat, dp); + + if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) + w = dp[i][j] = 1 + + findLongestFromACell(i + 1, j, mat, dp); + + return dp[i][j] = Math.max( + x, + Math.max(y, Math.max(z, Math.max(w, 1)))); + } + + static int finLongestOverAll(int mat[][]) { + + int result = 1; + + int[][] dp = new int[n][n]; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + dp[i][j] = -1; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (dp[i][j] == -1) + findLongestFromACell(i, j, mat, dp); + + result = Math.max(result, dp[i][j]); + } + } + + return result; + } + + public static void main(String[] args) { + int mat[][] = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; + System.out.println("Length of the longest path is " + + finLongestOverAll(mat)); + } +} diff --git a/Make_Change_Problem.java b/Make_Change_Problem.java new file mode 100644 index 00000000..4a792dd9 --- /dev/null +++ b/Make_Change_Problem.java @@ -0,0 +1,29 @@ +public class Make_Change_Problem{ + static int max = 100; + + static int[] ans = new int[max]; + public static void main(String[] args){ + int coins[] = {25,20,10,5}; + int value = 105; + + int minCount = findMinCoins(coins,value); + + System.out.println("Total coins Needed = " + minCount); + + } + + public static int findMinCoins(int[] coins,int val){ + int count = 0; + + for(int i=0;i=coins[i]){ + val -= coins[i]; + ans[count++] = coins[i]; + } + if(val == 0) + break; + } + + return count; + } +} \ No newline at end of file diff --git a/Maximum_product_subarray.cpp b/Maximum_product_subarray.cpp new file mode 100644 index 00000000..e31bd116 --- /dev/null +++ b/Maximum_product_subarray.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int maxProduct(vector& nums) { + int max_pro=1; + int curr_pro=1; + for(int i=0;i Right -> Up -> Left, if the path doesn't work, then backtrack + /** + * + * @Description + * @author OngLipWei + * @date Jun 23, 202111:36:14 AM + * @param map The maze + * @param i x coordinate of your ball(target) + * @param j y coordinate of your ball(target) + * @return If we did find a path for the ball,return true,else false + */ + public static boolean setWay(int[][] map, int i, int j) { + if (map[6][5] == 2) {// means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : down -> right -> up -> left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay(map, i + 1, j)) { // go down + return true; + } else if (setWay(map, i, j + 1)) { // go right + return true; + } else if (setWay(map, i - 1, j)) { // go up + return true; + } else if (setWay(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + + } + + // Here is another move strategy for the ball: up->right->down->left + public static boolean setWay2(int[][] map, int i, int j) { + if (map[6][5] == 2) {// means the ball find its path, ending condition + return true; + } + if (map[i][j] == 0) { // if the ball haven't gone through this point + // then the ball follows the move strategy : up->right->down->left + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + if (setWay2(map, i - 1, j)) { // go up + return true; + } else if (setWay2(map, i, j + 1)) { // go right + return true; + } else if (setWay2(map, i + 1, j)) { // go down + return true; + } else if (setWay2(map, i, j - 1)) { // go left + return true; + } else { + // means that the current point is the dead end, the ball cannot proceed, set + // the current point to 3 and return false, the backtraking will start, it will + // go to the previous step and check for feasible path again + map[i][j] = 3; + return false; + } + + } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the + // ball cannot hit the wall, cannot go to the path that has gone though before, + // and cannot head to deadend. + return false; + } + + } + +} diff --git a/MergeKSortedLists b/MergeKSortedLists new file mode 100644 index 00000000..31e47465 --- /dev/null +++ b/MergeKSortedLists @@ -0,0 +1,43 @@ +class Solution { + public ListNode mergeKLists(ListNode[] lists) { + if(lists.length==0) + return null; + ListNode node=sort(lists,0,lists.length-1); + return node; + } + public ListNode sort(ListNode [] arr,int l,int r){ + if(l==r) + return arr[l]; + int mid=(l+r)/2; + ListNode a=sort(arr,l,mid); + ListNode b=sort(arr,mid+1,r); + return merge(a,b); + } + + public ListNode merge(ListNode a,ListNode b){ + ListNode head=new ListNode(); + ListNode n=head; + while(a!=null && b!=null){ + if(a.val 2(T/2) + N == O(N logN) By Master's Theorem. + OR + It is In Complete Binary Tree form so Complexity of + Complete Binary tree is => log(N) & it is Performing N step at every Mode + so O(n*LogN ) */ +public class MergeSorting { + static int currStep=0; + + static void MergeSort(int []Array,int left,int right) { + if(left < right){ + int mid = (left + right)/2; + MergeSort(Array,left,mid); + MergeSort(Array,mid+1,right); + Merge(Array,left,mid,right); + } + } + static void Merge(int []Array,int left,int mid,int right) { + // Dummy Array for References + int []b=new int[left+right]; + int i=left; + int j=mid+1; + + int k = left; // For Dummy Array + + // if element of First Partition Array is smaller than Dummy == Array, + // if element of Second Partition Array is smaller than Dummy == Array. + while(i<=mid&&j<=right){ + if(Array[i]mid){ + while(j heap; + public int size; + + public MinHeap() { + this.heap = new ArrayList(); + this.heap.add(null); + this.size = 0; + } + + public void add(int value) { + this.heap.add(value); + this.size += 1; + System.out.println("Adding: " + value); + System.out.println(this.heap); + this.bubbleUp(); + } + + public int popMin() { + if (this.size == 0) { + throw new Error("Heap is empty!"); + } + System.out.println("Swap min element " + this.heap.get(1) + " and last element " + this.heap.get(this.size)); + this.swap(1, this.size); + int min = this.heap.remove(this.size); + System.out.println("Removed from the heap: " + min); + System.out.println(this.heap); + this.size--; + this.heapify(); + return min; + } + + + private void bubbleUp() { + int current = this.size; + while (current > 1 && this.heap.get(this.getParent(current)) > this.heap.get(current)) { + System.out.println("Swap index " + current + " with index " + this.getParent(current)); + System.out.println(this.heap); + this.swap(current, this.getParent(current)); + current = this.getParent(current); + } + } + + private void heapify() { + int current = 1; + int leftChild = this.getLeft(current); + int rightChild = this.getRight(current); + while (this.canSwap(current, leftChild, rightChild)) { + if (this.exists(leftChild) && this.exists(rightChild)) { + if (this.heap.get(leftChild) < this.heap.get(rightChild)) { + this.swap(current, leftChild); + current = leftChild; + } else { + this.swap(current, rightChild); + current = rightChild; + } + } else { + this.swap(current, leftChild); + current = leftChild; + } + leftChild = this.getLeft(current); + rightChild = this.getRight(current); + + } + } + + + + private void swap(int a, int b) { + int temp = this.heap.get(b); + this.heap.set(b, this.heap.get(a)); + this.heap.set(a, temp); + } + + private boolean exists(int index) { + return index <= this.size; + } + + private boolean canSwap(int current, int leftChild, int rightChild) { + return (this.exists(leftChild) && (this.heap.get(current) > this.heap.get(leftChild))) + || (this.exists(rightChild) && (this.heap.get(current) > this.heap.get(rightChild))); + } + + public int getParent(int current) { + return (int) Math.floor(current / 2); + } + + public int getLeft(int current) { + return current * 2; + } + + public int getRight(int current) { + return (current * 2) + 1; + } + + + public static void main(String[] args) { + MinHeap minHeap = new MinHeap(); + Random r = new Random(); + for (int i = 0; i < 6; i++) { + int int_random = r.nextInt(40); + minHeap.add(int_random); + } + System.out.println("--------------"); + System.out.println("BUBBLED UP: " + minHeap.heap); + + // Remove minimum value multiple times + for (int i = 0; i < 6; i++) { + System.out.println("--------------"); + minHeap.popMin(); + System.out.println("HEAPIFIED: " + minHeap.heap); + } + } +} \ No newline at end of file diff --git a/MinimumSumPartition.java b/MinimumSumPartition.java new file mode 100644 index 00000000..fc0d87a4 --- /dev/null +++ b/MinimumSumPartition.java @@ -0,0 +1,89 @@ +package com.thealgorithms.dynamicprogramming; + +// Partition a set into two subsets such that the difference of subset sums is minimum + +/* +Input: arr[] = {1, 6, 11, 5} +Output: 1 +Explanation: +Subset1 = {1, 5, 6}, sum of Subset1 = 12 +Subset2 = {11}, sum of Subset2 = 11 + +Input: arr[] = {36, 7, 46, 40} +Output: 23 +Explanation: +Subset1 = {7, 46} ; sum of Subset1 = 53 +Subset2 = {36, 40} ; sum of Subset2 = 76 + */ +public class MinimumSumPartition { + + public static int subSet(int[] arr) { + int n = arr.length; + int sum = getSum(arr); + boolean[][] dp = new boolean[n + 1][sum + 1]; + for (int i = 0; i <= n; i++) { + dp[i][0] = true; + } + for (int j = 0; j <= sum; j++) { + dp[0][j] = false; + } + + // fill dp array + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= sum; j++) { + if (arr[i - 1] < j) { + dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i - 1][j]; + } else if (arr[i - 1] == j) { + dp[i][j] = true; + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + + // fill the index array + int[] index = new int[sum]; + int p = 0; + for (int i = 0; i <= sum / 2; i++) { + if (dp[n][i]) { + index[p++] = i; + } + } + + return getMin(index, sum); + } + + /** + * Calculate sum of array elements + * + * @param arr the array + * @return sum of given array + */ + public static int getSum(int[] arr) { + int sum = 0; + for (int temp : arr) { + sum += temp; + } + return sum; + } + + public static int getMin(int[] arr, int sum) { + if (arr.length == 0) { + return 0; + } + int min = Integer.MAX_VALUE; + for (int temp : arr) { + min = Math.min(min, sum - 2 * temp); + } + return min; + } + + /** + * Driver Code + */ + public static void main(String[] args) { + assert subSet(new int[] { 1, 6, 11, 5 }) == 1; + assert subSet(new int[] { 36, 7, 46, 40 }) == 23; + assert subSet(new int[] { 1, 2, 3, 9 }) == 3; + } +} \ No newline at end of file diff --git a/MoveAllNegativeOneSide.cpp b/MoveAllNegativeOneSide.cpp new file mode 100644 index 00000000..6a42ba76 --- /dev/null +++ b/MoveAllNegativeOneSide.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; +void move(int a[], int n) +{int j=0; +for(int i=0;i +using namespace std; +int grid[10][10]; + +//print the solution +void print(int n) { + for (int i = 0;i <= n-1; i++) { + for (int j = 0;j <= n-1; j++) { + + cout <= 0 && j >= 0; i--,j--) { + if (grid[i][j]) { + return false; + } + } + //check for upper right diagonal + for (int i = row, j = col; i >= 0 && j < n; j++, i--) { + if (grid[i][j]) { + return false; + } + } + return true; +} + +//function to find the position for each queen +//row is indicates the queen no. and col represents the possible positions +bool solve (int n, int row) { + if (n == row) { + print(n); + return true; + } + //variable res is use for possible backtracking + bool res = false; + for (int i = 0;i <=n-1;i++) { + if (isSafe(i, row, n)) { + grid[row][i] = 1; + //recursive call solve(n, row+1) for next queen (row+1) + res = solve(n, row+1) || res;//if res ==false then backtracking will occur + //by assigning the grid[row][i] = 0 + + grid[row][i] = 0; + } + } + return res; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n; + cout<<"Enter the number of queen"<> n; diff --git a/N-Queen1(SFS).cpp b/N-Queen1(SFS).cpp new file mode 100644 index 00000000..f04666da --- /dev/null +++ b/N-Queen1(SFS).cpp @@ -0,0 +1,87 @@ +//program to solve the n queen problem +//grid[][] is represent the 2-d array with value(0 and 1) for grid[i][j]=1 means queen i are placed at j column. +//we can take any number of queen , for this time we take the atmost 10 queen (grid[10][10]). +#include +using namespace std; +int grid[10][10]; + +//print the solution +void print(int n) { + for (int i = 0;i <= n-1; i++) { + for (int j = 0;j <= n-1; j++) { + + cout <= 0 && j >= 0; i--,j--) { + if (grid[i][j]) { + return false; + } + } + //check for upper right diagonal + for (int i = row, j = col; i >= 0 && j < n; j++, i--) { + if (grid[i][j]) { + return false; + } + } + return true; +} + +//function to find the position for each queen +//row is indicates the queen no. and col represents the possible positions +bool solve (int n, int row) { + if (n == row) { + print(n); + return true; + } + //variable res is use for possible backtracking + bool res = false; + for (int i = 0;i <=n-1;i++) { + if (isSafe(i, row, n)) { + grid[row][i] = 1; + //recursive call solve(n, row+1) for next queen (row+1) + res = solve(n, row+1) || res;//if res ==false then backtracking will occur + //by assigning the grid[row][i] = 0 + + grid[row][i] = 0; + } + } + return res; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n; + cout<<"Enter the number of queen"<> n; + for (int i = 0;i < n;i++) { + for (int j = 0;j < n;j++) { + grid[i][j] = 0; + } + } + bool res = solve(n, 0); + if(res == false) { + cout << -1 << endl; //if there is no possible solution + } else { + cout << endl; + } + return 0; +} diff --git a/N-Queen1(SSF).cpp b/N-Queen1(SSF).cpp new file mode 100644 index 00000000..182b94fa --- /dev/null +++ b/N-Queen1(SSF).cpp @@ -0,0 +1,87 @@ +//MY Program to solve the N-Queen problem +//grid[][] is represent the 2-d array with value(0 and 1) for grid[i][j]=1 means queen i are placed at j column. +//we can take any number of queen , for this time we take the atmost 10 queen (grid[10][10]). +#include +using namespace std; +int grid[10][10]; + +//print the solution +void print(int n) { + for (int i = 0;i <= n-1; i++) { + for (int j = 0;j <= n-1; j++) { + + cout <= 0 && j >= 0; i--,j--) { + if (grid[i][j]) { + return false; + } + } + //check for upper right diagonal + for (int i = row, j = col; i >= 0 && j < n; j++, i--) { + if (grid[i][j]) { + return false; + } + } + return true; +} + +//function to find the position for each queen +//row is indicates the queen no. and col represents the possible positions +bool solve (int n, int row) { + if (n == row) { + print(n); + return true; + } + //variable res is use for possible backtracking + bool res = false; + for (int i = 0;i <=n-1;i++) { + if (isSafe(i, row, n)) { + grid[row][i] = 1; + //recursive call solve(n, row+1) for next queen (row+1) + res = solve(n, row+1) || res;//if res ==false then backtracking will occur + //by assigning the grid[row][i] = 0 + + grid[row][i] = 0; + } + } + return res; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n; + cout<<"Enter the number of queen"<> n; + for (int i = 0;i < n;i++) { + for (int j = 0;j < n;j++) { + grid[i][j] = 0; + } + } + bool res = solve(n, 0); + if(res == false) { + cout << -1 << endl; //if there is no possible solution + } else { + cout << endl; + } + return 0; +} diff --git a/NMS-python.py b/NMS-python.py new file mode 100644 index 00000000..1ec51fa6 --- /dev/null +++ b/NMS-python.py @@ -0,0 +1,21 @@ +import telepot +import pyping + + +def ping_server(ip): + response = pyping.ping(ip) + if response.ret_code == 0: + send_telegram('Server {} up!'.format(ip)) + else: + send_telegram('Server {} down!'.format(ip)) + + +def send_telegram(pesan): + telegram_token = 'your_telegram_token' + chat_id = 'your_chat_id' + bot = telepot.Bot(telegram_token) + bot.sendMessage(chat_id, pesan) + + +if __name__ == '__main__': + ping_server('your_server') \ No newline at end of file diff --git a/NQueens.java b/NQueens.java new file mode 100644 index 00000000..fb0138d1 --- /dev/null +++ b/NQueens.java @@ -0,0 +1,111 @@ +package com.thealgorithms.backtracking; + +import java.util.ArrayList; +import java.util.List; + +/** + * Problem statement: Given a N x N chess board. Return all arrangements in + * which N queens can be placed on the board such no two queens attack each + * other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....", + * "...Q..", ".....Q", "Q.....", "..Q...", "....Q." + *

+ * Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.." + *

+ * Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..." + *

+ * Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...." + * + * Solution: Brute Force approach: + * + * Generate all possible arrangement to place N queens on N*N board. Check each + * board if queens are placed safely. If it is safe, include arrangement in + * solution set. Otherwise ignore it + * + * Optimized solution: This can be solved using backtracking in below steps + * + * Start with first column and place queen on first row Try placing queen in a + * row on second column If placing second queen in second column attacks any of + * the previous queens, change the row in second column otherwise move to next + * column and try to place next queen In case if there is no rows where a queen + * can be placed such that it doesn't attack previous queens, then go back to + * previous column and change row of previous queen. Keep doing this until last + * queen is not placed safely. If there is no such way then return an empty list + * as solution + */ +public class NQueens { + + public static void main(String[] args) { + placeQueens(1); + placeQueens(2); + placeQueens(3); + placeQueens(4); + placeQueens(5); + placeQueens(6); + } + + public static void placeQueens(final int queens) { + List> arrangements = new ArrayList>(); + getSolution(queens, arrangements, new int[queens], 0); + if (arrangements.isEmpty()) { + System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens); + } else { + System.out.println("Arrangement for placing " + queens + " queens"); + } + arrangements.forEach(arrangement -> { + arrangement.forEach(row -> System.out.println(row)); + System.out.println(); + }); + } + + /** + * This is backtracking function which tries to place queen recursively + * + * @param boardSize: size of chess board + * @param solutions: this holds all possible arrangements + * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param columnIndex: This is the column in which queen is being placed + */ + private static void getSolution(int boardSize, List> solutions, int[] columns, int columnIndex) { + if (columnIndex == boardSize) { + // this means that all queens have been placed + List sol = new ArrayList(); + for (int i = 0; i < boardSize; i++) { + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < boardSize; j++) { + sb.append(j == columns[i] ? "Q" : "."); + } + sol.add(sb.toString()); + } + solutions.add(sol); + return; + } + + // This loop tries to place queen in a row one by one + for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) { + columns[columnIndex] = rowIndex; + if (isPlacedCorrectly(columns, rowIndex, columnIndex)) { + // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column + getSolution(boardSize, solutions, columns, columnIndex + 1); + } + } + } + + /** + * This function checks if queen can be placed at row = rowIndex in column = + * columnIndex safely + * + * @param columns: columns[i] = rowId where queen is placed in ith column. + * @param rowIndex: row in which queen has to be placed + * @param columnIndex: column in which queen is being placed + * @return true: if queen can be placed safely false: otherwise + */ + private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { + for (int i = 0; i < columnIndex; i++) { + int diff = Math.abs(columns[i] - rowIndex); + if (diff == 0 || columnIndex - i == diff) { + return false; + } + } + return true; + } +} diff --git a/Number is Palindrome or Not.java b/Number is Palindrome or Not.java new file mode 100644 index 00000000..395b5fa7 --- /dev/null +++ b/Number is Palindrome or Not.java @@ -0,0 +1,26 @@ +import java.util.Scanner; + class expalindrome +{ +public static void main(String args[]) +{ +int x,number, y=0,temp=0; +Scanner s=new Scanner(System.in); +System.out.println("Enter any number: "); +number=s.nextInt(); +x=number; +while(number>0) +{ +x=number%10; +number=number/10; +temp=temp*10+x; +} +if(temp==y) +{ +System.out.println("Number is Palindrome"); +} +else +{ +System.out.println("not Palindrome"); +} +} +} diff --git a/NumberFrequencyofArray.java b/NumberFrequencyofArray.java new file mode 100644 index 00000000..b28a969c --- /dev/null +++ b/NumberFrequencyofArray.java @@ -0,0 +1,30 @@ +public class Frequency { + public static void main(String[] args) { + //Initialize array + int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1}; + //Array fr will store frequencies of element + int [] fr = new int [arr.length]; + int visited = -1; + for(int i = 0; i < arr.length; i++){ + int count = 1; + for(int j = i+1; j < arr.length; j++){ + if(arr[i] == arr[j]){ + count++; + //To avoid counting same element again + fr[j] = visited; + } + } + if(fr[i] != visited) + fr[i] = count; + } + + + System.out.println("---------------------------------------"); + System.out.println(" Element | Frequency"); + System.out.println("---------------------------------------"); + for(int i = 0; i < fr.length; i++){ + if(fr[i] != visited) + System.out.println(" " + arr[i] + " | " + fr[i]); + } + System.out.println("----------------------------------------"); + }} diff --git a/Number_guessing_game.java b/Number_guessing_game.java new file mode 100644 index 00000000..fca0218f --- /dev/null +++ b/Number_guessing_game.java @@ -0,0 +1,66 @@ +import java.util.Scanner; + +public class GFG { + + public static void + guessingNumberGame() + { + Scanner sc = new Scanner(System.in); + + int number = 1 + (int)(100 + * Math.random()); + + int K = 5; + + int i, guess; + + System.out.println( + "A number is chosen" + + " between 1 to 100." + + "Guess the number" + + " within 5 trials."); + + for (i = 0; i < K; i++) { + + System.out.println( + "Guess the number:"); + + guess = sc.nextInt(); + + if (number == guess) { + System.out.println( + "Congratulations!" + + " You guessed the number."); + break; + } + else if (number > guess + && i != K - 1) { + System.out.println( + "The number is " + + "greater than " + guess); + } + else if (number < guess + && i != K - 1) { + System.out.println( + "The number is" + + " less than " + guess); + } + } + + if (i == K) { + System.out.println( + "You have exhausted" + + " K trials."); + + System.out.println( + "The number was " + number); + } + } + + public static void + main(String arg[]) + { + + guessingNumberGame(); + } +} diff --git a/OccuranceOfEachCharacter.java b/OccuranceOfEachCharacter.java new file mode 100644 index 00000000..781c1f49 --- /dev/null +++ b/OccuranceOfEachCharacter.java @@ -0,0 +1,70 @@ +package coding; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +public class OccuranceOfEachCharacter extends BaseTestNg{ + String str = "welcome to automation"; + int count =0; + + @Test(priority=1) + public void main() { + char[] char_array =str.toCharArray(); + Map charCounter=new HashMap(); + for (char ch : char_array) { + if(charCounter.containsKey(ch)){ + charCounter.put(ch, charCounter.get(ch)+1); + } + else{ + charCounter.put(ch, 1); + } + } + System.out.println(charCounter); + } + + @Test(priority=2) + public void occurance() { + String string=""; + int temp =0; + Map map =new LinkedHashMap(); + for (int i = 0; i < str.length(); i++) { + map.put(temp, ""+str.charAt(i)); + temp++; + } + for (int eachChar : map.keySet()) { + count=0; + string =map.get(eachChar); + for (Integer eachKey : map.keySet()) { + if (string.equals(map.get(eachKey))) { + count++; + } + } + System.out.println(map.get(eachChar)+"-->"+count); + } + } + + @Test(priority=3) + public void occuranceOfString() { + for (int j = 0; j < str.length(); j++) { + count = 0; + char c = str.charAt(j); + for (int i = 0; i < str.length(); i++) { + if (c == str.charAt(i)) { + count++; + } + } + System.out.println(c + " occurs " + count + " times in " + str); // you can store this in Map and print for better solution + } + } + + + +} + + + + + diff --git a/OopsConcept.java b/OopsConcept.java new file mode 100644 index 00000000..5902834a --- /dev/null +++ b/OopsConcept.java @@ -0,0 +1,21 @@ +class Student{ + int rollno; + String name; + float fee; + Student(int roll,String names,float fees){ + rollno=roll; + name=names; + fee=fees; + } + void display(){ + System.out.println(rollno+" "+name+" "+fee); + } +} +class OopsConcept{ + public static void main(String args[]){ + Student s1=new Student(111,"ankit",5000f); + Student s2=new Student(112,"sumit",6000f); + s1.display(); + s2.display(); + } +} diff --git a/Overloading.java b/Overloading.java new file mode 100644 index 00000000..12e2fbd3 --- /dev/null +++ b/Overloading.java @@ -0,0 +1,30 @@ +// Java program to demonstrate working of method +// overloading in Java + +public class Sum { + + // Overloaded sum(). This sum takes two int parameters + public int sum(int x, int y) { return (x + y); } + + // Overloaded sum(). This sum takes three int parameters + public int sum(int x, int y, int z) + { + return (x + y + z); + } + + // Overloaded sum(). This sum takes two double + // parameters + public double sum(double x, double y) + { + return (x + y); + } + + // Driver code + public static void main(String args[]) + { + Sum s = new Sum(); + System.out.println(s.sum(10, 20)); + System.out.println(s.sum(10, 20, 30)); + System.out.println(s.sum(10.5, 20.5)); + } +} diff --git a/PalinNumber.java b/PalinNumber.java new file mode 100644 index 00000000..77922bae --- /dev/null +++ b/PalinNumber.java @@ -0,0 +1,24 @@ +import java.util.*; +class PalinNumber { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("enter starting and ending point to find palindrome in between"); + int m=sc.nextInt(); + int n=sc.nextInt(); + System.out.println("palindrome numbers..."); + for(int i=m;i<=n;i++) + { + int x=i; + int s=0; + while(x!=0) + { + s=s*10+(x%10); + x=x/10; + } + if(i==s) + { + System.out.println(i); + } + } + } +} \ No newline at end of file diff --git a/PalindromeNumber.java b/PalindromeNumber.java new file mode 100644 index 00000000..dc3ad552 --- /dev/null +++ b/PalindromeNumber.java @@ -0,0 +1,17 @@ +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"); +} +} diff --git a/Pattern.java b/Pattern.java new file mode 100644 index 00000000..bc9dd90e --- /dev/null +++ b/Pattern.java @@ -0,0 +1,35 @@ +import java.util.Scanner; +public class MainClass +{ + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + + //Taking rows value from the user + + System.out.println("How many rows you want in this pattern?"); + + int rows = sc.nextInt(); + + System.out.println("Here is your pattern....!!!"); + + for (int i=1; i<= rows ; i++) + { + for (int j = i; j < rows ; j++) { + System.out.print(" "); + } + for (int k = 1; k <= (2*i -1) ;k++) { + if( k==1 || i == rows || k==(2*i-1)) { + System.out.print("*"); + } + else { + System.out.print(" "); + } + } + System.out.println(""); + } + + //Close the resources + sc.close(); + } +} diff --git a/Patterns.cpp b/Patterns.cpp new file mode 100644 index 00000000..bafbad83 --- /dev/null +++ b/Patterns.cpp @@ -0,0 +1,193 @@ +/* +Approach method : - +1. No of lines = No of rows = No of times outer loop will run +2. Identify for every row no + *How many columns are there + *Types of elements in columns +3. What do you need to print +*/ + +#include +using namespace std; + +void pattern1(int noOfLines){ + for(int row = 0; row < noOfLines; row++){ + for (int column = 0; column < noOfLines; column++) + { + cout<<"*"; + } + cout<= row; column-- + { + cout<<"*"; + } + cout<>noOfLines; + cout<<"\n"<<" Patterns are "<0; i--){ + for (int j = 0; j=18)&&(age<=100)) + { + System.out.println("Congratulation "+name+", You are eligible for Voting"); + } + else + { + System.out.println("Sorry "+name+", You are not eligible for voting"); + } + } +} diff --git a/Project1.py b/Project1.py new file mode 100644 index 00000000..52546412 --- /dev/null +++ b/Project1.py @@ -0,0 +1,34 @@ +import random +print("\n\t\t\t******* Game of Snake, Water and Gun *******\n") +print(" There are some rules in this game.These are:-") +print("\tRule no.1:- You need to choose snake, water or gun") +print('\tRule no.2:- To choose snake type 1, to choose water type 2 and to choose gun type 3') +print("\tRule no.3:- If you want to quit type 5") +print("\n\t\t\t Ok then, Have fun!") + +a = True +while a == True: + def game(comp,user): + if comp == 3 and user == 2: + print(f"You win because the computer choose Gun") + elif comp == 2 and user == 3: + print(f"You lose because the computer choose Water") + elif comp == 3 and user == 1: + print(f"You Lose because the computer choose gun") + elif comp == 1 and user == 3: + print(f"You Win because the computer choose Snake") + elif comp == 1 and user == 2: + print(f"You Lose because the computer choose Snake") + elif comp == 2 and user == 1: + print(f"You Win because the computer choose Water") + elif user == 5: + print("\n\t\tYou quit the game.Thanks for Playing this game!") + quit() + elif user == comp : + print("The game is draw") + else: + print("Warring: Donot enter any wrong number.Please check the rules again") + + comp = random.randint(1, 3) + user = int(input('Your turn: ')) + game(comp, user) \ No newline at end of file diff --git a/PythonCalculator.py b/PythonCalculator.py new file mode 100644 index 00000000..2803b538 --- /dev/null +++ b/PythonCalculator.py @@ -0,0 +1,64 @@ +# Python Calculator +# Created by Amey Karan + + +import math + +print("Welcome to Python Calculator!") +print("What do you want to do today?") +print("1. Addition") +print("2. Subtraction") +print("3. Multiplication") +print("4. Division") +print("5. Highest Common Factor (HCF)") +print("6. Least Common Multiple (LCM)") + +while True: + choice = input("Enter your choice: ") + if choice in ["1", "2", "3", "4", "5", "6"]: + break + else: + print("Please select a valid choice") + +print() +while True: + num1 = input("Enter the first number: ") + try: + num1 = int(num1) + break + except: + print("Enter a valid number!") + +while True: + num2 = input("Enter the second number: ") + try: + num2 = int(num2) + break + except: + print("Enter a valid number!") + + +print() + +choice = int(choice) +if choice == 1: + print(f"{num1} + {num2} = {num1 + num2}") + +elif choice == 2: + print(f"{num1} - {num2} = {num1 + num2}") + +elif choice == 3: + print(f"{num1} * {num2} = {num1 + num2}") + +elif choice == 4: + print(f"{num1} ÷ {num2} = {num1 + num2}") + print(f"Quotient: {num1 // num2}") + print(f"Remainder: {num1 % num2}") + +elif choice == 5: + print(f"HCF({num1}, {num2}) = {math.gcd(num1, num2)}") + +elif choice == 6: + print(f"LCM({num1}, {num2}) = {math.lcm(num1, num2)}") + +print("Thank you for choosing me. Hope to see you soon!") diff --git a/Queue.java b/Queue.java new file mode 100644 index 00000000..1e5d11b1 --- /dev/null +++ b/Queue.java @@ -0,0 +1,121 @@ +public class Queue { + int SIZE = 5; + int items[] = new int[SIZE]; + int front, rear; + + Queue() { + front = -1; + rear = -1; + } + + // check if the queue is full + boolean isFull() { + if (front == 0 && rear == SIZE - 1) { + return true; + } + return false; + } + + // check if the queue is empty + boolean isEmpty() { + if (front == -1) + return true; + else + return false; + } + + // insert elements to the queue + void enQueue(int element) { + + // if queue is full + if (isFull()) { + System.out.println("Queue is full"); + } + else { + if (front == -1) { + // mark front denote first element of queue + front = 0; + } + + rear++; + // insert element at the rear + items[rear] = element; + System.out.println("Insert " + element); + } + } + + // delete element from the queue + int deQueue() { + int element; + + // if queue is empty + if (isEmpty()) { + System.out.println("Queue is empty"); + return (-1); + } + else { + // remove element from the front of queue + element = items[front]; + + // if the queue has only one element + if (front >= rear) { + front = -1; + rear = -1; + } + else { + // mark next element as the front + front++; + } + System.out.println( element + " Deleted"); + return (element); + } + } + + // display element of the queue + void display() { + int i; + if (isEmpty()) { + System.out.println("Empty Queue"); + } + else { + // display the front of the queue + System.out.println("\nFront index-> " + front); + + // display element of the queue + System.out.println("Items -> "); + for (i = front; i <= rear; i++) + System.out.print(items[i] + " "); + + // display the rear of the queue + System.out.println("\nRear index-> " + rear); + } + } + + public static void main(String[] args) { + + // create an object of Queue class + Queue q = new Queue(); + + // try to delete element from the queue + // currently queue is empty + // so deletion is not possible + q.deQueue(); + + // insert elements to the queue + for(int i = 1; i < 6; i ++) { + q.enQueue(i); + } + + // 6th element can't be added to queue because queue is full + q.enQueue(6); + + q.display(); + + // deQueue removes element entered first i.e. 1 + q.deQueue(); + + // Now we have just 4 elements + q.display(); + + } +} diff --git a/Queue_ll.java b/Queue_ll.java new file mode 100644 index 00000000..30ac5a33 --- /dev/null +++ b/Queue_ll.java @@ -0,0 +1,52 @@ +public class Queue_ll { + static class Node{ + Node next; + int data; + Node(int data){ + this.data=data; + this.next=null;}} + + static class Queue{ + static Node head=null,tail=null; + static boolean isEmpty() { + return head==null & tail==null;} + + static void add(int data) { + Node p=new Node(data); + if(tail==null) { + tail=head=p; + return;} + tail.next=p; + tail=p;} + + static int rem() { + if(isEmpty()) { + System.out.println("empty"); + return -1;} + int front=head.data; + if(head==null) + tail=null; + head=head.next; + return front;} + + static int print() { + if(head==null) { + System.out.println("empty"); + System.exit(0);} + return head.data;} + + + public static void main(String[] args) { + Queue q=new Queue(); + q.add(5); + q.add(6); + q.add(2); + q.add(78); + + while(!q.isEmpty()) { + System.out.println(q.print()); + q.rem(); } + } + + } +} \ No newline at end of file diff --git a/QuickSort.java b/QuickSort.java new file mode 100644 index 00000000..a6e0adb4 --- /dev/null +++ b/QuickSort.java @@ -0,0 +1,39 @@ +public class QuickSort { + public static void main(String[] args) { + for(int n = 10;n<=50;n+=5){ + int[] arr = new int[n]; + for(int i=0;i Array to be sorted, + low --> Starting index, + high --> Ending index + */ + static void quickSort(int[] arr, int low, int high) + { + if (low < high) { + + // pi is partitioning index, arr[p] + // is now at right place + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } + } + + // Function to print an array + static void printArray(int[] arr, int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver Code + public static void main(String[] args) + { + int[] arr = { 10, 7, 8, 9, 1, 5 }; + int n = arr.length; + + quickSort(arr, 0, n - 1); + System.out.println("Sorted array: "); + printArray(arr, n); + } +} diff --git a/README.md b/README.md index 37c9895d..2db23e22 100644 --- a/README.md +++ b/README.md @@ -1 +1,28 @@ -# 🅰️ java-algorithms +# Hacktoberfest-2022🔥 +![image](https://user-images.githubusercontent.com/70385488/192114009-0830321a-d227-4a4d-8411-6c03b54d7ce6.png) + +

+ +[![Open Source Love](https://firstcontributions.github.io/open-source-badges/badges/open-source-v1/open-source.svg)](https://github.com/kishanrajput23/Hacktoberfest-2022) +Hacktober Badge +Star Badge +Contributions + +
+ + +### This repository aims to help code beginners with their first successful pull request and open-source contribution. :partying_face: + +:star: Feel free to use this project to make your first contribution to an open-source project on GitHub. Practice making your first pull request to a public repository before doing the real thing! + +:star: Make sure to grab some cool swags during Hacktoberfest by getting involved in the open-source community. + +### This repository is open to all members of the GitHub community. Any member can contribute to this project! The only thing which you need to keep in mind is that it should be genuine PR :grin: + +## What is Hacktoberfest? :thinking: +A month-long celebration from October 1st to October 31st presented by [Digital Ocean](https://hacktoberfest.digitalocean.com/) and [DEV Community](https://dev.to/) collaborated with [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open-source developer community. + +[https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/) + +## Rules :fire: +To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repo on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt. diff --git a/RadixSort.java b/RadixSort.java new file mode 100644 index 00000000..76677279 --- /dev/null +++ b/RadixSort.java @@ -0,0 +1,80 @@ +// Radix sort Java implementation + +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/RatMaze.java b/RatMaze.java new file mode 100644 index 00000000..07935d0d --- /dev/null +++ b/RatMaze.java @@ -0,0 +1,85 @@ + + +public class RatMaze { + + + static int N; + + + void printSolution(int sol[][]) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + System.out.print( + " " + sol[i][j] + " "); + System.out.println(); + } + } + + + boolean isSafe( + int maze[][], int x, int y) + { + + return (x >= 0 && x < N && y >= 0 + && y < N && maze[x][y] == 1); + } + + + boolean solveMaze(int maze[][]) + { + int sol[][] = new int[N][N]; + + if (solveMazeUtil(maze, 0, 0, sol) == false) { + System.out.print("Solution doesn't exist"); + return false; + } + + printSolution(sol); + return true; + } + + + boolean solveMazeUtil(int maze[][], int x, int y, + int sol[][]) + { + + if (x == N - 1 && y == N - 1 + && maze[x][y] == 1) { + sol[x][y] = 1; + return true; + } + + if (isSafe(maze, x, y) == true) { + if (sol[x][y] == 1) + return false; + + sol[x][y] = 1; + + if (solveMazeUtil(maze, x + 1, y, sol)) + return true; + + + if (solveMazeUtil(maze, x, y + 1, sol)) + return true; + + + sol[x][y] = 0; + return false; + } + + return false; + } + + public static void main(String args[]) + { + RatMaze rat = new RatMaze(); + int maze[][] = { { 1, 0, 0, 0 }, + { 1, 1, 0, 1 }, + { 0, 1, 0, 0 }, + { 1, 1, 1, 1 } }; + + N = maze.length; + rat.solveMaze(maze); + } +} diff --git a/RedBlackTreeInsertion.java b/RedBlackTreeInsertion.java new file mode 100644 index 00000000..0bf4c408 --- /dev/null +++ b/RedBlackTreeInsertion.java @@ -0,0 +1,235 @@ +import java.io.*; + +public class RedBlackTree +{ + public Node root;//root node + public RedBlackTree() + { + super(); + root = null; + } + // node creating subclass + class Node + { + int data; + Node left; + Node right; + char colour; + Node parent; + + Node(int data) + { + super(); + this.data = data; // only including data. not key + this.left = null; // left subtree + this.right = null; // right subtree + this.colour = 'R'; // colour . either 'R' or 'B' + this.parent = null; // required at time of rechecking. + } + } + // this function performs left rotation + Node rotateLeft(Node node) + { + Node x = node.right; + Node y = x.left; + x.left = node; + node.right = y; + node.parent = x; // parent resetting is also important. + if(y!=null) + y.parent = node; + return(x); + } + //this function performs right rotation + Node rotateRight(Node node) + { + Node x = node.left; + Node y = x.right; + x.right = node; + node.left = y; + node.parent = x; + if(y!=null) + y.parent = node; + return(x); + } + + + // these are some flags. + // Respective rotations are performed during traceback. + // rotations are done if flags are true. + boolean ll = false; + boolean rr = false; + boolean lr = false; + boolean rl = false; + // helper function for insertion. Actually this function performs all tasks in single pass only. + Node insertHelp(Node root, int data) + { + // f is true when RED RED conflict is there. + boolean f=false; + + //recursive calls to insert at proper position according to BST properties. + if(root==null) + return(new Node(data)); + else if(data list = Arrays.asList(s.split(" ")); + for(String word : list){ + resp += reverseIt(word); + resp += " "; + } + return resp.trim(); + } + + String reverseIt(String word){ + StringBuilder input = new StringBuilder(); + input.append(word); + input.reverse(); + return input.toString(); + } +} diff --git a/ReverseNumberPrint.java b/ReverseNumberPrint.java new file mode 100644 index 00000000..6bdf4a1b --- /dev/null +++ b/ReverseNumberPrint.java @@ -0,0 +1,13 @@ +public class ReverseNumber{ +public static void main(String[] args) +{ +int number = 987654, reverse = 0; +while(number != 0) +{ +int remainder = number % 10; +reverse = reverse * 10 + remainder; +number = number/10; +} +System.out.println("The reverse of the given number is: " + reverse); +} +} diff --git a/Right Triangle pattern program b/Right Triangle pattern program new file mode 100644 index 00000000..80dc029c --- /dev/null +++ b/Right Triangle pattern program @@ -0,0 +1,21 @@ + class RightTrianglePattern +{ +public static void main(String args[]) +{ +//i for rows and j for columns +//n denotes the number of rows you want to print +int i, j, n=6; +//outer loop for rows +for(i=0; i> " + inputString); + System.out.println(); + System.out.println("Encrypted/Decrypted String:"); + System.out.println(">> " + rotifiedString); + } + + private String rotify( String inputString) { + String outputString = ""; + for (int i = 0; i < inputString.length(); i++) { + char convertedChar = charRot(inputString.charAt(i)); + outputString += convertedChar; + } + return outputString; + } + + public char charRot(char charInput) { + char[] alphabets = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; + char convertedChar = charInput; + boolean isUppercase = !(convertedChar == (Character.toLowerCase(convertedChar))); + + for (int i = 0; i < 26; i++) { + if (Character.toLowerCase(charInput) == alphabets[i]) { + int convertedPositionInArray = i + 13; + + if (convertedPositionInArray >= 26) { + convertedPositionInArray -= 26; + } + + if (isUppercase) { + convertedChar = Character.toUpperCase(alphabets[convertedPositionInArray]); + } else + convertedChar = alphabets[convertedPositionInArray]; + } + } + return convertedChar; + } + +} \ No newline at end of file diff --git a/Screenshot_20220916-190224_WhatsApp.jpg b/Screenshot_20220916-190224_WhatsApp.jpg new file mode 100644 index 00000000..a65483a3 Binary files /dev/null and b/Screenshot_20220916-190224_WhatsApp.jpg differ diff --git a/Search using BinarySearch b/Search using BinarySearch new file mode 100644 index 00000000..af46a656 --- /dev/null +++ b/Search using BinarySearch @@ -0,0 +1,16 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + + // Using binarySearch() + int pos = Collections.binarySearch(numbers, 3); + System.out.println("The position of 3 is " + pos); + } +} diff --git a/SearchBinaryTree.java b/SearchBinaryTree.java new file mode 100644 index 00000000..bd98f344 --- /dev/null +++ b/SearchBinaryTree.java @@ -0,0 +1,68 @@ +public class SearchBinaryTree { + + //Represent a 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 static boolean flag = false; + + public SearchBinaryTree(){ + root = null; + } + + //searchNode() will search for the particular node in the binary tree + public void searchNode(Node temp, int value){ + //Check whether tree is empty + if(root == null){ + System.out.println("Tree is empty"); + } + else{ + //If value is found in the given binary tree then, set the flag to true + if(temp.data == value){ + flag = true; + return; + } + //Search in left subtree + if(flag == false && temp.left != null){ + searchNode(temp.left, value); + } + //Search in right subtree + if(flag == false && temp.right != null){ + searchNode(temp.right, value); + } + } + } + + public static void main(String[] args) { + + SearchBinaryTree bt = new SearchBinaryTree(); + //Add nodes to the binary tree + bt.root = new Node(1); + bt.root.left = new Node(2); + bt.root.right = new Node(3); + bt.root.left.left = new Node(4); + bt.root.right.left = new Node(5); + bt.root.right.right = new Node(6); + + //Search for node 5 in the binary tree + bt.searchNode(bt.root, 5); + + if(flag) + System.out.println("Element is present in the binary tree"); + else + System.out.println("Element is not present in the binary tree"); + } + } \ No newline at end of file diff --git a/Searching Using binary Search b/Searching Using binary Search new file mode 100644 index 00000000..af46a656 --- /dev/null +++ b/Searching Using binary Search @@ -0,0 +1,16 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + + // Using binarySearch() + int pos = Collections.binarySearch(numbers, 3); + System.out.println("The position of 3 is " + pos); + } +} diff --git a/SecondSmallestInArrayExample.java b/SecondSmallestInArrayExample.java new file mode 100644 index 00000000..c9f4e5ce --- /dev/null +++ b/SecondSmallestInArrayExample.java @@ -0,0 +1,23 @@ +public class SecondSmallestInArrayExample{ +public static int getSecondSmallest(int[] a, int total){ +int temp; +for (int i = 0; i < total; i++) + { + for (int j = i + 1; j < total; j++) + { + if (a[i] > a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + return a[1];//2nd element because index starts from 0 +} +public static void main(String args[]){ +int a[]={1,2,5,6,3,2}; +int b[]={44,66,99,77,33,22,55}; +System.out.println("Second smallest: "+getSecondSmallest(a,6)); +System.out.println("Second smallest: "+getSecondSmallest(b,7)); +}} \ No newline at end of file diff --git a/Selection Sort.java b/Selection Sort.java new file mode 100644 index 00000000..cd2e69a8 --- /dev/null +++ b/Selection Sort.java @@ -0,0 +1,27 @@ +import java.util.* ; +import java.io.*; +public class Solution { + public static void selectionSort(int arr[], int n) { + + for(int i = 0; i < arr.length - 1; i++){ + int minIndex = i; + for (int j = i+1; j < arr.length; j++){ + if (arr[j] < arr[minIndex]){ + minIndex = j; + } + + } + int temp = arr[i]; + arr[i] = arr[minIndex]; + arr[minIndex] = temp; + + + + + } + + + + + } +} diff --git a/SelectionSortpro.java b/SelectionSortpro.java new file mode 100644 index 00000000..6dce5856 --- /dev/null +++ b/SelectionSortpro.java @@ -0,0 +1,36 @@ +public class SelectionSortpro +{ + public static void main(String[] args) { + // This is unsorted array + Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 }; + + // Let's sort using selection sort + selectionSort(array, 0, array.length); + + // Verify sorted array + System.out.println(Arrays.toString(array)); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static void selectionSort(Object[] array, int fromIndex, int toIndex) + { + Object d; + for (int currentIndex = fromIndex; currentIndex < toIndex; currentIndex++) + { + int indexToMove = currentIndex; + for (int tempIndexInLoop = currentIndex + 1; tempIndexInLoop < toIndex; tempIndexInLoop++) + { + if (((Comparable) array[indexToMove]).compareTo(array[tempIndexInLoop]) > 0) + { + //Swapping + indexToMove = tempIndexInLoop; + } + } + d = array[currentIndex]; + array[currentIndex] = array[indexToMove]; + array[indexToMove] = d; + } + } +} + +Output: [3, 6, 10, 12, 13, 24, 70, 90] \ No newline at end of file diff --git a/SetMismatch.java b/SetMismatch.java new file mode 100644 index 00000000..94e8fc8e --- /dev/null +++ b/SetMismatch.java @@ -0,0 +1,44 @@ +// SET MISMATCH +// URL : https://leetcode.com/problems/set-mismatch/ + +package com.akshat; + +import java.util.Arrays; + +public class SetMismatch { + + public static void main(String[] args) { + + int[] nums = {1, 2, 2, 4}; + + int[] ans = findErrorNums(nums); + System.out.println(Arrays.toString(ans)); + + } + + static int[] findErrorNums(int[] nums){ + int i = 0; + while (i < nums.length){ + int correct = nums[i] - 1; + if (nums[i] != nums[correct]){ + swap(nums, i, correct); + } + else{ + i++; + } + } + for (int index=0; index set1; + + // Adding the elements + set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE, + Gfg.LEARN, Gfg.CODE); + + System.out.println("Set 1: " + set1); + } +} diff --git a/Sets.java/Classes/HashSet.txt b/Sets.java/Classes/HashSet.txt new file mode 100644 index 00000000..21a16be6 --- /dev/null +++ b/Sets.java/Classes/HashSet.txt @@ -0,0 +1,48 @@ +// Java program Demonstrating Creation of Set object +// Using the Hashset class + +// Importing utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Creating object of Set of type String + Set h = new HashSet(); + + // Adding elements into the HashSet + // using add() method + + // Custom input elements + h.add("India"); + h.add("Australia"); + h.add("South Africa"); + + // Adding the duplicate element + h.add("India"); + + // Displaying the HashSet + System.out.println(h); + + // Removing items from HashSet + // using remove() method + h.remove("Australia"); + System.out.println("Set after removing " + + "Australia:" + h); + + // Iterating over hash set items + System.out.println("Iterating over set:"); + + // Iterating through iterators + Iterator i = h.iterator(); + + // It holds true till there is a single element + // remaining in the object + while (i.hasNext()) + + System.out.println(i.next()); + } +} diff --git a/Sets.java/Classes/LinkedHashSet.txt b/Sets.java/Classes/LinkedHashSet.txt new file mode 100644 index 00000000..bb5e9bfa --- /dev/null +++ b/Sets.java/Classes/LinkedHashSet.txt @@ -0,0 +1,37 @@ +// Java program to demonstrate the +// creation of Set object using +// the LinkedHashset class +import java.util.*; + +class GFG { + + public static void main(String[] args) + { + Set lh = new LinkedHashSet(); + + // Adding elements into the LinkedHashSet + // using add() + lh.add("India"); + lh.add("Australia"); + lh.add("South Africa"); + + // Adding the duplicate + // element + lh.add("India"); + + // Displaying the LinkedHashSet + System.out.println(lh); + + // Removing items from LinkedHashSet + // using remove() + lh.remove("Australia"); + System.out.println("Set after removing " + + "Australia:" + lh); + + // Iterating over linked hash set items + System.out.println("Iterating over set:"); + Iterator i = lh.iterator(); + while (i.hasNext()) + System.out.println(i.next()); + } +} diff --git a/Sets.java/Classes/TreeSet.txt b/Sets.java/Classes/TreeSet.txt new file mode 100644 index 00000000..143711e8 --- /dev/null +++ b/Sets.java/Classes/TreeSet.txt @@ -0,0 +1,44 @@ +// Java Program Demonstrating Creation of Set object +// Using the TreeSet class + +// Importing utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Creating a Set object and declaring it of String + // type + // with reference to TreeSet + Set ts = new TreeSet(); + + // Adding elements into the TreeSet + // using add() + ts.add("India"); + ts.add("Australia"); + ts.add("South Africa"); + + // Adding the duplicate + // element + ts.add("India"); + + // Displaying the TreeSet + System.out.println(ts); + + // Removing items from TreeSet + // using remove() + ts.remove("Australia"); + System.out.println("Set after removing " + + "Australia:" + ts); + + // Iterating over Tree set items + System.out.println("Iterating over set:"); + Iterator i = ts.iterator(); + + while (i.hasNext()) + System.out.println(i.next()); + } +} diff --git a/Sets.java/Operations/Accessing the Elements.txt b/Sets.java/Operations/Accessing the Elements.txt new file mode 100644 index 00000000..ea253567 --- /dev/null +++ b/Sets.java/Operations/Accessing the Elements.txt @@ -0,0 +1,38 @@ +// Java code to demonstrate Working of Set by +// Accessing the Elements of the Set object + +// Importing all utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Creating an object of Set and + // declaring object of type String + Set hs = new HashSet(); + + // Elements are added using add() method + // Later onwards we will show accessing the same + + // Custom input elements + hs.add("A"); + hs.add("B"); + hs.add("C"); + hs.add("A"); + + // Print the Set object elements + System.out.println("Set is " + hs); + + // Declaring a string + String check = "D"; + + // Check if the above string exists in + // the SortedSet or not + // using contains() method + System.out.println("Contains " + check + " " + + hs.contains(check)); + } +} diff --git a/Sets.java/Operations/Adding Elements.txt b/Sets.java/Operations/Adding Elements.txt new file mode 100644 index 00000000..d3c983e7 --- /dev/null +++ b/Sets.java/Operations/Adding Elements.txt @@ -0,0 +1,27 @@ +// Java Program Demonstrating Working of Set by +// Adding elements using add() method + +// Importing all utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Creating an object of Set and + // declaring object of type String + Set hs = new HashSet(); + + // Adding elements to above object + // using add() method + hs.add("B"); + hs.add("B"); + hs.add("C"); + hs.add("A"); + + // Printing the elements inside the Set object + System.out.println(hs); + } +} diff --git a/Sets.java/Operations/Iterating through the Set.txt b/Sets.java/Operations/Iterating through the Set.txt new file mode 100644 index 00000000..44c8e6af --- /dev/null +++ b/Sets.java/Operations/Iterating through the Set.txt @@ -0,0 +1,36 @@ +// Java Program to Demonstrate Working of Set by +// Iterating through the Elements + +// Importing utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Creating object of Set and declaring String type + Set hs = new HashSet(); + + // Adding elements to Set + // using add() method + + // Custom input elements + hs.add("A"); + hs.add("B"); + hs.add("C"); + hs.add("B"); + hs.add("D"); + hs.add("E"); + + // Iterating through the Set + // via for-each loop + for (String value : hs) + + // Printing all the values inside the object + System.out.print(value + ", "); + + System.out.println(); + } +} diff --git a/Sets.java/Operations/Removing the Values.txt b/Sets.java/Operations/Removing the Values.txt new file mode 100644 index 00000000..38eb3e10 --- /dev/null +++ b/Sets.java/Operations/Removing the Values.txt @@ -0,0 +1,38 @@ +// Java Program Demonstrating Working of Set by +// Removing Element/s from the Set + +// Importing all utility classes +import java.util.*; + +// Main class +class GFG { + + // Main driver method + public static void main(String[] args) + { + // Declaring object of Set of type String + Set hs = new HashSet(); + + // Elements are added + // using add() method + + // Custom input elements + hs.add("A"); + hs.add("B"); + hs.add("C"); + hs.add("B"); + hs.add("D"); + hs.add("E"); + + // Printing initial Set elements + System.out.println("Initial HashSet " + hs); + + // Removing custom element + // using remove() method + hs.remove("B"); + + // Printing Set elements after removing an element + // and printing updated Set elements + System.out.println("After removing element " + hs); + } +} diff --git a/Sets.java/Set Interface.txt b/Sets.java/Set Interface.txt new file mode 100644 index 00000000..668ffbf5 --- /dev/null +++ b/Sets.java/Set Interface.txt @@ -0,0 +1,27 @@ +// Java program Illustrating Set Interface + +// Importing utility classes +import java.util.*; + +// Main class +public class GFG { + + // Main driver method + public static void main(String[] args) + { + // Demonstrating Set using HashSet + // Declaring object of type String + Set hash_Set = new HashSet(); + + // Adding elements to the Set + // using add() method + hash_Set.add("Set1"); + hash_Set.add("Set2"); + hash_Set.add("Set3"); + hash_Set.add("Example"); + hash_Set.add("Set"); + + // Printing elements of HashSet object + System.out.println(hash_Set); + } +} diff --git a/Shell_Sort.java b/Shell_Sort.java new file mode 100644 index 00000000..15c15891 --- /dev/null +++ b/Shell_Sort.java @@ -0,0 +1,47 @@ +package Sorting; + +public class shell { + + public static void main(String args[]) + { + int[] a={9, 8, 3, 56, 5, 6, 4, 1}; + int length=a.length; + + + int gap=length/2; + // System.out.println(gap); + while(gap>0) + { + for(int i=gap;i=gap && a[j-gap]>temp) + { + // System.out.println(a[j]); + a[j]=a[j-gap]; + // System.out.println(a[j]); + j=j-gap; + + a[j]=temp; + // System.out.println(a[j]); + + } + + + } + + gap=gap/2; + + + } + for(int i=0;i 0; gap /= 2) + { + // Do a gapped insertion sort for this gap size. + // The first gap elements a[0..gap-1] are already + // in gapped order keep adding one more element + // until the entire array is gap sorted + for (int i = gap; i < n; i += 1) + { + // add a[i] to the elements that have been gap + // sorted save a[i] in temp and make a hole at + // position i + int temp = arr[i]; + + // shift earlier gap-sorted elements up until + // the correct location for a[i] is found + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + // put temp (the original a[i]) in its correct + // location + arr[j] = temp; + } + } + return 0; + } + + // Driver method + public static void main(String args[]) + { + int arr[] = {12, 34, 54, 2, 3}; + System.out.println("Array before sorting"); + printArray(arr); + + ShellSort ob = new ShellSort(); + ob.sort(arr); + + System.out.println("Array after sorting"); + printArray(arr); + } +} +/*This code is contributed by Rajat Mishra */ diff --git a/Shortest Common Supersequence Problem b/Shortest Common Supersequence Problem new file mode 100644 index 00000000..c3c2329a --- /dev/null +++ b/Shortest Common Supersequence Problem @@ -0,0 +1,51 @@ +import java.util.HashMap; +import java.util.Map; + +class Main +{ + // Function to find the length of the shortest common supersequence of + // sequences `X[0…m-1]` and `Y[0…n-1]` + public static int SCSLength(String X, String Y, int m, int n, + Map lookup) + { + // if the end of either sequence is reached, return + // the length of another sequence + if (m == 0 || n == 0) { + return n + m; + } + + // construct a unique map key from dynamic elements of the input + String key = m + "|" + n; + + // if the subproblem is seen for the first time, solve it and + // store its result in a map + if (!lookup.containsKey(key)) + { + // if the last character of `X` and `Y` matches + if (X.charAt(m - 1) == Y.charAt(n - 1)) { + lookup.put(key, SCSLength(X, Y, m - 1, n - 1, lookup) + 1); + } + else { + // otherwise, if the last character of `X` and `Y` don't match + int min = Integer.min(SCSLength(X, Y, m, n - 1, lookup) + 1, + SCSLength(X, Y, m - 1, n, lookup) + 1); + lookup.put(key, min); + } + } + + // return the subproblem solution from the map + return lookup.get(key); + } + + public static void main(String[] args) + { + String X = "ABCBDAB", Y = "BDCABA"; + + // create a map to store solutions to subproblems; + // we can also use an array instead of a map + Map lookup = new HashMap<>(); + + System.out.print("The length of the shortest common supersequence is " + + SCSLength(X, Y, X.length(), Y.length(), lookup)); + } +} diff --git a/Shuffling Using shuffle() b/Shuffling Using shuffle() new file mode 100644 index 00000000..e05e4cb8 --- /dev/null +++ b/Shuffling Using shuffle() @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + // Creating an array list + ArrayList numbers = new ArrayList<>(); + + // Add elements + numbers.add(1); + numbers.add(2); + numbers.add(3); + System.out.println("Sorted ArrayList: " + numbers); + + // Using the shuffle() method + Collections.shuffle(numbers); + System.out.println("ArrayList using shuffle: " + numbers); + + } +} diff --git a/Sierpinski.java b/Sierpinski.java new file mode 100644 index 00000000..557297fb --- /dev/null +++ b/Sierpinski.java @@ -0,0 +1,45 @@ +// Java program to print +// sierpinski triangle. +import java.util.*; +import java.io.*; + +class Sierpinski +{ + static void printSierpinski(int n) + { + for (int b = n - 1; b >= 0; b--) { + + // printing space till + // the value of y + for (int i = 0; i < b; i++) { + System.out.print(" "); + } + + // printing '*' + for (int a = 0; a + b < n; a++) { + + // printing '*' at the appropriate + // position is done by the and + // value of x and y wherever value + // is 0 we have printed '*' + if ((a & b) != 0) + System.out.print(" " + + " "); + else + System.out.print("* "); + } + + System.out.print("\n"); + } + } + + // Driver code + public static void main(String args[]) + { + int n = 16; + + // Function calling + printSierpinski(n); + } +} + diff --git a/SieveOfEratosthenes.java b/SieveOfEratosthenes.java new file mode 100644 index 00000000..c2e4a2bc --- /dev/null +++ b/SieveOfEratosthenes.java @@ -0,0 +1,42 @@ +import java.util.*; +public class SieveOfEratosthenes { + + + static boolean[] sieveOfEr(int n) + { + boolean isPrime[]=new boolean[n+1]; + Arrays.fill(isPrime,true); + for(int i=2;i*i<=n;i++) + { for(int j=2;j<=n;j=j+i) + { +isPrime[j]=false; + } + + } + return isPrime; + } + + public static void main (String args[]) +{ + Scanner sc=new Scanner(System.in); + + int n=sc.nextInt(); + boolean iPrime[]=sieveOfEr(n); + for(int i=2;i +#include + +void main() +{ + FILE *fp; + char ch; + int size = 0; + + fp = fopen("MyFile.txt", "r"); + if (fp == NULL) + { + printf("\nFile unable to open..."); + } + else + { + printf("\nFile opened..."); + } + fseek(fp, 0, 2); /* File pointer at the end of file */ + size = ftell(fp); /* Take a position of file pointer in size variable */ + printf("The size of given file is: %d\n", size); + fclose(fp); +} diff --git a/SnakeGameusingjavaProcessing/snake 2022-10-06 21-25-39.mp4 b/SnakeGameusingjavaProcessing/snake 2022-10-06 21-25-39.mp4 new file mode 100644 index 00000000..8a766d94 Binary files /dev/null and b/SnakeGameusingjavaProcessing/snake 2022-10-06 21-25-39.mp4 differ diff --git a/SnakeGameusingjavaProcessing/snake.pde b/SnakeGameusingjavaProcessing/snake.pde new file mode 100644 index 00000000..963531c0 --- /dev/null +++ b/SnakeGameusingjavaProcessing/snake.pde @@ -0,0 +1,88 @@ +ArrayListx=new ArrayList(),y=new ArrayList(); +int w=30,h=30,blocks=20,direction=2,fx=15,fy=15,fc1=255,fc2=255,fc3=255,speed=8; +int[] x_dir={0,0,1,-1},y_dir={1,-1,0,0}; +boolean gameover=false; + + + +void setup(){ + size(600,600); + x.add(0); + y.add(15); +} + + +void draw(){ + background(0); + fill(#084D15); + for(int i =0 ; i=w || y.get(0)>=h) gameover=true; + + for(int i =1; i=2) speed-=1; + fx=(int)random(0,w); + fy=(int)random(0,h); + fc1=(int)random(255); + fc2=(int)random(255); + fc3=(int)random(255); + + } + else{ + x.remove(x.size()-1); + y.remove(y.size()-1); + } +} + } + else{ + fill(200,200,0); + textSize(30); + textAlign(CENTER); + text("GAME OVER \n Your Score is : "+x.size()+"\n Press Enter", width/2,height/3); + if(keyCode == ENTER){ + x.clear(); + y.clear(); + x.add(0); + y.add(15); + direction=2; + speed=8; + gameover= false; + + } +} + + + //keyPressed(); + +} + + +void keyPressed(){ + +int newdir=keyCode==DOWN? 0:(keyCode==UP?1:(keyCode==RIGHT?2:(keyCode==LEFT?3:-1))); +if(newdir != -1){ +direction = newdir; +} + +} diff --git a/Solution.java b/Solution.java new file mode 100644 index 00000000..5becba63 Binary files /dev/null and b/Solution.java differ diff --git a/Spiral_Matrix.cpp b/Spiral_Matrix.cpp new file mode 100644 index 00000000..053dd253 --- /dev/null +++ b/Spiral_Matrix.cpp @@ -0,0 +1,37 @@ + vector spiralOrder(vector>& matrix) { + + int count=0; + vector ans; + int startingrow=0,startingcol=0,endingrow=matrix.size(),endingcol=matrix[0].size(); + int total=endingrow*endingcol; + endingrow=matrix.size()-1; + endingcol=endingcol-1; + + while(count=startingcol&&count=startingrow&&count> j) & 1) % 2 == 1) + sum += arr[j]; + + // if the sum is equal to given sum print yes + if (sum == s) { + System.out.println("YES"); + return; + } + } + + // else print no + System.out.println("NO"); + } + + // driver code + public static void main(String[] args) + { + int sum = 5; + int []array = { -1, 2, 4, 121 }; + int length = array.length; + + // find whether it is possible to sum to n + find(array, length, sum); + + } + +} + +// This code is contributed by ihritik diff --git a/Subtract_Product_&_Sum_of_Digits_Integer.java b/Subtract_Product_&_Sum_of_Digits_Integer.java new file mode 100644 index 00000000..168828f1 --- /dev/null +++ b/Subtract_Product_&_Sum_of_Digits_Integer.java @@ -0,0 +1,37 @@ +// Subtract the Product and Sum of Digits of an Integer +// Given an integer number n, return the difference between the product of its digits and the sum of its digits. + +/* +Sample: +Input: n = 234 +Output: 15 +Explanation: +Product of digits = 2 * 3 * 4 = 24 +Sum of digits = 2 + 3 + 4 = 9 +Result = 24 - 9 = 15 +*/ + +//code +class Solution { + public int subtractProductAndSum(int n) { + int reverse=0,sum=0,product=1; + int temp=n; + //for sum + while(temp>0) { + reverse=temp%10; + sum+=reverse; + temp/=10; + } + //for multiply + + while(n>0) { + reverse=n%10; + product*=reverse; + n/=10; + } + //returning the difference + return (product-sum); + + } + +} diff --git a/Sudoku Solver b/Sudoku Solver new file mode 100644 index 00000000..90b2cd38 --- /dev/null +++ b/Sudoku Solver @@ -0,0 +1,95 @@ +/** + * Most Optimized Backtracking solution using Bit Manipulation + * + * Time Complexity: T(N) = 9 * T(N-1) + O(9) ==> TC = (9^N). Also, O(9*9) is + * required for checking validity and finding blanks. + * + * Space Complexity: O(3*9 + 2*N). 3*9 for rows, cols and boxes int array. N for + * blanks list. N will be the recursion depth. + * + * N = Number of blank spaces. In worst case it can be 9*9 = 81. + */ +class Solution1 { + public void solveSudoku(char[][] board) { + if (board == null || board.length != 9 || board[0].length != 9) { + throw new IllegalArgumentException("Input is invalid"); + } + + int[] rows = new int[9]; + int[] cols = new int[9]; + int[] boxes = new int[9]; + List blanks = new ArrayList<>(); + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + char c = board[i][j]; + // To Blanks List + if (c == '.') { + blanks.add(new int[] { i, j }); + continue; + } + + // Check for Invalid Chars + if (c < '1' || c > '9') { + throw new IllegalArgumentException("Invalid sudoku board"); + } + + int b = 3 * (i / 3) + (j / 3); + int mask = 1 << (c - '1'); + + // Check for unsolvable board + if (((rows[i] & mask) != 0) || ((cols[j] & mask) != 0) || ((boxes[b] & mask) != 0)) { + throw new IllegalArgumentException("Invalid sudoku board"); + } + + // Add the cell to rows, cols and boxes. + rows[i] |= mask; + cols[j] |= mask; + boxes[b] |= mask; + } + } + + if (!solveSudokuHelper(board, rows, cols, boxes, blanks, 0)) { + throw new RuntimeException("Input sudoku does not have a valid solution"); + } + } + + private boolean solveSudokuHelper(char[][] board, int[] rows, int[] cols, int[] boxes, List blanks, + int idx) { + if (idx == blanks.size()) { + return true; + } + + int[] cell = blanks.get(idx); + int i = cell[0]; + int j = cell[1]; + int b = 3 * (i / 3) + (j / 3); + + for (char c = '1'; c <= '9'; c++) { + int mask = 1 << (c - '1'); + + // Check if the number already used in row, column and sub-box. + if (((rows[i] & mask) != 0) || ((cols[j] & mask) != 0) || ((boxes[b] & mask) != 0)) { + continue; + } + + // Add the cell to rows, cols and boxes. + rows[i] |= mask; + cols[j] |= mask; + boxes[b] |= mask; + board[i][j] = c; + + if (solveSudokuHelper(board, rows, cols, boxes, blanks, idx + 1)) { + return true; + } + + // Backtrack + // Remove the cell to rows, cols and boxes. + rows[i] &= ~mask; + cols[j] &= ~mask; + boxes[b] &= ~mask; + } + + return false; + } +} diff --git a/Sum of squares of all Subsets of given Array b/Sum of squares of all Subsets of given Array new file mode 100644 index 00000000..88689435 --- /dev/null +++ b/Sum of squares of all Subsets of given Array @@ -0,0 +1,44 @@ +// Java implementation of the approach +class GFG +{ + static final int mod = (int)(1e9 + 7); + + // Function to return (2^P % mod) + static long power(int p) + { + long res = 1; + for (int i = 1; i <= p; ++i) + { + res *= 2; + res %= mod; + } + return res % mod; + } + + // Function to return the sum of squares of subsets + static long subset_square_sum(int A[]) + { + int n = A.length; + + long ans = 0; + + // Sqauaring the elements + // and adding it to ans + for (int i : A) + { + ans += (1 * i * i) % mod; + ans %= mod; + } + return (1 * ans * power(n - 1)) % mod; + } + + // Driver code + public static void main (String[] args) + { + int A[] = { 3, 7 }; + + System.out.println(subset_square_sum(A)); + } +} + +// This code is contributed by AnkitRai01 diff --git a/Sum of subsets of an Array b/Sum of subsets of an Array new file mode 100644 index 00000000..28d762a1 --- /dev/null +++ b/Sum of subsets of an Array @@ -0,0 +1,51 @@ +// Java implementation of the approach +class GFG +{ +static int maxN = 10; + +// To store factorial values +static int []fact = new int[maxN]; + +// Function to return ncr +static int ncr(int n, int r) +{ + return (fact[n] / fact[r]) / fact[n - r]; +} + +// Function to return the required sum +static int findSum(int[] arr, int n) +{ + // Initialising factorial + fact[0] = 1; + for (int i = 1; i < n; i++) + fact[i] = i * fact[i - 1]; + + // Multiplier + int mul = 0; + + // Finding the value of multipler + // according to the formula + for (int i = 0; i <= n - 1; i++) + mul += (int)Math.pow(2, i) * ncr(n - 1, i); + + // To store the final answer + int ans = 0; + + // Calculate the final answer + for (int i = 0; i < n; i++) + ans += mul * arr[i]; + + return ans; +} + +// Driver code +public static void main(String []args) +{ + int arr[] = { 1, 1 }; + int n = arr.length; + + System.out.println(findSum(arr, n)); +} +} + +// This code is contributed by Rajput-Ji diff --git a/Swap Numbers b/Swap Numbers new file mode 100644 index 00000000..ff675dec --- /dev/null +++ b/Swap Numbers @@ -0,0 +1,24 @@ +public class SwapNumbers { + + public static void main(String[] args) { + + float first = 1.20f, second = 2.45f; + + System.out.println("--Before swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + + // Value of first is assigned to temporary + float temporary = first; + + // Value of second is assigned to first + first = second; + + // Value of temporary (which contains the initial value of first) is assigned to second + second = temporary; + + System.out.println("--After swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + } +} diff --git a/Swap.cpp b/Swap.cpp new file mode 100644 index 00000000..6053852a --- /dev/null +++ b/Swap.cpp @@ -0,0 +1,36 @@ +#include + +int main() { + + double first, second, temp; + + printf("Enter first number: "); + + scanf("%lf", &first); + + printf("Enter second number: "); + + scanf("%lf", &second); + + // value of first is assigned to temp + + temp = first; + + // value of second is assigned to first + + first = second; + + // value of temp (initial value of first) is assigned to second + + second = temp; + + // %.2lf displays number up to 2 decimal points + + printf("\nAfter swapping, first number = %.2lf\n", first); + + printf("After swapping, second number = %.2lf", second); + + return 0; + +} + diff --git a/Tallest Billboard [naive depth first search] b/Tallest Billboard [naive depth first search] new file mode 100644 index 00000000..5223731d --- /dev/null +++ b/Tallest Billboard [naive depth first search] @@ -0,0 +1,19 @@ +class Solution { + public int tallestBillboard(int[] rods) { + int[] result = new int[1]; + dfs(rods, 0, 0, 0, rods.length, result); + return result[0]; + } + private void dfs(int[] rods, int left, int right, int level, int n, int[] result) { + if (level == n) { + if (left == right) { + result[0] = Math.max(left, result[0]); + } + return; + } + + dfs(rods, left, right, level + 1, n, result); + dfs(rods, left + rods[level], right, level + 1, n, result); + dfs(rods, left, right + rods[level], level + 1, n, result); + } +} diff --git a/Template Overload.cpp b/Template Overload.cpp new file mode 100644 index 00000000..d85d39b6 --- /dev/null +++ b/Template Overload.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +template +void display(T1 a) +{ + cout<<"\nOne Variable Template "< +void display(T1 a,T2 b) +{ + cout<<"\nTwo Variable Template "<= l) +{ + int mid1 = l + (r - l) / 3; + int mid2 = mid1 + (r - l) / 3; + + // If x is present at the mid1 + if (arr[mid1] == x) return mid1; + + // If x is present at the mid2 + if (arr[mid2] == x) return mid2; + + // If x is present in left one-third + if (arr[mid1] > x) + return ternarySearch(arr, l, mid1 - 1, x); + + // If x is present in right one-third + if (arr[mid2] < x) + return ternarySearch(arr, mid2 + 1, r, x); + + // If x is present in middle one-third + return ternarySearch(arr, mid1 + 1, + mid2 - 1, x); +} + +// We reach here when element is +// not present in array +return -1; +} +} diff --git a/TestMyException.java b/TestMyException.java new file mode 100644 index 00000000..8a6dc8e5 --- /dev/null +++ b/TestMyException.java @@ -0,0 +1,26 @@ +public class TestMyException +{ + void throwExp(int i) throws MyException +{ +if(i>100) +throw new MyException(i); +else +System.out.println("value :"+i); +} +public static void main(String args[]) +{ + int x=Integer.parseInt(args[0]); + int y=Integer.parseInt(args[1]); + +TestMyException t=new TestMyException(); +try +{ + t.throwExp(x); + t.throwExp(y); + +}catch(Throwable e) +{ +System.out.println(e); +} +} +} diff --git a/TestStack.java b/TestStack.java new file mode 100644 index 00000000..84354e05 --- /dev/null +++ b/TestStack.java @@ -0,0 +1,58 @@ + +import java.io.*; +import java.util.*; + +class Test +{ + // Pushing element on the top of the stack + static void stack_push(Stack stack) + { + for(int i = 0; i < 5; i++) + { + stack.push(i); + } + } + + + static void stack_pop(Stack stack) + { + System.out.println("Pop Operation:"); + + for(int i = 0; i < 5; i++) + { + Integer y = (Integer) stack.pop(); + System.out.println(y); + } + } + + + static void stack_peek(Stack stack) + { + Integer element = (Integer) stack.peek(); + System.out.println("Element on stack top: " + element); + } + + + static void stack_search(Stack stack, int element) + { + Integer pos = (Integer) stack.search(element); + + if(pos == -1) + System.out.println("Element not found"); + else + System.out.println("Element is found at position: " + pos); + } + + + public static void main (String[] args) + { + Stack stack = new Stack(); + + stack_push(stack); + stack_pop(stack); + stack_push(stack); + stack_peek(stack); + stack_search(stack, 2); + stack_search(stack, 6); + } +} diff --git a/TestTwoMethods.java b/TestTwoMethods.java new file mode 100644 index 00000000..d663522e --- /dev/null +++ b/TestTwoMethods.java @@ -0,0 +1,11 @@ +package demoTest; + +public class TestTwoMethods { + public String checkMood(String message){ + return "Happy"; + } + + public static String displayStudentName(String firstName, String lastName) { + return firstName + " "+lastName; + } +} diff --git a/Tic Tac Toe/README.md b/Tic Tac Toe/README.md new file mode 100644 index 00000000..2a526492 --- /dev/null +++ b/Tic Tac Toe/README.md @@ -0,0 +1,3 @@ +# Tic-Tac-Toe Game in Java + +The task is to create a Java program to implement a 3×3 Tic-Tac-Toe game for two players. diff --git a/Tic Tac Toe/tic-tac-toe.java b/Tic Tac Toe/tic-tac-toe.java new file mode 100644 index 00000000..584c42f2 --- /dev/null +++ b/Tic Tac Toe/tic-tac-toe.java @@ -0,0 +1,173 @@ +// A simple program to demonstrate +// Tic-Tac-Toe Game. +import java.util.*; + +public class solution { + + static String[] board; + static String turn; + + + // CheckWinner method will + // decide the combination + // of three box given below. + static String checkWinner() + { + for (int a = 0; a < 8; a++) { + String line = null; + + switch (a) { + case 0: + line = board[0] + board[1] + board[2]; + break; + case 1: + line = board[3] + board[4] + board[5]; + break; + case 2: + line = board[6] + board[7] + board[8]; + break; + case 3: + line = board[0] + board[3] + board[6]; + break; + case 4: + line = board[1] + board[4] + board[7]; + break; + case 5: + line = board[2] + board[5] + board[8]; + break; + case 6: + line = board[0] + board[4] + board[8]; + break; + case 7: + line = board[2] + board[4] + board[6]; + break; + } + //For X winner + if (line.equals("XXX")) { + return "X"; + } + + // For O winner + else if (line.equals("OOO")) { + return "O"; + } + } + + for (int a = 0; a < 9; a++) { + if (Arrays.asList(board).contains( + String.valueOf(a + 1))) { + break; + } + else if (a == 8) { + return "draw"; + } + } + + // To enter the X Or O at the exact place on board. + System.out.println( + turn + "'s turn; enter a slot number to place " + + turn + " in:"); + return null; + } + + // To print out the board. + /* |---|---|---| + | 1 | 2 | 3 | + |-----------| + | 4 | 5 | 6 | + |-----------| + | 7 | 8 | 9 | + |---|---|---|*/ + + static void printBoard() + { + System.out.println("|---|---|---|"); + System.out.println("| " + board[0] + " | " + + board[1] + " | " + board[2] + + " |"); + System.out.println("|-----------|"); + System.out.println("| " + board[3] + " | " + + board[4] + " | " + board[5] + + " |"); + System.out.println("|-----------|"); + System.out.println("| " + board[6] + " | " + + board[7] + " | " + board[8] + + " |"); + System.out.println("|---|---|---|"); + } + + public static void main(String[] args) + { + Scanner in = new Scanner(System.in); + board = new String[9]; + turn = "X"; + String winner = null; + + for (int a = 0; a < 9; a++) { + board[a] = String.valueOf(a + 1); + } + + System.out.println("Welcome to 3x3 Tic Tac Toe."); + printBoard(); + + System.out.println( + "X will play first. Enter a slot number to place X in:"); + + while (winner == null) { + int numInput; + + // Exception handling. + // numInput will take input from user like from 1 to 9. + // If it is not in range from 1 to 9. + // then it will show you an error "Invalid input." + try { + numInput = in.nextInt(); + if (!(numInput > 0 && numInput <= 9)) { + System.out.println( + "Invalid input; re-enter slot number:"); + continue; + } + } + catch (InputMismatchException e) { + System.out.println( + "Invalid input; re-enter slot number:"); + continue; + } + + // This game has two player x and O. + // Here is the logic to decide the turn. + if (board[numInput - 1].equals( + String.valueOf(numInput))) { + board[numInput - 1] = turn; + + if (turn.equals("X")) { + turn = "O"; + } + else { + turn = "X"; + } + + printBoard(); + winner = checkWinner(); + } + else { + System.out.println( + "Slot already taken; re-enter slot number:"); + } + } + + // If no one win or lose from both player x and O. + // then here is the logic to print "draw". + if (winner.equalsIgnoreCase("draw")) { + System.out.println( + "It's a draw! Thanks for playing."); + } + + // For winner -to display Congratulations! message. + else { + System.out.println( + "Congratulations! " + winner + + "'s have won! Thanks for playing."); + } + } +} diff --git a/Tic-tac-toe java program.java b/Tic-tac-toe java program.java new file mode 100644 index 00000000..04abd225 --- /dev/null +++ b/Tic-tac-toe java program.java @@ -0,0 +1,176 @@ +import java.util.Scanner; + + +public class TicTacToe +{ + private int counter; + private char posn[]=new char[10]; + private char player; + + + public static void main(String args[]) + { + String ch; + TicTacToe Toe=new TicTacToe(); + do{ + Toe.newBoard(); + Toe.play(); + System.out.println ("Would you like to play again (Enter 'yes')? "); + Scanner in =new Scanner(System.in); + ch=in.nextLine(); + System.out.println("ch value is "+ch); + }while (ch.equals("yes")); + + + } + public void newBoard() + { + + char posndef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'}; + int i; + counter = 0; + player = 'X'; + for (i=1; i<10; i++) posn[i]=posndef[i]; + currentBoard(); + + + } + public String currentBoard() + { + System.out.println( "\n\n" ); + System.out.println( "\n\n" ); + System.out.println( "\n\n\t\t" + posn [1] + " | " +posn [2]+ " | " +posn [3]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t ___|____|___ " ); + System.out.println( "\n\n\t\t" +posn [4]+ " | " +posn [5]+ " | " +posn [6]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t ___|____|___ " ); + System.out.println( "\n\n\t\t" +posn [7]+ " | " +posn [8]+ " | " +posn [9]); + System.out.println( " \t\t | | " ); + System.out.println( " \t\t | | " ); + System.out.println( "\n\n" ); + return "currentBoard"; + } + + public void play() + { + int spot; + char blank = ' '; + + System.out.println( "Player " + getPlayer() +" will go first and be the letter 'X'" ); + + do { + currentBoard(); // display current board + + System.out.println( "\n\n Player " + getPlayer() +" choose a posn." ); + + boolean posTaken = true; + while (posTaken) { + // System.out.println( "position is taken, please enter a valid space"); + Scanner in =new Scanner (System.in); + spot=in.nextInt(); + posTaken = checkPosn(spot); + if(posTaken==false) + posn[spot]=getPlayer(); + } + + System.out.println( "Nice move." ); + + currentBoard(); // display current board + + nextPlayer(); + }while ( checkWinner() == blank ); + + } + + public char checkWinner() + { + char Winner = ' '; + + // Check if X wins + if (posn[1] == 'X' && posn[2] == 'X' && posn[3] == 'X') Winner = 'X'; + if (posn[4] == 'X' && posn[5] == 'X' && posn[6] == 'X') Winner = 'X'; + if (posn[7] == 'X' && posn[8] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[1] == 'X' && posn[4] == 'X' && posn[7] == 'X') Winner = 'X'; + if (posn[2] == 'X' && posn[5] == 'X' && posn[8] == 'X') Winner = 'X'; + if (posn[3] == 'X' && posn[6] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[1] == 'X' && posn[5] == 'X' && posn[9] == 'X') Winner = 'X'; + if (posn[3] == 'X' && posn[5] == 'X' && posn[7] == 'X') Winner = 'X'; + if (Winner == 'X' ) + {System.out.println("Player1 wins the game." ); + return Winner; + } + + // Check if O wins + if (posn[1] == 'O' && posn[2] == 'O' && posn[3] == 'O') Winner = 'O'; + if (posn[4] == 'O' && posn[5] == 'O' && posn[6] == 'O') Winner = 'O'; + if (posn[7] == 'O' && posn[8] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[1] == 'O' && posn[4] == 'O' && posn[7] == 'O') Winner = 'O'; + if (posn[2] == 'O' && posn[5] == 'O' && posn[8] == 'O') Winner = 'O'; + if (posn[3] == 'O' && posn[6] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[1] == 'O' && posn[5] == 'O' && posn[9] == 'O') Winner = 'O'; + if (posn[3] == 'O' && posn[5] == 'O' && posn[7] == 'O') Winner = 'O'; + if (Winner == 'O' ) + { + System.out.println( "Player2 wins the game." ); + return Winner; } + + // check for Tie + for(int i=1;i<10;i++) + { + if(posn[i]=='X' || posn[i]=='O') + { + if(i==9) + { + char Draw='D'; + System.out.println(" Game is stalemate "); + return Draw; + } + continue; + } + else + break; + + } + + return Winner; + } + + public boolean checkPosn(int spot) + { + + + if (posn[spot] == 'X' || posn[spot] == 'O') + { + System.out.println("That posn is already taken, please choose another"); + return true; + } + else { + return false; + } + + // counter++; + // return false; + } + + + + public void nextPlayer() + { + if (player == 'X') + player = 'O'; + else player = 'X'; + + } + + public String getTitle() + { + return "Tic Tac Toe" ; + } + + public char getPlayer() + { + return player; + } + +} diff --git a/TimSort.java b/TimSort.java new file mode 100644 index 00000000..f4d00b9f --- /dev/null +++ b/TimSort.java @@ -0,0 +1,84 @@ +import java.util.Arrays; +public final class TimSort { + + static int RUN = 32; + public static void insertionSort(int[] arr, int left, int right) { + for (int i = left + 1; i <= right; i++) { + int temp = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > temp && j >= left) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = temp; + } + } + + public static void merge(int[] arr, int left, int mid, int right) { + + int leftArryLen = mid - left + 1, rightArrLen = right - mid; + int[] leftArr = new int[leftArryLen]; + int[] rightArr = new int[rightArrLen]; + + for (int x = 0; x < leftArryLen; x++) { + leftArr[x] = arr[left + x]; + } + + for (int x = 0; x < rightArrLen; x++) { + rightArr[x] = arr[mid + 1 + x]; + } + + int i = 0; + int j = 0; + int k = left; + + while (i < leftArryLen && j < rightArrLen) { + if (leftArr[i] <= rightArr[j]) { + arr[k] = leftArr[i]; + i++; + } else { + arr[k] = rightArr[j]; + j++; + } + k++; + } + + while (i < leftArryLen) { + arr[k] = leftArr[i]; + k++; + i++; + } + + while (j < rightArrLen) { + arr[k] = rightArr[j]; + k++; + j++; + } + } + + public static void timSort(int[] arr) { + int length = arr.length; + + // Sort individual subarrays of size THRESHOLD + for (int i = 0; i < length; i += RUN) { + // perform insertion sort + insertionSort(arr, i, Math.min((i + 31), (length - 1))); + } + + for (int size = RUN; size < length; size = 2 * size) { + for (int left = 0; left < length; left += 2 * size) { + int mid = left + size - 1; + int right = Math.min((left + 2 * size - 1), (length - 1)); + // perform merge sort + merge(arr, left, mid, right); + } + } + } + + public static void main(String[] args) { + int[] arr = { 10, 3, 2, 19, 7, 15, 23, 13, 1 }; + System.out.println(Arrays.toString(arr)); + timSort(arr); + System.out.println(Arrays.toString(arr)); + } +} diff --git a/Timesort.java b/Timesort.java new file mode 100644 index 00000000..f638dd13 --- /dev/null +++ b/Timesort.java @@ -0,0 +1,142 @@ + +class GFG +{ + + static int MIN_MERGE = 32; + + public static int minRunLength(int n) + { + assert n >= 0; + + // Becomes 1 if any 1 bits are shifted off + int r = 0; + while (n >= MIN_MERGE) + { + r |= (n & 1); + n >>= 1; + } + return n + r; + } + + + public static void insertionSort(int[] arr, int left, + int right) + { + for (int i = left + 1; i <= right; i++) + { + int temp = arr[i]; + int j = i - 1; + while (j >= left && arr[j] > temp) + { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = temp; + } + } + + // Merge function merges the sorted runs + public static void merge(int[] arr, int l, + int m, int r) + { + // Original array is broken in two parts + // left and right array + int len1 = m - l + 1, len2 = r - m; + int[] left = new int[len1]; + int[] right = new int[len2]; + for (int x = 0; x < len1; x++) + { + left[x] = arr[l + x]; + } + for (int x = 0; x < len2; x++) + { + right[x] = arr[m + 1 + x]; + } + + int i = 0; + int j = 0; + int k = l; + + while (i < len1 && j < len2) + { + if (left[i] <= right[j]) + { + arr[k] = left[i]; + i++; + } + else { + arr[k] = right[j]; + j++; + } + k++; + } + + while (i < len1) + { + arr[k] = left[i]; + k++; + i++; + } + + while (j < len2) + { + arr[k] = right[j]; + k++; + j++; + } + } + + public static void timSort(int[] arr, int n) + { + int minRun = minRunLength(MIN_MERGE); + + // Sort individual subarrays of size RUN + for (int i = 0; i < n; i += minRun) + { + insertionSort(arr, i, + Math.min((i + MIN_MERGE - 1), (n - 1))); + } + + + for (int size = minRun; size < n; size = 2 * size) + { + for (int left = 0; left < n; + left += 2 * size) + { + + int mid = left + size - 1; + int right = Math.min((left + 2 * size - 1), + (n - 1)); + + if(mid < right) + merge(arr, left, mid, right); + } + } + } + + // Utility function to print the Array + public static void printArray(int[] arr, int n) + { + for (int i = 0; i < n; i++) { + System.out.print(arr[i] + " "); + } + System.out.print("\n"); + } + + // Driver code + public static void main(String[] args) + { + int[] arr = { -2, 7, 15, -14, 0, 15, 0, 7, + -7, -4, -13, 5, 8, -14, 12 }; + int n = arr.length; + System.out.println("Given Array is"); + printArray(arr, n); + + timSort(arr, n); + + System.out.println("After Sorting Array is"); + printArray(arr, n); + } +} + + diff --git a/Tower_Of_Hanoi.c b/Tower_Of_Hanoi.c new file mode 100644 index 00000000..9c45cafd --- /dev/null +++ b/Tower_Of_Hanoi.c @@ -0,0 +1,26 @@ +//program for tower of hanoi +#include +#include +void main() +{ + int n; + char A='A',B='B',C='C'; + void hanoi(int,char,char,char); + printf("Enter the number of disks : "); + scanf("%d",&n); + printf("\n\n Tower of Hanoi problem with %d disks\n",n); + printf("Sequence of moves :\n"); + hanoi(n,A,B,C); + getch(); +} +void hanoi(int n,char A,char B,char C) +{ + if(n==1) + printf("\n Move disk 1 from rod %c to rod %c",A,C); + else + { + hanoi(n-1,A,C,B); + printf("\n Move disk %d from rod %c to rod %c",n,A,C); + hanoi(n-1,B,A,C); + } +} diff --git a/Transpose_of_Matrix.java b/Transpose_of_Matrix.java new file mode 100644 index 00000000..0cc2dcca --- /dev/null +++ b/Transpose_of_Matrix.java @@ -0,0 +1,30 @@ +public class MatrixTransposeExample{ +public static void main(String args[]){ +//creating a matrix +int original[][]={{1,3,4},{2,4,3},{3,4,5}}; + +//creating another matrix to store transpose of a matrix +int transpose[][]=new int[3][3]; //3 rows and 3 columns + +//Code to transpose a matrix +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +transpose[i][j]=original[j][i]; +} +} + +System.out.println("Printing Matrix without transpose:"); +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +System.out.print(original[i][j]+" "); +} +System.out.println();//new line +} +System.out.println("Printing Matrix After Transpose:"); +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +System.out.print(transpose[i][j]+" "); +} +System.out.println();//new line +} +}} diff --git a/TrappingRainWater.java b/TrappingRainWater.java new file mode 100644 index 00000000..5527a65e --- /dev/null +++ b/TrappingRainWater.java @@ -0,0 +1,36 @@ +// Given n non-negative integers representing an elevation map where the width of each bar is 1, +// compute how much water it can trap after raining. + +// Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +// Output: 6 +// Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. + +// Time complexity : O(n) +// Space Complexity : O(n) + O(n) +class Solution { + + public int trap(int[] height) { + + int n = height.length, ans = 0, i; + + // store left max for every elevation map in array + // store -1 if rain water can't trapped by any elevation map, else store max + int[] left = new int[n]; + left[0] = height[0]; + for(i = 1; i < n; i++) + left[i] = Math.max(left[i-1], height[i]); + + // store right max for every elevation map in array + int[] right = new int[n]; + right[n-1] = height[n-1]; + for(i = n-2; i >= 0; i--) + right[i] = Math.max(right[i+1], height[i]); + + // compare left and right max for every elvation map + // for ith elevation map trapped water will be min(leftmax, rightmax)-height[i] + for(i = 0; i < n; i++) + ans += Math.max(0, Math.min((left[i]-height[i]), (right[i]-height[i]))); + + return ans; + } +} diff --git a/Tree/All Traversal In One go b/Tree/All Traversal In One go new file mode 100644 index 00000000..877c87a5 --- /dev/null +++ b/Tree/All Traversal In One go @@ -0,0 +1,201 @@ +package com.trees; + +import java.util.*; + +public class preoreder { + static class TreeNode { + int data; + TreeNode left; + TreeNode right; +// represationOfTree.Node right; + + public TreeNode(int key) { + data = key; + left = null; + right = null; + + } + + static void preorderTriversal(TreeNode root) { + if (root == null) { + return; + } + System.out.println(root.data); + preorderTriversal(root.left); + preorderTriversal(root.right); + + } + + static void inorderTriversal(TreeNode root) { + if (root == null) { + return; + } + inorderTriversal(root.left); + System.out.println(root.data); + inorderTriversal(root.right); + } + + static void postorder(TreeNode root) { + if (root == null) { + return; + } + postorder(root.left); + postorder(root.right); + System.out.println(root.data); + } + } + + public List> levelOrder(TreeNode root) { + + Queue queue = new LinkedList(); + List> wrapList = new LinkedList>(); + // base case + if (root == null) { + return wrapList; + } + // add the value of root into the queue + queue.offer(root); + while (!queue.isEmpty()) { + int levelNum = queue.size(); + List sublist = new LinkedList(); + for (int i = 0; i < levelNum; i++) { + if (queue.peek().left != null) { + queue.offer(queue.peek().left); + } + if (queue.peek().right != null) { + queue.offer(queue.peek().right); + } + sublist.add(queue.poll().data); + + } + wrapList.add(sublist); + + } + return wrapList; + } + + // itataviely + public List preorderTraversal(TreeNode root) { + List preorder = new ArrayList<>(); + // base case + if (root == null) { + return preorder; + } + Stack st = new Stack(); + st.push(root); + while (!st.isEmpty()) { + root = st.pop(); + + preorder.add(root.data); + if (root.right != null) { + st.push(root.right); + } + if (root.left != null) { + st.push(root.left); + } + } + return preorder; + + + } + + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + Stack st = new Stack(); + if (root == null) { + return ans; + } + TreeNode node = root; + while (true) { + if (node != null) { + st.push(node); + node = node.left; + } else { + if (st.isEmpty()) { + break; + } + node = st.pop(); + ans.add(node.data); + node = node.right; + + } + } + return ans; + } + + // post order itrattevealy + public List postorderTraversal(TreeNode cur) { + List postorder = new ArrayList<>(); + if (cur == null){ + return postorder; + } + Stack st = new Stack<>(); + while (cur != null || !st.isEmpty()){ + if (cur != null){ + st.push(cur); + cur = cur.left; + + } + else { + TreeNode temp = st.peek().right; + if (temp == null){ + temp = st.peek(); + st.pop(); + postorder.add(temp.data); + + } + else cur = temp; + } + } + return postorder; + + } + // all trevelsal in one go + class Pair{ + TreeNode node; + int num ; + Pair(TreeNode node,int num){ + this.node = node; + this.num = num; + } + } + public void allTraversal(TreeNode root){ + Stack st = new Stack(); + st.push(new Pair(root,1)); + List pre = new ArrayList<>(); + List in = new ArrayList<>(); + List post = new ArrayList<>(); + // base case is + if (root == null) return; + while (!st.isEmpty()){ + Pair it = st.pop(); + + if (it.num == 1){ + pre.add(it.node.data); + it.num++; + st.push(it); + if (it.node.left != null){ + st.push( new Pair(it.node.left,1)); + } + + } + else if (it.num == 2 ){ + in.add(it.node.data); + it.num++; + st.push(it); + if (it.node.right != null){ + st.push(new Pair(it.node.right,1)); + + } + } + else + { + post.add(it.node.data); + } + } + + + } + +} + diff --git a/Tree/DeletionInRedBlacKTree.java b/Tree/DeletionInRedBlacKTree.java new file mode 100644 index 00000000..f31038aa --- /dev/null +++ b/Tree/DeletionInRedBlacKTree.java @@ -0,0 +1,407 @@ +// Implementing Red-Black Tree in Java + +class Node { + int data; + Node parent; + Node left; + Node right; + int color; +} + +public class RedBlackTree { + private Node root; + private Node TNULL; + + // Preorder + private void preOrderHelper(Node node) { + if (node != TNULL) { + System.out.print(node.data + " "); + preOrderHelper(node.left); + preOrderHelper(node.right); + } + } + + // Inorder + private void inOrderHelper(Node node) { + if (node != TNULL) { + inOrderHelper(node.left); + System.out.print(node.data + " "); + inOrderHelper(node.right); + } + } + + // Post order + private void postOrderHelper(Node node) { + if (node != TNULL) { + postOrderHelper(node.left); + postOrderHelper(node.right); + System.out.print(node.data + " "); + } + } + + // Search the tree + private Node searchTreeHelper(Node node, int key) { + if (node == TNULL || key == node.data) { + return node; + } + + if (key < node.data) { + return searchTreeHelper(node.left, key); + } + return searchTreeHelper(node.right, key); + } + + // Balance the tree after deletion of a node + private void fixDelete(Node x) { + Node s; + while (x != root && x.color == 0) { + if (x == x.parent.left) { + s = x.parent.right; + if (s.color == 1) { + s.color = 0; + x.parent.color = 1; + leftRotate(x.parent); + s = x.parent.right; + } + + if (s.left.color == 0 && s.right.color == 0) { + s.color = 1; + x = x.parent; + } else { + if (s.right.color == 0) { + s.left.color = 0; + s.color = 1; + rightRotate(s); + s = x.parent.right; + } + + s.color = x.parent.color; + x.parent.color = 0; + s.right.color = 0; + leftRotate(x.parent); + x = root; + } + } else { + s = x.parent.left; + if (s.color == 1) { + s.color = 0; + x.parent.color = 1; + rightRotate(x.parent); + s = x.parent.left; + } + + if (s.right.color == 0 && s.right.color == 0) { + s.color = 1; + x = x.parent; + } else { + if (s.left.color == 0) { + s.right.color = 0; + s.color = 1; + leftRotate(s); + s = x.parent.left; + } + + s.color = x.parent.color; + x.parent.color = 0; + s.left.color = 0; + rightRotate(x.parent); + x = root; + } + } + } + x.color = 0; + } + + private void rbTransplant(Node u, Node v) { + if (u.parent == null) { + root = v; + } else if (u == u.parent.left) { + u.parent.left = v; + } else { + u.parent.right = v; + } + v.parent = u.parent; + } + + private void deleteNodeHelper(Node node, int key) { + Node z = TNULL; + Node x, y; + while (node != TNULL) { + if (node.data == key) { + z = node; + } + + if (node.data <= key) { + node = node.right; + } else { + node = node.left; + } + } + + if (z == TNULL) { + System.out.println("Couldn't find key in the tree"); + return; + } + + y = z; + int yOriginalColor = y.color; + if (z.left == TNULL) { + x = z.right; + rbTransplant(z, z.right); + } else if (z.right == TNULL) { + x = z.left; + rbTransplant(z, z.left); + } else { + y = minimum(z.right); + yOriginalColor = y.color; + x = y.right; + if (y.parent == z) { + x.parent = y; + } else { + rbTransplant(y, y.right); + y.right = z.right; + y.right.parent = y; + } + + rbTransplant(z, y); + y.left = z.left; + y.left.parent = y; + y.color = z.color; + } + if (yOriginalColor == 0) { + fixDelete(x); + } + } + + // Balance the node after insertion + private void fixInsert(Node k) { + Node u; + while (k.parent.color == 1) { + if (k.parent == k.parent.parent.right) { + u = k.parent.parent.left; + if (u.color == 1) { + u.color = 0; + k.parent.color = 0; + k.parent.parent.color = 1; + k = k.parent.parent; + } else { + if (k == k.parent.left) { + k = k.parent; + rightRotate(k); + } + k.parent.color = 0; + k.parent.parent.color = 1; + leftRotate(k.parent.parent); + } + } else { + u = k.parent.parent.right; + + if (u.color == 1) { + u.color = 0; + k.parent.color = 0; + k.parent.parent.color = 1; + k = k.parent.parent; + } else { + if (k == k.parent.right) { + k = k.parent; + leftRotate(k); + } + k.parent.color = 0; + k.parent.parent.color = 1; + rightRotate(k.parent.parent); + } + } + if (k == root) { + break; + } + } + root.color = 0; + } + + private void printHelper(Node root, String indent, boolean last) { + if (root != TNULL) { + System.out.print(indent); + if (last) { + System.out.print("R----"); + indent += " "; + } else { + System.out.print("L----"); + indent += "| "; + } + + String sColor = root.color == 1 ? "RED" : "BLACK"; + System.out.println(root.data + "(" + sColor + ")"); + printHelper(root.left, indent, false); + printHelper(root.right, indent, true); + } + } + + public RedBlackTree() { + TNULL = new Node(); + TNULL.color = 0; + TNULL.left = null; + TNULL.right = null; + root = TNULL; + } + + public void preorder() { + preOrderHelper(this.root); + } + + public void inorder() { + inOrderHelper(this.root); + } + + public void postorder() { + postOrderHelper(this.root); + } + + public Node searchTree(int k) { + return searchTreeHelper(this.root, k); + } + + public Node minimum(Node node) { + while (node.left != TNULL) { + node = node.left; + } + return node; + } + + public Node maximum(Node node) { + while (node.right != TNULL) { + node = node.right; + } + return node; + } + + public Node successor(Node x) { + if (x.right != TNULL) { + return minimum(x.right); + } + + Node y = x.parent; + while (y != TNULL && x == y.right) { + x = y; + y = y.parent; + } + return y; + } + + public Node predecessor(Node x) { + if (x.left != TNULL) { + return maximum(x.left); + } + + Node y = x.parent; + while (y != TNULL && x == y.left) { + x = y; + y = y.parent; + } + + return y; + } + + public void leftRotate(Node x) { + Node y = x.right; + x.right = y.left; + if (y.left != TNULL) { + y.left.parent = x; + } + y.parent = x.parent; + if (x.parent == null) { + this.root = y; + } else if (x == x.parent.left) { + x.parent.left = y; + } else { + x.parent.right = y; + } + y.left = x; + x.parent = y; + } + + public void rightRotate(Node x) { + Node y = x.left; + x.left = y.right; + if (y.right != TNULL) { + y.right.parent = x; + } + y.parent = x.parent; + if (x.parent == null) { + this.root = y; + } else if (x == x.parent.right) { + x.parent.right = y; + } else { + x.parent.left = y; + } + y.right = x; + x.parent = y; + } + + public void insert(int key) { + Node node = new Node(); + node.parent = null; + node.data = key; + node.left = TNULL; + node.right = TNULL; + node.color = 1; + + Node y = null; + Node x = this.root; + + while (x != TNULL) { + y = x; + if (node.data < x.data) { + x = x.left; + } else { + x = x.right; + } + } + + node.parent = y; + if (y == null) { + root = node; + } else if (node.data < y.data) { + y.left = node; + } else { + y.right = node; + } + + if (node.parent == null) { + node.color = 0; + return; + } + + if (node.parent.parent == null) { + return; + } + + fixInsert(node); + } + + public Node getRoot() { + return this.root; + } + + public void deleteNode(int data) { + deleteNodeHelper(this.root, data); + } + + public void printTree() { + printHelper(this.root, "", true); + } + + public static void main(String[] args) { + RedBlackTree bst = new RedBlackTree(); + bst.insert(55); + bst.insert(40); + bst.insert(65); + bst.insert(60); + bst.insert(75); + bst.insert(57); + bst.printTree(); + + System.out.println("\nAfter deleting:"); + bst.deleteNode(40); + bst.printTree(); + } +} diff --git a/Tree/TreeImplementationLinkedList.java b/Tree/TreeImplementationLinkedList.java new file mode 100644 index 00000000..93304d88 --- /dev/null +++ b/Tree/TreeImplementationLinkedList.java @@ -0,0 +1,67 @@ +package Tree; + +import java.util.Scanner; + +public class TreeImplementationLinkedList { + + static Scanner sc=null; + public static void main(String[] args) { + + sc=new Scanner(System.in); + + Node root= createTree(); + inOrder(root); + + } + + static Node createTree() + { + Node root = null; + System.out.println("Enter Data:- "); + int data= sc.nextInt(); + + if (data==-1) return null; + + root=new Node(data); + + System.out.println("Enter Left for " + data ); + root.left=createTree(); + + System.out.println("Enter Right for " + data ); + root.right=createTree(); + + return root; + } + + static void inOrder(Node root) { + if(root == null) return; + + inOrder(root.left); + System.out.print(root.data+" "); + inOrder(root.right); + } + + static void preOrder(Node root) { + if(root == null) return; + System.out.print(root.data+" "); + preOrder(root.left); + preOrder(root.right); + } + + static void postOrder(Node root) { + if(root == null) return; + + postOrder(root.left); + postOrder(root.right); + System.out.print(root.data+" "); + } +} +class Node{ + Node left,right; + int data; + + public Node(int data) + { + this.data=data; + } +} \ No newline at end of file diff --git a/Tree/balanced_tree.java b/Tree/balanced_tree.java new file mode 100644 index 00000000..a6f86d22 --- /dev/null +++ b/Tree/balanced_tree.java @@ -0,0 +1,124 @@ +import java.io.*; +import java.util.*; + +public class Main { + public static class Node { + int data; + Node left; + Node right; + + Node(int data, Node left, Node right) { + this.data = data; + this.left = left; + this.right = right; + } + } + + public static class Pair { + Node node; + int state; + + Pair(Node node, int state) { + this.node = node; + this.state = state; + } + } + + public static Node construct(Integer[] arr) { + Node root = new Node(arr[0], null, null); + Pair rtp = new Pair(root, 1); + + Stack st = new Stack<>(); + st.push(rtp); + + int idx = 0; + while (st.size() > 0) { + Pair top = st.peek(); + if (top.state == 1) { + idx++; + if (arr[idx] != null) { + top.node.left = new Node(arr[idx], null, null); + Pair lp = new Pair(top.node.left, 1); + st.push(lp); + } else { + top.node.left = null; + } + + top.state++; + } else if (top.state == 2) { + idx++; + if (arr[idx] != null) { + top.node.right = new Node(arr[idx], null, null); + Pair rp = new Pair(top.node.right, 1); + st.push(rp); + } else { + top.node.right = null; + } + + top.state++; + } else { + st.pop(); + } + } + + return root; + } + + public static void display(Node node) { + if (node == null) { + return; + } + + String str = ""; + str += node.left == null ? "." : node.left.data + ""; + str += " <- " + node.data + " -> "; + str += node.right == null ? "." : node.right.data + ""; + System.out.println(str); + + display(node.left); + display(node.right); + } + + public static class BalPair { + int ht; + boolean isBal; + } + + public static BalPair isBalanced(Node node){ + if(node == null){ + BalPair bp = new BalPair(); + bp.ht = -1; + bp.isBal = true; + return bp; + } + + BalPair lp = isBalanced(node.left); + BalPair rp = isBalanced(node.right); + + BalPair mp = new BalPair(); + mp.ht = Math.max(lp.ht, rp.ht) + 1; + mp.isBal = lp.isBal && rp.isBal && Math.abs(lp.ht - rp.ht) <= 1; + + return mp; + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + Integer[] arr = new Integer[n]; + String[] values = br.readLine().split(" "); + for (int i = 0; i < n; i++) { + if (values[i].equals("n") == false) { + arr[i] = Integer.parseInt(values[i]); + } else { + arr[i] = null; + } + } + + Node root = construct(arr); + BalPair bp = isBalanced(root); + System.out.println(bp.isBal); + } + +} + diff --git a/Tree/deletionBinaryTree.java b/Tree/deletionBinaryTree.java new file mode 100644 index 00000000..b1a2704b --- /dev/null +++ b/Tree/deletionBinaryTree.java @@ -0,0 +1,156 @@ +// Java program to delete element +// in binary tree +import java.util.LinkedList; +import java.util.Queue; + +class GFG{ + +// A binary tree node has key, pointer to +// left child and a pointer to right child +static class Node +{ + int key; + Node left, right; + + // Constructor + Node(int key) + { + this.key = key; + left = null; + right = null; + } +} + +static Node root; +static Node temp = root; + +// Inorder traversal of a binary tree +static void inorder(Node temp) +{ + if (temp == null) + return; + + inorder(temp.left); + System.out.print(temp.key + " "); + inorder(temp.right); +} + +// Function to delete deepest +// element in binary tree +static void deleteDeepest(Node root, + Node delNode) +{ + Queue q = new LinkedList(); + q.add(root); + + Node temp = null; + + // Do level order traversal until last node + while (!q.isEmpty()) + { + temp = q.peek(); + q.remove(); + + if (temp == delNode) + { + temp = null; + return; + + } + if (temp.right!=null) + { + if (temp.right == delNode) + { + temp.right = null; + return; + } + else + q.add(temp.right); + } + + if (temp.left != null) + { + if (temp.left == delNode) + { + temp.left = null; + return; + } + else + q.add(temp.left); + } +} +} + +// Function to delete given element +// in binary tree +static void delete(Node root, int key) +{ + if (root == null) + return; + + if (root.left == null && + root.right == null) + { + if (root.key == key) + { + root=null; + return; + } + else + return; + } + + Queue q = new LinkedList(); + q.add(root); + Node temp = null, keyNode = null; + + // Do level order traversal until + // we find key and last node. + while (!q.isEmpty()) + { + temp = q.peek(); + q.remove(); + + if (temp.key == key) + keyNode = temp; + + if (temp.left != null) + q.add(temp.left); + + if (temp.right != null) + q.add(temp.right); + } + + if (keyNode != null) + { + int x = temp.key; + deleteDeepest(root, temp); + keyNode.key = x; + } +} + +// Driver code +public static void main(String args[]) +{ + root = new Node(10); + root.left = new Node(11); + root.left.left = new Node(7); + root.left.right = new Node(12); + root.right = new Node(9); + root.right.left = new Node(15); + root.right.right = new Node(8); + + System.out.print("Inorder traversal " + + "before deletion:"); + inorder(root); + + int key = 11; + delete(root, key); + + System.out.print("\nInorder traversal " + + "after deletion:"); + inorder(root); +} +} + +// This code is contributed by Ravi Kant Verma diff --git a/Tree/treeds b/Tree/treeds new file mode 100644 index 00000000..a803c646 --- /dev/null +++ b/Tree/treeds @@ -0,0 +1,165 @@ +import java.util.*; + +class Tree{ + static node create(){ + Scanner sc=new Scanner(System.in); + node root=null; + System.out.println("Enter the data "); + int data=sc.nextInt(); + if(data==-1){ + return null; + } + root=new node(data); + System.out.println("enter data to left of root "+root.data); + root.left=create(); + System.out.println("enter data to right of root "+root.data); + root.right=create(); + return root; + } + public static int height(node root){ + if(root==null){ + return 0; + } + return Math.max(height(root.left),height(root.right))+1; + } + public static class node{ + node left,right; + int data; + node(int data){ + this.data=data; + left=null; + right=null; + } + } + //preorder traversal in tree data structure + public static void preoder(node root){ + if(root==null){ + return; + } + System.out.print(root.data+" "); + preoder(root.left); + preoder(root.right); + } + //finding maximum in tree + public static int maximum(node root){ + if(root==null) + return Integer.MIN_VALUE; + return Math.max(root.data,Math.max(maximum(root.left),maximum(root.right))); + } + //finding minimum in tree + public static int minimum(node root){ + if(root==null) + return Integer.MAX_VALUE; + return Math.min(root.data,Math.min(minimum(root.left),minimum(root.right))); + } + //postorder traversal in tree + public static void postorder(node root){ + if(root==null){ + return; + } + postorder(root.left); + postorder(root.right); + System.out.print(root.data+" "); + } + //inoreder traveral in tree + public static void inorder(node root){ + if(root==null){ + return; + } + inorder(root.left); + System.out.print(root.data+" "); + inorder(root.right); + } + //level order traversal in tree + public static void levelorder(node root){ + Queue q=new LinkedList<>(); + q.add(root); + while(!q.isEmpty()){ + node cur=q.poll(); + System.out.print(cur.data+" "); + if(cur.left!=null){ + q.add(cur.left); + } + if(cur.right!=null){ + q.add(cur.right); + } + } + } + //int size of tree + public static int size(node root) { + if(root == null) + return 0; + return size(root.left)+size(root.right)+1; + } + public static void printleftview(node root){ + ArrayList list=new ArrayList<>(); + printviewleft(root, list, 0); + for(node cur: list){ + System.out.print(cur.data+" "); + } + } + public static void printviewleft(node root,ArrayList list,int level){ + if(root==null){ + return; + } + if(list.get(level)==null){ + list.set(level,root); + } + printviewleft(root.left, list, level+1); + printviewleft(root.right, list, level+1); + } + + public static void levelordernextlevel(node root){ + Queue q1=new LinkedList<>(); + q1.add(root); + q1.add(null); + while(!q1.isEmpty()){ + node cur=q1.poll(); + if(cur==null){ + if(q1.isEmpty()){ + return; + } + q1.add(null); + System.out.println(); + continue; + } + System.out.print(cur.data+" "); + + if(cur.left!=null){ + q1.add(cur.left); + } + if(cur.right!=null){ + q1.add(cur.right); + } + } + } + + + public static void main(String [] args){ + node root=create(); + System.out.print("preorder:-"); + preoder(root); + System.out.println(); + System.out.print("inorder:-"); + inorder(root); + System.out.println(); + System.out.print("postorder:-"); + postorder(root); + System.out.println(); + System.out.print("levelorder:-"); + levelorder(root); + System.out.println(); + System.out.print("levelorder next line:-"); + levelordernextlevel(root); + System.out.println(); + System.out.print("height of tree is "+ height(root)); + System.out.println(); + System.out.print("size of tree is "+ size(root)); + System.out.println(); + System.out.print("maximum of tree is "+ maximum(root)); + System.out.println(); + System.out.print("minimum of tree is "+ minimum(root)); + System.out.println(); + printleftview(root); + } +} diff --git a/Tree_traversal.java b/Tree_traversal.java new file mode 100644 index 00000000..33bede17 --- /dev/null +++ b/Tree_traversal.java @@ -0,0 +1,75 @@ +class Node { + public int value; + public Node left, right; + + public Node(int element) + { + value = element; + left = right = null; + } +} + +class Tree { + Node root; /* root of the tree */ + + Tree() { root = null; } + /*function to print the nodes of given binary in Preorder*/ + void traversePreorder(Node node) + { + if (node == null) + return; + System.out.print(node.value + " "); + traversePreorder(node.left); + traversePreorder(node.right); + } + /*function to print the nodes of given binary in Inorder*/ + void traverseInorder(Node node) + { + if (node == null) + return; + traverseInorder(node.left); + System.out.print(node.value + " "); + traverseInorder(node.right); + } + /*function to print the nodes of given binary in Postorder*/ + void traversePostorder(Node node) + { + if (node == null) + return; + traversePostorder(node.left); + traversePostorder(node.right); + System.out.print(node.value + " "); + } + + + void traversePreorder() { traversePreorder(root); } + void traverseInorder() { traverseInorder(root); } + void traversePostorder() { traversePostorder(root); } + + public static void main(String args[]) + { + Tree pt = new Tree(); + pt.root = new Node(36); + pt.root.left = new Node(26); + pt.root.right = new Node(46); + pt.root.left.left = new Node(21); + pt.root.left.right = new Node(31); + pt.root.left.left.left = new Node(11); + pt.root.left.left.right = new Node(24); + pt.root.right.left = new Node(41); + pt.root.right.right = new Node(56); + pt.root.right.right.left = new Node(51); + pt.root.right.right.right = new Node(66); + + System.out.println(); + System.out.println("The Preorder traversal of given binary tree is - "); + pt.traversePreorder(); + System.out.println("\n"); + System.out.println("The Inorder traversal of given binary tree is - "); + pt.traverseInorder(); + System.out.println("\n"); + System.out.println("The Postorder traversal of given binary tree is - "); + pt.traversePostorder(); + System.out.println(); + } +} \ No newline at end of file diff --git a/Treecut.cpp b/Treecut.cpp new file mode 100644 index 00000000..b5a44042 --- /dev/null +++ b/Treecut.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; +bool isPossible(long long *arr,long long n,long long mid,long long k){ + int sum=0; + for(long long i=0;i0){ + sum=sum+arr[i]-mid; + } + if(sum>=k){ + return true; + } + } + return false; +} +int main() { + long long n,k; + cin>>n>>k; + long long arr[n]; + for(long long i=0;i>arr[i]; + } + sort(arr,arr+n); + long long ans=-1; + long long s=0; + long long e=arr[n-1]; + long long mid=s+(e-s)/2; + while(s<=e){ + if(isPossible(arr,n,mid,k)){ + s=mid+1; + ans=mid; + } + else{ + e=mid-1; + } + mid=s+(e-s)/2; + } + cout< s = new HashSet(); + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.contains(curr_sum - A[j])) + { + System.out.printf("Triplet is %d, + %d, %d", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.add(A[j]); + } + } + + + return false; + } + + /* Driver code */ + public static void main(String[] args) + { + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + + find3Numbers(A, arr_size, sum); + } +} + + diff --git a/Vowel or Consonant b/Vowel or Consonant new file mode 100644 index 00000000..2dad978c --- /dev/null +++ b/Vowel or Consonant @@ -0,0 +1,7 @@ +ch = input("Enter a character: ") + +if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I' + or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'): + print(ch, "is a Vowel") +else: + print(ch, "is a Consonant") diff --git a/WaterConnectionProblem.java b/WaterConnectionProblem.java new file mode 100644 index 00000000..bcadb3a2 --- /dev/null +++ b/WaterConnectionProblem.java @@ -0,0 +1,109 @@ + +// Java program to find efficient +// solution for the network +import java.util.*; + +class Optimalsolution { + + // number of houses and number + // of pipes + static int number_of_houses, number_of_pipes; + + // Array rd stores the + // ending vertex of pipe + static int ending_vertex_of_pipes[] = new int[1100]; + + // Array wd stores the value + // of diameters between two pipes + static int diameter_of_pipes[] = new int[1100]; + + // Array cd stores the + // starting end of pipe + static int starting_vertex_of_pipes[] = new int[1100]; + + // arraylist a, b, c are used + // to store the final output + static List a = new ArrayList(); + + static List b = new ArrayList(); + + static List c = new ArrayList(); + + static int ans; + + static int dfs(int w) + { + if (starting_vertex_of_pipes[w] == 0) + return w; + if (diameter_of_pipes[w] < ans) + ans = diameter_of_pipes[w]; + + return dfs(starting_vertex_of_pipes[w]); + } + + // Function to perform calculations. + static void solve(int arr[][]) + { + int i = 0; + + while (i < number_of_pipes) { + + int q = arr[i][0]; + int h = arr[i][1]; + int t = arr[i][2]; + + starting_vertex_of_pipes[q] = h; + diameter_of_pipes[q] = t; + ending_vertex_of_pipes[h] = q; + i++; + } + + a = new ArrayList(); + b = new ArrayList(); + c = new ArrayList(); + + for (int j = 1; j <= number_of_houses; ++j) + + /*If a pipe has no ending vertex + but has starting vertex i.e is + an outgoing pipe then we need + to start DFS with this vertex.*/ + if (ending_vertex_of_pipes[j] == 0 + && starting_vertex_of_pipes[j] > 0) { + ans = 1000000000; + int w = dfs(j); + + // We put the details of + // component in final output + // array + a.add(j); + b.add(w); + c.add(ans); + } + + System.out.println(a.size()); + + for (int j = 0; j < a.size(); ++j) + System.out.println(a.get(j) + " " + b.get(j) + + " " + c.get(j)); + } + + // main function + public static void main(String args[]) + { + number_of_houses = 9; + number_of_pipes = 6; + + // set the value of the array + // to zero + for (int i = 0; i < 1100; i++) + ending_vertex_of_pipes[i] + = starting_vertex_of_pipes[i] + = diameter_of_pipes[i] = 0; + + int arr[][] + = { { 7, 4, 98 }, { 5, 9, 72 }, { 4, 6, 10 }, + { 2, 8, 22 }, { 9, 7, 17 }, { 3, 1, 66 } }; + solve(arr); + } +} diff --git a/WordSearch.java b/WordSearch.java new file mode 100644 index 00000000..3e6f6d6d --- /dev/null +++ b/WordSearch.java @@ -0,0 +1,70 @@ +// https://leetcode.com/problems/word-search/ + +public class WordSearch { + public static void main(String[] args) { + char[][] board = { + {'A','B','C','E'}, + {'S','F','C','S'}, + {'A','D','E','E'} + }; + boolean ans = exist(board, "ABCCED"); + System.out.println(ans); + } + public static boolean exist(char[][] board, String word) { + + for(int i = 0; i < board.length; i++){ + for(int j = 0; j < board[0].length; j++){ + if(board[i][j] == word.charAt(0)){ + char temp = board[i][j]; + board[i][j] = '0'; + if(isValid(board, i, j, 1, word)){ + return true; + } + board[i][j] = temp; + } + } + } + + return false; + } + public static boolean isValid(char[][] board, int row, int col, int index, String word){ + if(index == word.length()){ + return true; + } + char temp; + if(col != 0 && board[row][col - 1] == word.charAt(index)){ + temp = board[row][col - 1]; + board[row][col - 1] = '0'; + if(isValid(board, row, col-1, index+1, word)){ + return true; + } + board[row][col-1] = temp; + } + if(col <= board[0].length-2 && board[row][col + 1] == word.charAt(index)){ + temp = board[row][col + 1]; + board[row][col + 1] = '0'; + if(isValid(board, row, col+1, index+1, word)){ + return true; + } + board[row][col+1] = temp; + } + if(row != 0 && board[row - 1][col] == word.charAt(index)){ + temp = board[row - 1][col]; + board[row - 1][col] = '0'; + if(isValid(board, row - 1, col, index+1, word)){ + return true; + } + board[row - 1][col] = temp; + } + if(row <= board.length - 2 && board[row + 1][col] == word.charAt(index)){ + temp = board[row + 1][col]; + board[row + 1][col] = '0'; + if(isValid(board, row + 1, col, index+1, word)){ + return true; + } + board[row + 1][col] = temp; + } + + return false; + } +} diff --git a/Zig-Zag_tree_traversal.java b/Zig-Zag_tree_traversal.java new file mode 100644 index 00000000..fb30027a --- /dev/null +++ b/Zig-Zag_tree_traversal.java @@ -0,0 +1,104 @@ +// Java implementation of a O(n) time method for +// Zigzag order traversal +import java.util.*; +public class Main { + // Class containing left and + // right child of current + // node and key value + static class Node { + + public int data; + public Node left, right; + + public Node(int data) + { + this.data = data; + left = right = null; + } + } + + // A utility function to create a new node + static Node newNode(int data) + { + Node node = new Node(data); + return node; + } + + // Function to print the zigzag traversal + static ArrayList zigZagTraversal(Node root) + { + + ArrayList ans = new ArrayList(); + // if there is no element in the tree,return empty + // arraylist + if (root == null) + return ans; + Queue q = new LinkedList(); + q.add(root); + // this variable helps to check if elements are to + // be added from left to right or right to left + boolean leftToRight = true; + while (q.size() > 0) { + int size = q.size(); + // this arraylist is used to store element at + // current level + ArrayList temp = new ArrayList<>(); + for (int i = 0; i < size; i++) { + Node curr = q.poll(); + if (curr.left != null) + q.add(curr.left); + if (curr.right != null) + q.add(curr.right); + temp.add(curr.data); + } + if (leftToRight) // at current level,add element + // from left to right to our + // answer + { + // do nothing + } + // we have to add element from to right to left + // and this can be done by reversing our temp + // arraylist + else { + Collections.reverse(temp); + } + // add element form temp arraylist to our ans + // arraylist + for (int i = 0; i < temp.size(); i++) { + ans.add(temp.get(i)); + } + // change the value of leftToRight from true to + // false or false to true for next iteration. + leftToRight = !(leftToRight); + } + // return our ans arraylist + return ans; + } + + public static void main(String[] args) + { + + // Arraylist to store the traversal order. + ArrayList ans; + + // create tree + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(7); + root.left.right = newNode(6); + root.right.left = newNode(5); + root.right.right = newNode(4); + System.out.println( + "ZigZag Order traversal of binary tree is"); + + ans = zigZagTraversal(root); + + for (int i = 0; i < ans.size(); + i++) { // to print the order + System.out.print(ans.get(i) + " "); + } + } +} +// this is contributed by harsh diff --git a/_24Operators.java b/_24Operators.java new file mode 100644 index 00000000..708764a6 --- /dev/null +++ b/_24Operators.java @@ -0,0 +1,101 @@ +import java.util.Scanner; + +public class _24Operators { + + void display() + { + double d = 67.54; + int i = (int)d; //casting double type to integer + System.out.println(i); + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Scanner reader = new Scanner(System.in); + + System.out.println("----Types of operator---- "); + + System.out.println("Unary operator:- "); + int num1 = +50; // it is optional 'cause its default + System.out.println("Unary Plus Operator: " + num1); + int num2 = -50; + System.out.println("Unary Minus Operator: " + num2); + + + System.out.println("\nArithmetic Operator:-"); + int num3 = 10 + 20; + System.out.println("Arithmetic Plus Operator: " + num3); + int num4 = 20 - 10; + System.out.println("Arithmetic Minus Operator: " + num4); + int num5 = 10 * 5; + System.out.println("Arithmetic Multiplication Operator: " + num5); + int num6 = 10 / 2; + System.out.println("Arithmetic Divide Operator: " + num6); + int num7 = 10 % 3; + System.out.println("Arithmetic Mudular Operator: " + num7); + + + int a = 20, b = 5, c = 20; + System.out.println("\nSwift Operator(Add, Sub, Pro, Div, Mod):- "); + int num8 = (a + b); + System.out.println("Swift Add Operator: " + num8); + + + System.out.println("\nRelational Operator(a=10, b=5, c=20):- "); + System.out.println("a > b is " + (a>b)); + System.out.println("a < b is " + (a= b is " + (a>=b)); + System.out.println("a <= b is " + (a<=b)); + System.out.println("a == c is " + (a==b)); + System.out.println("a != c is " + (a!=b)); + + a = 9; b = 8; c=15; + System.out.println("\nBitwise Operator(a=9, b=8, c=15):-"); + System.out.println("a & b is " + (a&b)); // bitwise AND + System.out.println("a ^ b is " + (a^b)); // bitwise exclusive OR + System.out.println("a | b is " + (a|b)); // bitwise inclusive OR + System.out.println("~2 is " + (~2)); // ~0010= 1101 = -3 + System.out.println("c >> 2 is " + (c >>2)); // right shift + System.out.println("c << 2 is " + (c <<2)); // left shift + + a = 10; b = 20; + System.out.println("\nLogical Operator(a=10, b=20, c=15):-"); + System.out.println("a<15 && b>15 is " + (a<15 && b>15)); + System.out.println("a=0 || b>15 is " + (a==0 || b>15)); + System.out.println("! b>15 is " + !(b>15)); + + + a = 10; b = 20; c = 30; + a = a > b ? (a > c ? a : c) : (b > c ? b : c); + System.out.println("\nCondition/Ternary Operator:-"); + System.out.println("The largest value is " + a); + + a = 10; b = 20; + System.out.println("\nAssignment Operator(a=10, b=20):-"); + System.out.println("a += b is " + (a += b)); + + a = 10; b = 20; + System.out.println("\nIncrement & Decreament Operator(a=10, b=20):-"); + System.out.println("++a is " + (++a)); // prefix + System.out.println("--b is " + (--b)); // prefix + + + System.out.println("\nSpecial Operator:-"); + System.out.println("1. Instaneof Operator:-"); + // create a variable of string type + String name = "MASQ"; + + // checks if name is instance of String + boolean check = name instanceof String; + System.out.println("Name is an instance of String: " + check); + + + System.out.println("\n2. Dot Operator:-"); + _24Operators doe = new _24Operators(); + doe.display(); //method calling + + reader.close(); + } + +} \ No newline at end of file diff --git a/_5factorial.java b/_5factorial.java new file mode 100644 index 00000000..ce4ea9fb --- /dev/null +++ b/_5factorial.java @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class _5factorial { + + public static void main(String[] args) { + + Scanner reader = new Scanner(System.in); + + System.out.println("Enter a number 1: "); + int n1 = reader.nextInt(); + int fact = 1; + + for (int i = 1; i <= n1; i++) { + + fact = fact * i; + } + System.out.println("Factorial value is " + fact); + + reader.close(); + } +} \ No newline at end of file diff --git a/abstract_class/Base.class b/abstract_class/Base.class new file mode 100644 index 00000000..ba8d2855 Binary files /dev/null and b/abstract_class/Base.class differ diff --git a/abstract_class/Derived.class b/abstract_class/Derived.class new file mode 100644 index 00000000..4a876c80 Binary files /dev/null and b/abstract_class/Derived.class differ diff --git a/abstract_class/Main.class b/abstract_class/Main.class new file mode 100644 index 00000000..468c7283 Binary files /dev/null and b/abstract_class/Main.class differ diff --git a/abstract_class/abstract.java b/abstract_class/abstract.java new file mode 100644 index 00000000..8e0b80c3 --- /dev/null +++ b/abstract_class/abstract.java @@ -0,0 +1,29 @@ +abstract class Base { + abstract void fun(); +} + +// Class 2 +class Derived extends Base { + void fun() + { + System.out.println("Derived fun() called"); + } +} + +// Class 3 +// Main class +class Main { + + // Main driver method + public static void main(String args[]) + { + + // Uncommenting the following line will cause + // compiler error as the line tries to create an + // instance of abstract class. Base b = new Base(); + + // We can have references of Base type. + Base b = new Derived(); + b.fun(); + } +} \ No newline at end of file diff --git a/abstract_method.txt b/abstract_method.txt new file mode 100644 index 00000000..11fe1a2f --- /dev/null +++ b/abstract_method.txt @@ -0,0 +1,36 @@ + /* Abstact Method in Java */ + +abstact class A //Superclass +{ + public abstract void Car(); +} + +class B extends A +{ + @Override + public void Car() + { + System.out.println("Anuj has Audi"); + } +} + +class C extends A +{ + @Override + public void Car() + { + System.out.println("Spandan has BMW"); + } +} + +class abstact_method +{ + public static void main(String[] a){ + A B_obj=new B(); // Reference of object class + B B_obj=new B(); // Instance of Class B + C C_obj=new C(); // Instance of Class C + B_obj.Car(); + C_obj.Car(); + } + +} \ No newline at end of file diff --git a/addTwoNumber.java b/addTwoNumber.java new file mode 100644 index 00000000..7fa0a479 --- /dev/null +++ b/addTwoNumber.java @@ -0,0 +1,16 @@ +import java.util.*; +import java.util.Scanner; +public class addTwoNumber { +public static void main (String[] args) { + + /* code */ + int a = 5; + int b = 10; + Scanner s = new Scanner(System.in); +int a = s.nextInt(); +int b = s.nextInt(); +System.out.println(a+b); + +} + +} \ No newline at end of file diff --git a/addstring.java b/addstring.java new file mode 100644 index 00000000..604e8239 --- /dev/null +++ b/addstring.java @@ -0,0 +1,47 @@ +// Source : https://leetcode.com/problems/add-strings/ +// Author : mohit parmar + +/*************************************************************************************** + * + * Given two non-negative numbers num1 and num2 represented as string, return the sum + * of num1 and num2. + * + * Note: + * + * The length of both num1 and num2 is + * Both num1 and num2 contains only digits 0-9. + * Both num1 and num2 does not contain any leading zero. + * You must not use any built-in BigInteger library or convert the inputs to integer + * directly. + ***************************************************************************************/ + +class Solution { +public: + string addStrings(string num1, string num2) { + string& longstr = ( num1.size() >= num2.size() ? num1 : num2 ); + string& shortstr = ( num1.size() < num2.size() ? num1 : num2 ); + + int longlen = longstr.size(); + int shortlen = shortstr.size(); + + char carry = 0; + int i, j; + + string result; + for (i = longlen-1, j=shortlen-1; i>=0; i--, j--) { + int add = 0; + if (j>=0) { + add = longstr[i] + shortstr[j] - 2 * '0' + carry; + }else{ + add = longstr[i] - '0' + carry; + } + carry = add/10; + result = char('0' + add % 10) + result; + } + + if (carry) { + result = '1' + result; + } + return result; + } +}; \ No newline at end of file diff --git a/aeonvdedn.c b/aeonvdedn.c new file mode 100644 index 00000000..c8acb995 --- /dev/null +++ b/aeonvdedn.c @@ -0,0 +1,14 @@ +#include +int main() { + int num; + printf("Enter an integer: "); + scanf("%d", &num); + + // true if num is perfectly divisible by 2 + if(num % 2 == 0) + printf("%d is even.", num); + else + printf("%d is odd.", num); + + return 0; +} diff --git a/armstrong.cpp b/armstrong.cpp new file mode 100644 index 00000000..a23e544e --- /dev/null +++ b/armstrong.cpp @@ -0,0 +1,17 @@ +#include +#include +int main(){ + int num,r,sum,temp; + for(num=1;num<=500;num++){ + temp=num; + sum = 0; + while(temp!=0){ + r=temp%10; + temp=temp/10; + sum=sum+(r*r*r); + } + if(sum==num) + cout << num << setw(2); + } + return 0; +} diff --git a/armstrong.java b/armstrong.java new file mode 100644 index 00000000..3302f71a --- /dev/null +++ b/armstrong.java @@ -0,0 +1,31 @@ +class Main { + public static void main(String[] args) { + + int low = 999, high = 99999; + + for(int number = low + 1; number < high; ++number) { + int digits = 0; + int result = 0; + int originalNumber = number; + + // number of digits calculation + while (originalNumber != 0) { + originalNumber /= 10; + ++digits; + } + + originalNumber = number; + + // result contains sum of nth power of its digits + while (originalNumber != 0) { + int remainder = originalNumber % 10; + result += Math.pow(remainder, digits); + originalNumber /= 10; + } + + if (result == number) { + System.out.print(number + " "); + } + } + } +} diff --git a/armstrongCheck.java b/armstrongCheck.java new file mode 100644 index 00000000..f9ef4c0f --- /dev/null +++ b/armstrongCheck.java @@ -0,0 +1,24 @@ +import java.util.Scanner; +public class JavaExample { + + public static void main(String[] args) { + + int num, number, temp, total = 0; + System.out.println("Enter 3 Digit Number"); + Scanner scanner = new Scanner(System.in); + num = scanner.nextInt(); + scanner.close(); + number = num; + + for( ;number!=0;number /= 10) + { + temp = number % 10; + total = total + temp*temp*temp; + } + + if(total == num) + System.out.println(num + " is an Armstrong number"); + else + System.out.println(num + " is not an Armstrong number"); + } +} diff --git a/array.java b/array.java new file mode 100644 index 00000000..cd909e99 --- /dev/null +++ b/array.java @@ -0,0 +1,14 @@ +public class Average { + + public static void main(String[] args) { + double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 }; + double sum = 0.0; + + for (double num: numArray) { + sum += num; + } + + double average = sum / numArray.length; + System.out.format("The average is: %.2f", average); + } +} diff --git a/arrayNumberPrint.java b/arrayNumberPrint.java new file mode 100644 index 00000000..014cd0f9 --- /dev/null +++ b/arrayNumberPrint.java @@ -0,0 +1,8 @@ +public class arrayNumberPrint { + public static void main(String[] args) { + int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + for (int i = 0; i <= arr.length - 1; i++) { + System.out.println(arr[i]); + } + } +} diff --git a/array_12.cpp b/array_12.cpp new file mode 100644 index 00000000..07081b18 --- /dev/null +++ b/array_12.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; +int main() +{ + int A[5] ={ 2,3,4,5,6}; + + int sum=0; + for(int i=0; i<5; i++) + sum=sum + A[i]; + cout<<"sum of all elements are"<< sum; +return 0; +} \ No newline at end of file diff --git a/arraylist1.java b/arraylist1.java new file mode 100644 index 00000000..ae8fd531 --- /dev/null +++ b/arraylist1.java @@ -0,0 +1,39 @@ +import java.util.*; + +class ArrayLists { + public static void main(String args[]) { + ArrayList list = new ArrayList(); + ArrayList list2 = new ArrayList(); + ArrayList list3 = new ArrayList(); + // add elements + list.add(1); + list.add(3); + list.add(4); + list.add(5); + System.out.println(list); + // to get an element + int element = list.get(0); // 0 is the index + System.out.println(element); + // add element in between + list.add(1, 2); // 1 is the index and 2 is the element to be added + System.out.println(list); + // set element + list.set(0, 0); + System.out.println(list); + // delete elements + list.remove(0); // 0 is the index + System.out.println(list); + // size of list + int size = list.size(); + System.out.println(size); + // Loops on lists + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i) + " "); + } + System.out.println(); + // Sorting the list + list.add(0); + Collections.sort(list); + System.out.println(list); + } +} diff --git a/ashishfactorial.cpp b/ashishfactorial.cpp new file mode 100644 index 00000000..6e74c6f6 --- /dev/null +++ b/ashishfactorial.cpp @@ -0,0 +1,13 @@ +#include +using namespace std; +int main() +{ + int i,fact=1,number; + cout<<"Enter any Number: "; + cin>>number; + for(i=1;i<=number;i++){ + fact=fact*i; + } + cout<<"Factorial of " < 0) +{ +//find the remainder (last digit) of the variable num and square and comparing them +if (num % 10 != square % 10) +//returns false if digits are not equal +return false; +//reduce num and square by dividing them by 10 +num = num/10; +square = square/10; +} +return true; +} +//Driver code +public static void main(String args[]) +{ +//number to be check +//calling the method and prints the result accordingly +System.out.println(isAutomorphic(76) ? "Automorphic" : "Not Automorphic"); +System.out.println(isAutomorphic(13) ? "Automorphic" : "Not Automorphic"); +} +} diff --git a/bestTimeToBuyAndSellStock b/bestTimeToBuyAndSellStock new file mode 100644 index 00000000..acbf2bdc --- /dev/null +++ b/bestTimeToBuyAndSellStock @@ -0,0 +1,82 @@ +public class bestTimeToBuyAndSellStock2 { +// driver code + public static void main(String[] args) { + + int[] Arr = {7, 1, 5, 3, 6, 4}; + System.out.println(maxProfit_start(Arr)); + + } + + static int maxProfit_start(int[] prices) { + int n = prices.length; + int[][] dp = new int[n][2]; + for (int[] row : dp) { + Arrays.fill(row, -1); + } + + return maxprofit(0, 0, n, prices,dp); + + + } + //recursion + + static int maxprofit(int ind, int buy, int n, int[] prices) { + if (ind == n) return 0; + + int profit = 0; + // we can by the stock + if (buy == 0) { + profit = Math.max(0 + maxprofit(ind + 1, 0, n, prices), maxprofit(ind + 1, 1, n, prices) - prices[ind]); + } + if (buy == 1) { + // we can sell the stock + profit = Math.max(0 + maxprofit(ind + 1, 1, n, prices), maxprofit(ind + 1, 0, n, prices) + prices[ind]); + } + return profit; + } + + // memorazation + static int maxprofit(int ind, int buy, int n, int[] prices, int[][] dp) { + if (ind == n) return 0; + if (dp[ind][buy] != -1) return dp[ind][buy]; + + int profit = 0; + // we can by the stock + if (buy == 0) { + profit = Math.max(0 + maxprofit(ind + 1, 0, n, prices), maxprofit(ind + 1, 1, n, prices) - prices[ind]); + } + if (buy == 1) { + // we can sell the stock + profit = Math.max(0 + maxprofit(ind + 1, 1, n, prices), maxprofit(ind + 1, 0, n, prices) + prices[ind]); + } + return dp[ind][buy] = profit; + } +} +// Tabulation + + + public int maxProfit(int[] prices){ + int n = prices.length; + int dp[][] = new int[n+1][2]; + for (int row[]:dp){ + Arrays.fill(row,-1); + } + //base condation + dp[n][0] = dp[n][1] = 0; + int profit = 0 ; + for (int ind = n-1; ind >=0 ; ind--) { + for (int buy = 0; buy <=1 ; buy++) { + if (buy == 0){ + // we can buy stock + profit = Math.max(0+dp[ind+1][0],dp[ind+1][1] -prices[ind]); + } + if (buy ==1 ){ + profit = Math.max(0+dp[ind+1][1],dp[ind+1][0] +prices[ind]); + } + dp[ind][buy] = profit; + + } + + } + return dp[0][0]; + } diff --git a/bestpattern.cpp b/bestpattern.cpp new file mode 100644 index 00000000..540f1829 --- /dev/null +++ b/bestpattern.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +int main() +{ int n ; + cin >> n ; + + int row = 1 ; + + while (row<=n) + { + int space = n-row ; + while (space) + { + cout << " "; + space--; + } + int col = 1; + while (col<= row) + { + cout<< col ; + col++; + } + + int start = row -1; + while (start) + { + cout << start ; + start--; + } + + + cout << endl; + row++; + } + + + return 0; +} \ No newline at end of file diff --git a/binary search b/binary search new file mode 100644 index 00000000..3d41232b --- /dev/null +++ b/binary search @@ -0,0 +1,58 @@ +import java.util.Scanner; + +// Binary Search in Java + +class Main { + int binarySearch(int array[], int element, int low, int high) { + + // Repeat until the pointers low and high meet each other + while (low <= high) { + + // get index of mid element + int mid = low + (high - low) / 2; + + // if element to be searched is the mid element + if (array[mid] == element) + return mid; + + // if element is less than mid element + // search only the left side of mid + if (array[mid] < element) + low = mid + 1; + + // if element is greater than mid element + // search only the right side of mid + else + high = mid - 1; + } + + return -1; + } + + public static void main(String args[]) { + + // create an object of Main class + Main obj = new Main(); + + // create a sorted array + int[] array = { 3, 4, 5, 6, 7, 8, 9 }; + int n = array.length; + + // get input from user for element to be searched + Scanner input = new Scanner(System.in); + + System.out.println("Enter element to be searched:"); + + // element to be searched + int element = input.nextInt(); + input.close(); + + // call the binary search method + // pass arguments: array, element, index of first and last element + int result = obj.binarySearch(array, element, 0, n - 1); + if (result == -1) + System.out.println("Not found"); + else + System.out.println("Element found at index " + result); + } +} diff --git a/binary-search.java b/binary-search.java new file mode 100644 index 00000000..2a131959 --- /dev/null +++ b/binary-search.java @@ -0,0 +1,45 @@ +// Java implementation of recursive Binary Search +class BinarySearch { + // Returns index of x if it is present in arr[l.. + // r], else return -1 + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) { + int mid = l + (r - l) / 2; + + // If the element is present at the + // middle itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not present + // in array + return -1; + } + + // Driver method to test above + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, 0, n - 1, x); + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at index " + + result); + } +} +/* This code is contributed by Rajat Mishra */ diff --git a/binarySearch.c b/binarySearch.c new file mode 100644 index 00000000..9ccb1eb5 --- /dev/null +++ b/binarySearch.c @@ -0,0 +1,35 @@ +#include + +int binarySearch(int arr[], int value, int left, int right) +{ + if (left > right) + { + return -1; + } + int mid = (left + right) / 2; + + if (arr[mid] == value) + { + return mid; + } + else if (arr[mid] < value) + { + return binarySearch(arr, value, mid + 1, right); + } + else + { + return binarySearch(arr, value, left, mid - 1); + } +} + +int main() +{ + int array[] = {1, 4, 6, 8, 9, 10, 15, 36, 45, 97}; + int n = 10; + + int idx = binarySearch(array, 36, 0, n - 1); + + printf("%d", idx); + + return 0; +} diff --git a/binary_search.java b/binary_search.java new file mode 100644 index 00000000..d670065d --- /dev/null +++ b/binary_search.java @@ -0,0 +1,25 @@ +class BinarySearchExample{ + public static void binarySearch(int arr[], int first, int last, int key){ + int mid = first + (last-first)/2; + while( first <= last ){ + if ( arr[mid] < key ){ + first = mid + 1; + }else if ( arr[mid] == key ){ + System.out.println("Element is found at index: " + mid); + break; + }else{ + last = mid - 1; + } + mid = (first + last)/2; + } + if ( first > last ){ + System.out.println("Element is not found!"); + } + } + public static void main(String args[]){ + int arr[] = {10,20,30,40,50}; + int key = 30; + int last=arr.length-1; + binarySearch(arr,0,last,key); + } +} diff --git a/binarysearch.java b/binarysearch.java new file mode 100644 index 00000000..af46a656 --- /dev/null +++ b/binarysearch.java @@ -0,0 +1,16 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + + // Using binarySearch() + int pos = Collections.binarySearch(numbers, 3); + System.out.println("The position of 3 is " + pos); + } +} diff --git a/bmiCalculator.html b/bmiCalculator.html new file mode 100644 index 00000000..4a63d745 --- /dev/null +++ b/bmiCalculator.html @@ -0,0 +1,15 @@ + + + + + BMI Cakculator + + +

BMI Calculator

+
+ + + +
+ + diff --git a/bnrsrch.cpp b/bnrsrch.cpp new file mode 100644 index 00000000..eb0d55f9 --- /dev/null +++ b/bnrsrch.cpp @@ -0,0 +1,54 @@ +#include +#include +using namespace std; +int main () +{ + // declaration of the variables and array + int arr[100], st, mid, end, i, num, tgt; + + cout << " Define the size of the array: " << endl; + cin >> num; // get size + + // enter only sorted array + cout << " Enter the values in sorted array either ascending or descending order: " << endl; + // use for loop to iterate values + for (i = 0; i < num; i++) + { + cout << " arr [" << i << "] = "; + cin >> arr[i]; + } + + // initialize the starting and ending variable's values + st = 0; + end = num - 1; // size of array (num) - 1 + + // define the item or value to be search + cout << " Define a value to be searched from sorted array: " << endl; + cin >> tgt; + + // use while loop to check 'st', should be less than equal to 'end'. + while ( st <= end) + { + // get middle value by splitting into half + mid = ( st + end ) / 2; + /* if we get the target value at mid index, print the position and exit from the program. */ + if (arr[mid] == tgt) + { + cout << " Element is found at index " << (mid + 1); + exit (0); // use for exit program the program + } + // check the value of target element is greater than the mid element' value + else if ( tgt > arr[mid]) + { + st = mid + 1; // set the new value for st variable + } + + // check the value of target element is less than the mid element' value + else if ( tgt < arr[mid]) + { + end = mid - 1; // set the new value for end variable + } + } + cout << " Number is not found. " << endl; + return 0; +} diff --git a/bouncynumber.java b/bouncynumber.java new file mode 100644 index 00000000..1d22fefc --- /dev/null +++ b/bouncynumber.java @@ -0,0 +1,62 @@ +import java.util.*; +public class BouncyNumberExample1 +{ +public static void main(String args[]) +{ +Scanner scan = new Scanner(System.in); +System.out.print("Enter any number you want to check: "); +//reading an integer from the user +int inputNumber = scan.nextInt(); +//if any of the following condition returns true, the number id not bouncy +if (isIncreasing(inputNumber) || isDecreasing(inputNumber) || inputNumber < 101) +//prints if the number is not bouncy +System.out.println(inputNumber+" not a bouncy number."); +else +//prints if the number is bouncy +System.out.println(inputNumber+" is a bouncy number."); +} +//function that checks if the number is an increasing number or not +public static boolean isIncreasing(int inputNumber) +{ +//converts the number into string +String str = Integer.toString(inputNumber); +char digit; +//flag set to true +boolean flag = true; +//iterates over the string up to length-1 +for(int i=0;i < str.length()-1;i++) +{ +digit = str.charAt(i); +//if any digit is greater than check next digit, it will not check further +if(digit > str.charAt(i+1)) +{ +//flag set to false if the condition returns true +flag = false; +break; +} +} +return flag; +} +//function that checks if the number is a decreasing number or not +public static boolean isDecreasing(int inputNumber) +{ +//converts the number into string +String str = Integer.toString(inputNumber); +char digit; +//flag set to true +boolean flag = true; +//iterates over the string up to length-1 +for(int i=0;i < str.length()-1;i++) +{ +digit = str.charAt(i); +//if any digit is less than the next digit, it will not check further +if(digit < str.charAt(i+1)) +{ +//flag set to false if the condition returns true +flag = false; +break; +} +} +return flag; +} +} diff --git a/boxmodel.html b/boxmodel.html new file mode 100644 index 00000000..4fdf4fba --- /dev/null +++ b/boxmodel.html @@ -0,0 +1,67 @@ + + + + + + + Box Model + + + +
+

This is my heading

+

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Incidunt harum quis, quibusdam, minima molestiae tempore vel magni, repellendus doloribus debitis rerum tenetur eveniet.

+
+ +
+

This is my heading

+

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Incidunt harum quis, quibusdam, minima molestiae tempore vel magni, repellendus doloribus debitis rerum tenetur eveniet.

+
+ +
+

This is my heading

+

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Incidunt harum quis, quibusdam, minima molestiae tempore vel magni, repellendus doloribus debitis rerum tenetur eveniet.

+
+ + diff --git a/bubble.java b/bubble.java new file mode 100644 index 00000000..4d6b7d6b --- /dev/null +++ b/bubble.java @@ -0,0 +1,58 @@ +// Java program to sort an array +// using bucket sort +import java.util.*; +import java.util.Collections; + +class GFG { + + // Function to sort arr[] of size n + // using bucket sort + static void bucketSort(float arr[], int n) + { + if (n <= 0) + return; + + // 1) Create n empty buckets + @SuppressWarnings("unchecked") + Vector[] buckets = new Vector[n]; + + for (int i = 0; i < n; i++) { + buckets[i] = new Vector(); + } + + // 2) Put array elements in different buckets + for (int i = 0; i < n; i++) { + float idx = arr[i] * n; + buckets[(int)idx].add(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) { + Collections.sort(buckets[i]); + } + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < buckets[i].size(); j++) { + arr[index++] = buckets[i].get(j); + } + } + } + + // Driver code + public static void main(String args[]) + { + float arr[] = { (float)0.897, (float)0.565, + (float)0.656, (float)0.1234, + (float)0.665, (float)0.3434 }; + + int n = arr.length; + bucketSort(arr, n); + + System.out.println("Sorted array is "); + for (float el : arr) { + System.out.print(el + " "); + } + } +} diff --git a/bubbleSort.c b/bubbleSort.c new file mode 100644 index 00000000..a4596f7c --- /dev/null +++ b/bubbleSort.c @@ -0,0 +1,36 @@ +#include +void bubblesort(int arr[], int n) +{ + + for (int i = 0; i < n - 1; i++) + { + int isSwaped = 0; + for (int j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + isSwaped = 1; + } + } + if (isSwaped = 0) + { + break; + } + } +} + +int main() +{ + int arr[] = {90,60,50,20,30}; + int n = sizeof(arr) / sizeof(arr[0]); + bubblesort(arr, n); + for (int i = 0; i < 5; i++) + { + printf("%d ", arr[i]); + } + + return 0; +} \ No newline at end of file diff --git a/bubbleSort.java b/bubbleSort.java new file mode 100644 index 00000000..436662e3 --- /dev/null +++ b/bubbleSort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/bubble_sort.java b/bubble_sort.java new file mode 100644 index 00000000..ff0f3854 --- /dev/null +++ b/bubble_sort.java @@ -0,0 +1,62 @@ +public class BubbleSortExample { + /*worst case of this code is O(n2).*/ + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + + } + /* An optimized version of Bubble Sort + worst case of this code is O(n).*/ + + static void optimizedbubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + if (swapped == false) + break; + } + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);/*sorting array elements using bubble sort */ + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} +//THIS CODE IS UPDATED BY BATRAKESHAV10 diff --git a/bubble_sortnew.java b/bubble_sortnew.java new file mode 100644 index 00000000..436662e3 --- /dev/null +++ b/bubble_sortnew.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/bubblesort.java b/bubblesort.java index 436662e3..ae1ceaaa 100644 --- a/bubblesort.java +++ b/bubblesort.java @@ -1,35 +1,35 @@ -public class BubbleSortExample { - static void bubbleSort(int[] arr) { - int n = arr.length; - int temp = 0; - for(int i=0; i < n; i++){ - for(int j=1; j < (n-i); j++){ - if(arr[j-1] > arr[j]){ - //swap elements - temp = arr[j-1]; - arr[j-1] = arr[j]; - arr[j] = temp; - } - - } - } - - } - public static void main(String[] args) { - int arr[] ={3,60,35,2,45,320,5}; - - System.out.println("Array Before Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - System.out.println(); - - bubbleSort(arr);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for(int i=0; i < arr.length; i++){ - System.out.print(arr[i] + " "); - } - - } -} +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} \ No newline at end of file diff --git a/bubblesort1.java b/bubblesort1.java index 75bdf84d..d50f6b0a 100644 --- a/bubblesort1.java +++ b/bubblesort1.java @@ -1,52 +1,33 @@ -// Optimized java implementation -// of Bubble sort -import java.io.*; - -class GFG -{ - // An optimized version of Bubble Sort - static void bubbleSort(int arr[], int n) - { - int i, j, temp; - boolean swapped; - for (i = 0; i < n - 1; i++) - { - swapped = false; - for (j = 0; j < n - i - 1; j++) - { - if (arr[j] > arr[j + 1]) - { - // swap arr[j] and arr[j+1] - temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; - swapped = true; - } - } - - // IF no two elements were - // swapped by inner loop, then break - if (swapped == false) - break; - } - } - - // Function to print an array - static void printArray(int arr[], int size) - { - int i; - for (i = 0; i < size; i++) - System.out.print(arr[i] + " "); - System.out.println(); - } - - // Driver program - public static void main(String args[]) - { - int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; - int n = arr.length; - bubbleSort(arr, n); - System.out.println("Sorted array: "); - printArray(arr, n); - } -} +// Bubble sort Implementation using Javascript + + +// Creating the bblSort function +function bblSort(arr){ + +for(var i = 0; i < arr.length; i++){ + +// Last i elements are already in place +for(var j = 0; j < ( arr.length - i -1 ); j++){ + + // Checking if the item at present iteration + // is greater than the next iteration + if(arr[j] > arr[j+1]){ + + // If the condition is true then swap them + var temp = arr[j] + arr[j] = arr[j + 1] + arr[j+1] = temp + } +} +} +// Print the sorted array +console.log(arr); +} + + +// This is our unsorted array +var arr = [234, 43, 55, 63, 5, 6, 235, 547]; + + +// Now pass this array to the bblSort() function +bblSort(arr); diff --git a/bubblesort97 b/bubblesort97 new file mode 100644 index 00000000..436662e3 --- /dev/null +++ b/bubblesort97 @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/bubblesorthacktoberfest.java b/bubblesorthacktoberfest.java new file mode 100644 index 00000000..24119cfa --- /dev/null +++ b/bubblesorthacktoberfest.java @@ -0,0 +1,31 @@ +package Sorting; + +public class bubblesort { + + public static void main(String args[]) + { + int a[]={3,4,5,2,1,87,45} + + for(int i=1;i=0 && a[hole]>key) + { + a[hole+1]=a[hole]; + hole=hole-1; + + a[hole+1]=key; + } + } + + for(int i=0;i arr[j + 1]) + { + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } + if (swapped == false) + break; + } + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/buzznumber.java b/buzznumber.java new file mode 100644 index 00000000..e9cdbc23 --- /dev/null +++ b/buzznumber.java @@ -0,0 +1,47 @@ +import Java.util.*; +import java.io.*; +import java.util.Scanner; + +//create BuzzNumberExample class to check whether the given number is Buzz number or not +class BuzzNumberExample { + + // create checkNumber() method that returns true when it founds number Buzz + static boolean checkNumber(int number) + { + // check whether the number ends with 7, is divisible by 7 or not + if(number % 10 == 7 || number % 7 == 0) + return true; //returns true when the number is Buzz + else + return false; //returns flase when the number is not Buzz + } + + // main() method start + public static void main(String args[]) + { + int n1, n2; + + //create scanner class object to get input from user + Scanner sc=new Scanner(System.in); + + //show custom message + System.out.println("Enter first number"); + + //store user entered value into variable n1 + n1 = sc.nextInt(); + + //show custom message + System.out.println("Enter second number"); + + //store user entered value into variable n2 + n2 = sc.nextInt(); + + if (checkNumber(n1)) + System.out.println(n1 + " is a Buzz number"); + else + System.out.println(n1 + " is not a Buzz number"); + if (checkNumber(n2)) + System.out.println(n2 + " is a Buzz number"); + else + System.out.println(n2 + " is not a Buzz number"); + } +} diff --git a/bytearraytohex.java b/bytearraytohex.java new file mode 100644 index 00000000..a47c44ab --- /dev/null +++ b/bytearraytohex.java @@ -0,0 +1,12 @@ +public class ByteHex { + + public static void main(String[] args) { + + byte[] bytes = {10, 2, 15, 11}; + + for (byte b : bytes) { + String st = String.format("%02X", b); + System.out.print(st); + } + } +} diff --git a/c++ structure.cpp b/c++ structure.cpp new file mode 100644 index 00000000..c28a4fc3 --- /dev/null +++ b/c++ structure.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +struct Person +{ + char name[50]; + int age; + float salary; +}; + +int main() +{ + Person p1; + + cout << "Enter Full name: "; + cin.get(p1.name, 50); + cout << "Enter age: "; + cin >> p1.age; + cout << "Enter salary: "; + cin >> p1.salary; + + cout << "\nDisplaying Information." << endl; + cout << "Name: " << p1.name << endl; + cout <<"Age: " << p1.age << endl; + cout << "Salary: " << p1.salary; + + return 0; +} \ No newline at end of file diff --git a/c++,2k00,java b/c++,2k00,java new file mode 100644 index 00000000..390d65a9 --- /dev/null +++ b/c++,2k00,java @@ -0,0 +1,22 @@ +#include +int sum(int n); + +int main() { + int number, result; + + printf("Enter a positive integer: "); + scanf("%d", &number); + + result = sum(number); + + printf("sum = %d", result); + return 0; +} + +int sum(int n) { + if (n != 0) + // sum() function calls itself + return n + sum(n-1); + else + return n; +} diff --git a/c++.cpp b/c++.cpp new file mode 100644 index 00000000..a956a991 --- /dev/null +++ b/c++.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() +{ + int a = 5, b = 10, temp; + + cout << "Before swapping." << endl; + cout << "a = " << a << ", b = " << b << endl; + + temp = a; + a = b; + b = temp; + + cout << "\nAfter swapping." << endl; + cout << "a = " << a << ", b = " << b << endl; + + return 0; +} diff --git a/c++001.cpp b/c++001.cpp new file mode 100644 index 00000000..5cfdd452 --- /dev/null +++ b/c++001.cpp @@ -0,0 +1,29 @@ +// Program to compute absolute value +// Works for both int and float + +#include +using namespace std; + +// function with float type parameter +float absolute(float var){ + if (var < 0.0) + var = -var; + return var; +} + +// function with int type parameter +int absolute(int var) { + if (var < 0) + var = -var; + return var; +} + +int main() { + + // call function with int type parameter + cout << "Absolute value of -5 = " << absolute(-5) << endl; + + // call function with float type parameter + cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl; + return 0; +} diff --git a/c++2004.cpp b/c++2004.cpp new file mode 100644 index 00000000..d585fe4e --- /dev/null +++ b/c++2004.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +int main() { + + int i, n; + bool is_prime = true; + + cout << "Enter a positive integer: "; + cin >> n; + + // 0 and 1 are not prime numbers + if (n == 0 || n == 1) { + is_prime = false; + } + + // loop to check if n is prime + for (i = 2; i <= n/2; ++i) { + if (n % i == 0) { + is_prime = false; + break; + } + } + + if (is_prime) + cout << n << " is a prime number"; + else + cout << n << " is not a prime number"; + + return 0; +} diff --git a/c++3,cpp b/c++3,cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/c++3,cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/c++3.cpp b/c++3.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/c++3.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/c++4.cpp b/c++4.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/c++4.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/c++400.cpp b/c++400.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/c++400.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/c++factorial.cpp b/c++factorial.cpp new file mode 100644 index 00000000..95e8630e --- /dev/null +++ b/c++factorial.cpp @@ -0,0 +1,25 @@ +//factorial of a number + +#include +using namespace std; +int main() +{ +int factorial(int); +int fact,value; +cout<<"Enter any number: "; +cin>>value; +fact=factorial(value); +cout<<"Factorial of a number is: "< +using namespace std; + +int main(){ + int a, b, output; + char input; + cout<<"Enter Value 1 and Value 2 : "; + cin>>a>>b; + cout<<"Enter The Arithmetic Operation You Want (+, -, /, x) : "; + cin>>input; + switch(input){ + case '+': output = a + b; + break; + case '-': output = a - b; + break; + case '/': output = a / b; + break; + case 'x': output = a * b; + break; + default: cout<<"Invalid Operation"; + } + cout< +using namespace std; + +// 10 catalan numbers-- 1 1 2 5 14 42 132 429 1430 4862 + +int catalan(int n){ + + if(n<=1){ + return 1; + } + + int res=0; + for(int i=0;i<=n-1;i++){ + res+= catalan(i) * catalan(n-i-1); + } + return res; +} + +int main(){ + + for(int i=0;i<10;i++){ + cout<arr[arr.length-1]) + { + return -1; + } + + int start=0,end=arr.length-1; + while(start<=end) + { + int mid=(start+end)/2; + if(targetarr[mid]) + { + start=mid+1; + } + else + { + return arr[mid]; + } + } + return arr[start]; // for floor value start will be replaced with end + } + +} + diff --git a/celeb.cpp b/celeb.cpp new file mode 100644 index 00000000..45115afb --- /dev/null +++ b/celeb.cpp @@ -0,0 +1,62 @@ +// C++ program to find celebrity +#include +#include +using namespace std; + +// Max # of persons in the party +#define N 8 + +// Person with 2 is celebrity +bool MATRIX[N][N] = {{0, 0, 1, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 0}, + {0, 0, 1, 0}}; + +bool knows(int a, int b) +{ + return MATRIX[a][b]; +} + +// Returns -1 if celebrity +// is not present. If present, +// returns id (value from 0 to n-1). +int findCelebrity(int n) +{ + //the graph needs not be constructed + //as the edges can be found by + //using knows function + + //degree array; + int indegree[n]={0},outdegree[n]={0}; + + //query for all edges + for(int i=0; i

tshirt image

stickers image

+
+ +# ✡What to do ? +1. Create a new README.md file or add any programming language codes of any projects, creating games, payloads, scripts in the given area. +2. You can also download this README.md file, edit and upload it here. + +# ✨Getting started: +```text +1. Create a github account +2. Register for hacktoberfest 2022 +3. Come here and edit this file +4. Edit any 2 line code then click on **Propose Changes** +5. Then save your edit and go to pull request on the up +6. You'll see **Merge and create pull request option** +7. Click on it and save it +8. The main developer will accept it +9. DONE, now you created one successfull pull request +10. REPEAT ALL STEPS 4 times to complete all the task +``` + +# Contribution rules📚: +```text +- The project must work when opening Contributors.html +- You are allowed to make pull requests that break the rules. We just merge it ;) +- Do NOT add any build steps e.g npm install (we want to keep this a simple static site) +- Do NOT remove other content. +- Styling/code can be pretty, ugly or stupid, big or small as long as it works +- Add your name to the Contributors.html file +- Try to keep pull requests small to minimize merge conflicts +``` + +```text +**Make this README FILE MORE PROFESSIONAL AND ATTRACTIVE** +``` diff --git a/checkstringisnumeric.java b/checkstringisnumeric.java new file mode 100644 index 00000000..c932183a --- /dev/null +++ b/checkstringisnumeric.java @@ -0,0 +1,19 @@ +public class Numeric { + + public static void main(String[] args) { + + String string = "12345.15"; + boolean numeric = true; + + try { + Double num = Double.parseDouble(string); + } catch (NumberFormatException e) { + numeric = false; + } + + if(numeric) + System.out.println(string + " is a number"); + else + System.out.println(string + " is not a number"); + } +} diff --git a/circular.java b/circular.java new file mode 100644 index 00000000..2fbf7a04 --- /dev/null +++ b/circular.java @@ -0,0 +1,92 @@ +public class MinMax { + //Represents the node of list. + public class Node{ + int data; + Node next; + public Node(int data) { + this.data = data; + } + } + + //Declaring head and tail pointer as null. + public Node head = null; + public Node tail = null; + + //This function will add the new node at the end of the list. + public void add(int data){ + //Create new node + Node newNode = new Node(data); + //Checks if the list is empty. + if(head == null) { + //If list is empty, both head and tail would point to new node. + head = newNode; + tail = newNode; + newNode.next = head; + } + else { + //tail will point to new node. + tail.next = newNode; + //New node will become new tail. + tail = newNode; + //Since, it is circular linked list tail will points to head. + tail.next = head; + } + } + + //Finds out the minimum value node in the list + public void minNode() { + Node current = head; + //Initializing min to initial node data + int min = head.data; + if(head == null) { + System.out.println("List is empty"); + } + else { + do{ + //If current node's data is smaller than min + //Then replace value of min with current node's data + if(min > current.data) { + min = current.data; + } + current= current.next; + }while(current != head); + + System.out.println("Minimum value node in the list: "+ min); + } + } + + //Finds out the maximum value node in the list + public void maxNode() { + Node current = head; + //Initializing max to initial node data + int max = head.data; + if(head == null) { + System.out.println("List is empty"); + } + else { + do{ + //If current node's data is greater than max + //Then replace value of max with current node's data + if(max < current.data) { + max = current.data; + } + current= current.next; + }while(current != head); + + System.out.println("Maximum value node in the list: "+ max); + } + } + + public static void main(String[] args) { + MinMax cl = new MinMax(); + //Adds data to the list + cl.add(5); + cl.add(20); + cl.add(10); + cl.add(1); + //Prints the minimum value node in the list + cl.minNode(); + //Prints the maximum value node in the list + cl.maxNode(); + } +} diff --git a/circular_linklist000001.cpp b/circular_linklist000001.cpp new file mode 100644 index 00000000..d26b6b39 --- /dev/null +++ b/circular_linklist000001.cpp @@ -0,0 +1,135 @@ +#include +#include +using namespace std; + +struct node +{ + int data; + struct node *next; +}; + +void trivarsal(struct node *head) +{ + struct node *ptr= head; + do + { + cout<<"Elements are :- "<data<next; + } while (ptr!=head); + +} +// circular link list insert at first +struct node *InsetAtFirst(struct node *head,int data){ + struct node *ptr; + ptr = (struct node *)malloc(sizeof(struct node)); + ptr->data = data; + struct node *p = head->next; + + while(p->next!=head){ + p=p->next; + } + p->next=ptr; + ptr->next=head; + head=ptr; + + return head; + +} +// case 1 --> delete at first +// struct node *Deleteatfirst(struct node *head){ +// struct node *ptr=head; +// head=head->next; +// free(ptr); +// return head; +// } + +// case 2 --> deletion a element at given index +// struct node *DeleteAtIndex(struct node *head,int index){ +// struct node *ptr=head; +// struct node *q = head->next; +// for(int i=0;inext; +// q->next; +// } +// ptr->next = q->next; +// free(q); +// return head; + +// case 3 :- delete at last element +// struct node *DeleteAtLast(struct node *head) +// { +// struct node *p = head; +// struct node *q = head->next; +// while (q->next != NULL) +// { +// p = p->next; +// q = p->next; +// } +// p->next = NULL; +// free(q); +// return head; +// } + +int main() +{ + struct node *head; + struct node *second; + struct node *third; + struct node *fourth; + struct node *fifth; + struct node *six; + struct node *seven; + struct node *eight; + head = (struct node *)malloc(sizeof(struct node)); + second = (struct node *)malloc(sizeof(struct node)); + third = (struct node *)malloc(sizeof(struct node)); + fourth = (struct node *)malloc(sizeof(struct node)); + fifth = (struct node *)malloc(sizeof(struct node)); + six = (struct node *)malloc(sizeof(struct node)); + seven = (struct node *)malloc(sizeof(struct node)); + eight = (struct node *)malloc(sizeof(struct node)); + + + head->data = 1; + head->next = second; + + second->data = 2; + second->next = third; + + third->data = 3; + third->next = fourth; + + fourth->data = 4; + fourth->next = fifth; + + fifth->data = 5; + fifth->next = six; + + six->data = 6; + six->next = seven; + + seven->data = 7; + seven->next = eight; + + eight->data = 8; + eight->next = head; + + + + + cout << "before insert in circular link list :- " << endl; + trivarsal(head); + cout << "After insert in circular link list At first :- " << endl; + head=InsetAtFirst(head,99); + trivarsal(head); + // head = Deleteatfirst(head); + // cout<<"after deletion :- "< +using namespace std; +class person +{ +private: + string name; + int age; + +public: + person(string person_name, int person_age) + { + cout << "Constructor for both name and age is called" << endl; + name = person_name; + age = person_age; + } + person(const person &obj) + { + cout << "Copy constructor is called" << endl; + name = obj.name; + age = obj.age; + } + void display() + { + cout << "Name of current object : " << name << endl; + cout << "Age of current object : " << age << endl; + cout << endl; + } +}; +int main() +{ + person obj1("First person", 25); + obj1.display(); + person obj2(obj1); + obj2.display(); +}; diff --git a/comparetwoobjects.java b/comparetwoobjects.java new file mode 100644 index 00000000..5c0302f5 --- /dev/null +++ b/comparetwoobjects.java @@ -0,0 +1,13 @@ +public class ObjectComparisonExample +{ +public static void main(String[] args) +{ +//creating constructor of the Double class +Double x = new Double(123.45555); +//creating constructor of the Long class +Long y = new Long(9887544); +//invoking the equals() method +System.out.println("Objects are not equal, hence it returns " + x.equals(y)); +System.out.println("Objects are equal, hence it returns " + x.equals(123.45555)); +} +} diff --git a/composition.java b/composition.java new file mode 100644 index 00000000..a00fc85c --- /dev/null +++ b/composition.java @@ -0,0 +1,25 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + int count = Collections.frequency(numbers, 2); + System.out.println("Count of 2: " + count); + + ArrayList newNumbers = new ArrayList<>(); + newNumbers.add(5); + newNumbers.add(6); + System.out.println("ArrayList2: " + newNumbers); + + boolean value = Collections.disjoint(numbers, newNumbers); + System.out.println("Two lists are disjoint: " + value); + } +} diff --git a/concatetwoarray.java b/concatetwoarray.java new file mode 100644 index 00000000..7f926418 --- /dev/null +++ b/concatetwoarray.java @@ -0,0 +1,18 @@ +import java.util.Arrays; + +public class Concat { + + public static void main(String[] args) { + int[] array1 = {1, 2, 3}; + int[] array2 = {4, 5, 6}; + + int aLen = array1.length; + int bLen = array2.length; + int[] result = new int[aLen + bLen]; + + System.arraycopy(array1, 0, result, 0, aLen); + System.arraycopy(array2, 0, result, aLen, bLen); + + System.out.println(Arrays.toString(result)); + } +} diff --git a/constructor_overloading.java b/constructor_overloading.java new file mode 100644 index 00000000..208c591a --- /dev/null +++ b/constructor_overloading.java @@ -0,0 +1,36 @@ +class area{ + int l,b; + area(){ + l=0; + b=0; + } + area(int l,int b){ + this.l=l; + this.b=b; + } + area(int l){ + this.l=l; + this.b=l; + } + area(area a){ + this.l=a.l; + this.b=a.b; + } + + void show(){ + System.out.println("Area of rectangle is "+l*b); + } +} + +public class constructor_overloading { + public static void main(String[] args) { + area a1=new area(); + a1.show(); + area a2=new area(10,20); + a2.show(); + area a3=new area(30); + a3.show(); + area a4=new area(a2); + a4.show(); + } +} \ No newline at end of file diff --git a/conwaygameoflife.java b/conwaygameoflife.java new file mode 100644 index 00000000..b166faaf --- /dev/null +++ b/conwaygameoflife.java @@ -0,0 +1,92 @@ +// A simple Java program to implement Game of Life +public class GameOfLife +{ + public static void main(String[] args) + { + int M = 10, N = 10; + + // Initializing the grid. + int[][] grid = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + }; + + // Displaying the grid + System.out.println("Original Generation"); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + { + if (grid[i][j] == 0) + System.out.print("."); + else + System.out.print("*"); + } + System.out.println(); + } + System.out.println(); + nextGeneration(grid, M, N); + } + + // Function to print next generation + static void nextGeneration(int grid[][], int M, int N) + { + int[][] future = new int[M][N]; + + // Loop through every cell + for (int l = 0; l < M; l++) + { + for (int m = 0; m < N; m++) + { + // finding no Of Neighbours that are alive + int aliveNeighbours = 0; + for (int i = -1; i <= 1; i++) + for (int j = -1; j <= 1; j++) + if ((l+i>=0 && l+i=0 && m+j 3)) + future[l][m] = 0; + + // A new cell is born + else if ((grid[l][m] == 0) && (aliveNeighbours == 3)) + future[l][m] = 1; + + // Remains the same + else + future[l][m] = grid[l][m]; + } + } + + System.out.println("Next Generation"); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + { + if (future[i][j] == 0) + System.out.print("."); + else + System.out.print("*"); + } + System.out.println(); + } + } +} diff --git a/coordinates.cpp b/coordinates.cpp new file mode 100644 index 00000000..ab97fa12 --- /dev/null +++ b/coordinates.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; + +struct point +{ +int x; +int y; +}; + +int main( ) +{ +point A,B,C; +cout<<"Enter coordinates for p1:"; +cin>>A.x>>A.y; +cout<<"Enter coordinates for p2:"; +cin>>B.x>>B.y; + +C.x=A.x+B.x; +C.y=A.y+B.y; + +cout<<"Coordinates of p1+p2 are:"<= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + // Driver method + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} +/*This code is contributed by Rajat Mishra */ diff --git a/cplus.cpp b/cplus.cpp new file mode 100644 index 00000000..09dc8652 --- /dev/null +++ b/cplus.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +void checkPalindrome(const char* p){ + + const char* pnew = p; + + for(p;*p != '\0';p++); + // p--; + while (*pnew++ == *--p); + + if(pnew>p) cout<<"is"; + + else cout<<"isnot"; + + +} +int main() +{ + int x; + cout<<"enter the size of the string "; + cin>>x; + + char* str = new char[x]; + + for(int i = 0; i>str[i] ; + } + + const char* pointer; + + pointer = str; + + checkPalindrome(pointer); + + delete [] str; + + + +} diff --git a/cpp4.cpp b/cpp4.cpp new file mode 100644 index 00000000..7e086884 --- /dev/null +++ b/cpp4.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int fibonnaci(int x) { + if((x==1)||(x==0)) { + return(x); + }else { + return(fibonnaci(x-1)+fibonnaci(x-2)); + } +} +int main() { + int x , i=0; + cout << "Enter the number of terms of series : "; + cin >> x; + cout << "\nFibonnaci Series : "; + while(i < x) { + cout << " " << fibonnaci(i); + i++; + } + return 0; +} diff --git a/cqq.c b/cqq.c new file mode 100644 index 00000000..4d064dcc --- /dev/null +++ b/cqq.c @@ -0,0 +1,32 @@ +#include +#include +#include +void removeChar(char * str, char charToRemmove){ + int i, j; + int len = strlen(str); + for(i=0; i +#include +#include +#include +#include +#include +using namespace std; + + +int main() { + /* Enter your code here. Read input from STDIN. Print output to STDOUT */ + int n,q; + cin>> n >> q; + cin.ignore(); + vector> a(n); + for (int i = 0; i< n; i++){ + string line; + getline(cin, line); + istringstream ss(line); + + int k_size, k_item; + ss>> k_size; + vector k(k_size, 0); + for(int j= 0; j< k_size; j++) { + ss>> k_item; + k[j] =k_item; + } + a[i] = k; + } + + for (int i = 0; i> x >> y; + cout<< a.at(x).at(y) < numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + System.out.println("ArrayList1: " + numbers); + + // Using reverse() + Collections.reverse(numbers); + System.out.println("Reversed ArrayList1: " + numbers); + + // Using swap() + Collections.swap(numbers, 0, 1); + System.out.println("ArrayList1 using swap(): " + numbers); + + ArrayList newNumbers = new ArrayList<>(); + + // Using addAll + newNumbers.addAll(numbers); + System.out.println("ArrayList2 using addAll(): " + newNumbers); + + // Using fill() + Collections.fill(numbers, 0); + System.out.println("ArrayList1 using fill(): " + numbers); + + // Using copy() + Collections.copy(newNumbers, numbers); + System.out.println("ArrayList2 using copy(): " + newNumbers); + } +} diff --git a/diamond.java b/diamond.java new file mode 100644 index 00000000..f4fdc175 --- /dev/null +++ b/diamond.java @@ -0,0 +1,27 @@ +import java.util.*; +public class Main +{ + public static void main(String[] args) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter the length of the diamond"); + int num=sc.nextInt(); + int j,k; + for(j=1;j<=num;j++) + { + for(k=1;k<=num-j;k++) + System.out.print(" "); + for(k=1;k<=j*2-1;k++) + System.out.print("*"); + System.out.println(); + } + for(j=num-1;j>0;j--) + { + for(k=1;k<=num-j;k++) + System.out.print(" "); + for(k=1;k<=j*2-1;k++) + System.out.print("*"); + System.out.println(); + } + } +} \ No newline at end of file diff --git a/dijkstra-algorithm.java b/dijkstra-algorithm.java new file mode 100644 index 00000000..1306c5f1 --- /dev/null +++ b/dijkstra-algorithm.java @@ -0,0 +1,115 @@ +import java.util.*; +class Graph_pq { + int dist[]; + Set visited; + PriorityQueue pqueue; + int V; // Number of vertices + List > adj_list; + //class constructor + public Graph_pq(int V) { + this.V = V; + dist = new int[V]; + visited = new HashSet(); + pqueue = new PriorityQueue(V, new Node()); + } + + // Dijkstra's Algorithm implementation + public void algo_dijkstra(List > adj_list, int src_vertex) + { + this.adj_list = adj_list; + + for (int i = 0; i < V; i++) + dist[i] = Integer.MAX_VALUE; + + // first add source vertex to PriorityQueue + pqueue.add(new Node(src_vertex, 0)); + + // Distance to the source from itself is 0 + dist[src_vertex] = 0; + while (visited.size() != V) { + + // u is removed from PriorityQueue and has min distance + int u = pqueue.remove().node; + + // add node to finalized list (visited) + visited.add(u); + graph_adjacentNodes(u); + } + } + // this methods processes all neighbours of the just visited node + private void graph_adjacentNodes(int u) { + int edgeDistance = -1; + int newDistance = -1; + + // process all neighbouring nodes of u + for (int i = 0; i < adj_list.get(u).size(); i++) { + Node v = adj_list.get(u).get(i); + + // proceed only if current node is not in 'visited' + if (!visited.contains(v.node)) { + edgeDistance = v.cost; + newDistance = dist[u] + edgeDistance; + + // compare distances + if (newDistance < dist[v.node]) + dist[v.node] = newDistance; + + // Add the current vertex to the PriorityQueue + pqueue.add(new Node(v.node, dist[v.node])); + } + } + } +} +class Main{ + public static void main(String arg[]) { + int V = 6; + int source = 0; + // adjacency list representation of graph + List > adj_list = new ArrayList >(); + // Initialize adjacency list for every node in the graph + for (int i = 0; i < V; i++) { + List item = new ArrayList(); + adj_list.add(item); + } + + + // Input graph edges + adj_list.get(0).add(new Node(1, 5)); + adj_list.get(0).add(new Node(2, 3)); + adj_list.get(0).add(new Node(3, 2)); + adj_list.get(0).add(new Node(4, 3)); + adj_list.get(0).add(new Node(5, 3)); + adj_list.get(2).add(new Node(1, 2)); + adj_list.get(2).add(new Node(3, 3)); + // call Dijkstra's algo method + Graph_pq dpq = new Graph_pq(V); + dpq.algo_dijkstra(adj_list, source); + + // Print the shortest path from source node to all the nodes + System.out.println("The shorted path from source node to other nodes:"); + System.out.println("Source\t\t" + "Node#\t\t" + "Distance"); + for (int i = 0; i < dpq.dist.length; i++) + System.out.println(source + " \t\t " + i + " \t\t " + dpq.dist[i]); + } +} + +// Node class +class Node implements Comparator { + public int node; + public int cost; + public Node() { } //empty constructor + + public Node(int node, int cost) { + this.node = node; + this.cost = cost; + } + @Override + public int compare(Node node1, Node node2) + { + if (node1.cost < node2.cost) + return -1; + if (node1.cost > node2.cost) + return 1; + return 0; + } +} diff --git a/disjoint set.java b/disjoint set.java new file mode 100644 index 00000000..d1405b34 --- /dev/null +++ b/disjoint set.java @@ -0,0 +1,118 @@ +// A Java program to implement Disjoint Set Data +// Structure. +import java.io.*; +import java.util.*; + +class DisjointUnionSets { + int[] rank, parent; + int n; + + // Constructor + public DisjointUnionSets(int n) + { + rank = new int[n]; + parent = new int[n]; + this.n = n; + makeSet(); + } + + // Creates n sets with single item in each + void makeSet() + { + for (int i = 0; i < n; i++) { + // Initially, all elements are in + // their own set. + parent[i] = i; + } + } + + // Returns representative of x's set + int find(int x) + { + // Finds the representative of the set + // that x is an element of + if (parent[x] != x) { + // if x is not the parent of itself + // Then x is not the representative of + // his set, + parent[x] = find(parent[x]); + + // so we recursively call Find on its parent + // and move i's node directly under the + // representative of this set + } + + return parent[x]; + } + + // Unites the set that includes x and the set + // that includes x + void union(int x, int y) + { + // Find representatives of two sets + int xRoot = find(x), yRoot = find(y); + + // Elements are in the same set, no need + // to unite anything. + if (xRoot == yRoot) + return; + + // If x's rank is less than y's rank + if (rank[xRoot] < rank[yRoot]) + + // Then move x under y so that depth + // of tree remains less + parent[xRoot] = yRoot; + + // Else if y's rank is less than x's rank + else if (rank[yRoot] < rank[xRoot]) + + // Then move y under x so that depth of + // tree remains less + parent[yRoot] = xRoot; + + else // if ranks are the same + { + // Then move y under x (doesn't matter + // which one goes where) + parent[yRoot] = xRoot; + + // And increment the result tree's + // rank by 1 + rank[xRoot] = rank[xRoot] + 1; + } + } +} + +// Driver code +public class Main { + public static void main(String[] args) + { + // Let there be 5 persons with ids as + // 0, 1, 2, 3 and 4 + int n = 5; + DisjointUnionSets dus = + new DisjointUnionSets(n); + + // 0 is a friend of 2 + dus.union(0, 2); + + // 4 is a friend of 2 + dus.union(4, 2); + + // 3 is a friend of 1 + dus.union(3, 1); + + // Check if 4 is a friend of 0 + if (dus.find(4) == dus.find(0)) + System.out.println("Yes"); + else + System.out.println("No"); + + // Check if 1 is a friend of 0 + if (dus.find(1) == dus.find(0)) + System.out.println("Yes"); + else + System.out.println("No"); + } +} diff --git a/division.c b/division.c new file mode 100644 index 00000000..5cfba9bb --- /dev/null +++ b/division.c @@ -0,0 +1,14 @@ +#include +int main() +{ + int num1,num2,div; + printf("\tEnter Two Numbers\n"); + printf("---------------------------\n"); + printf("Enter First Number : "); + scanf("%d", &num1); + printf("\nEnter Second Number : "); + scanf("%d",&num2); + div=num1/num2; + printf("\nDivision of %d & %d is = %d",num1,num2,div); + return 0; +} diff --git a/doublyLinkedList.cpp b/doublyLinkedList.cpp new file mode 100644 index 00000000..fa1a262c --- /dev/null +++ b/doublyLinkedList.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +struct Node{ +int data; +Node *next; +Node *prev; +}; +void insertAtHead(Node **head_ref ,int mydata) +{ + Node* temp=new Node(); + temp->data=mydata; + temp->next=*head_ref; + temp->prev=NULL; + if(*head_ref!=NULL) + { + (*head_ref)->prev=temp; + } + + (*head_ref)=temp; + +} +void print(Node*head) +{ + Node*temp=head; + while(temp!=NULL) + { + cout<data<<" "; + temp=temp->next; + } +} +int main(){ + Node*head=NULL; + insertAtHead(&head,2); + insertAtHead(&head,5); + insertAtHead(&head,7); + insertAtHead(&head,11); + print(head); + + return 0; +} \ No newline at end of file diff --git a/dsatrial1.cpp:tests b/dsatrial1.cpp:tests new file mode 100644 index 00000000..7a94da30 --- /dev/null +++ b/dsatrial1.cpp:tests @@ -0,0 +1,19 @@ +[ + { + "correct_answers": + [ + "enter number of students\nEnter Name : \nEnter Roll No. : \nEnter SGPA : \nEnter Name : \nEnter Roll No. : \nEnter SGPA : \n 1 for linear search\n 2 for binary search\n 3 to display details of all students\n 4 to exit\nenter your choice = \nEnter SGPA of the student : \nObject is present at 0 index.\nvansh\n5\n8\n 1 for linear search\n 2 for binary search\n 3 to display details of all students\n 4 to exit\nenter your choice =" + ], + "test": "2\nvansh\n5\n8\nvatsal\n6\n8.5\n1\n8\n4\n" + }, + { + "correct_answers": + [ + "enter number of students\nEnter Name : \nEnter Roll No. : \nEnter SGPA : \nEnter Name : \nEnter Roll No. : \nEnter SGPA : \n 1 for linear search\n 2 for binary search\n 3 to display details of all students\n 4 to exit\nenter your choice = \nEnter SGPA of the student : \nObject is present at 0 index.\nVans\n1\n8\nObject is present at 1 index.\nVansh\n2\n8\n 1 for linear search\n 2 for binary search\n 3 to display details of all students\n 4 to exit\nenter your choice = \nEnter SGPA of the student : \nObject is present at 0 index.\nVans\n1\n8\nObject is present at 1 index.\nVansh\n2\n8\n 1 for linear search\n 2 for binary search\n 3 to display details of all students\n 4 to exit\nenter your choice =" + ], + "test": "2\nVans\n1\n8\nVansh\n2\n8\n1\n8\n1\n8\n4\n" + }, + { + "test": "2\n" + } +] diff --git a/duck-number.java b/duck-number.java new file mode 100644 index 00000000..13e61a94 --- /dev/null +++ b/duck-number.java @@ -0,0 +1,106 @@ +//import required classes and packages +import java.util.*; +import java.io.*; +import java.util.Scanner; + +//create DuckNumberExample class to check whether the given number is a Duck number or not +public class DuckNumberExample { + + // create checkNumber() method that returns true when it founds number Buzz + public static boolean checkNumber(int number) { + + // use loop to repeat steps + while(number != 0) { + + // check whether the last digit of the number is zero or not + if(number%10 == 0) + return true; //return true if the number is Duck + + // divide the number by 10 to remove the last digit + number = number / 10; + } + + return false; //return false if the number is not Duck + } + // main() method start + public static void main(String args[]) + { + int n1, n2; + + //create scanner class object to get input from user + Scanner sc=new Scanner(System.in); + + //show custom message + System.out.println("Enter first number"); + + //store user entered value into variable n1 + n1 = sc.nextInt(); + + //show custom message + System.out.println("Enter second number"); + + //store user entered value into variable n2 + n2 = sc.nextInt(); + + if (checkNumber(n1)) + System.out.println(n1 + " is a Duck number"); + else + System.out.println(n1 + " is not a Duck number"); + if (checkNumber(n2)) + System.out.println(n2 + " is a Duck number"); + else + System.out.println(n2 + " is not a Duck number"); + } +} +Output + +Duck Number Java +Let's implement one more program to get all the Duck number in a given range + +FindAllDuckNumber.java + +//import required classes and packages +import java.util.*; +import java.io.*; +import java.util.Scanner; + +//create FindAllDuckNumber class to get all the Duck number in a given range +class FindAllDuckNumber +{ + //main() method start + public static void main(String args[]) + { + int range; + + //create scanner class object + Scanner sc=new Scanner(System.in); + + //show custom message + System.out.println("Enter the value of range"); + + //store user entered value into variable range + range = sc.nextInt(); + + for(int i = 1; i <= range; i++) + if(checkNumber(i)){ + System.out.println(i + " is a Duck number"); + } + } + + // create checkNumber() method that returns true when it founds number Buzz + public static boolean checkNumber(int number) { + + // use loop to repeat steps + while(number != 0) { + + // check whether the last digit of the number is zero or not + if(number%10 == 0) + return true; //return true if the number is Duck + + // divide the number by 10 to remove the last digit + number = number / 10; + } + + return false; //return false if the number is not Duck + } +} diff --git a/duck_number.java b/duck_number.java new file mode 100644 index 00000000..2f935891 --- /dev/null +++ b/duck_number.java @@ -0,0 +1,27 @@ +import java.util.*; +public class Main +{ + public static boolean duck(String num,int len) + { + int i=0; + while (i +using namespace std; + +class Encapsulation +{ + private: + // data hidden from outside world + int x; + + public: + // function to set value of + // variable x + void set(int a) + { + x =a; + } + + // function to return value of + // variable x + int get() + { + return x; + } +}; + +// main function +int main() +{ + Encapsulation obj; + + obj.set(5); + + cout< +#include +#include +int main() +{ + + // make two process which run same + // program after this instruction + fork(); + + printf("Hello world!\n"); + return 0; +} + diff --git a/extremevalue.java b/extremevalue.java new file mode 100644 index 00000000..d7d4d056 --- /dev/null +++ b/extremevalue.java @@ -0,0 +1,20 @@ +import java.util.Collections; +import java.util.ArrayList; + +class Main { + public static void main(String[] args) { + // Creating an ArrayList + ArrayList 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/factorial.java b/factorial.java new file mode 100644 index 00000000..bf0bda20 --- /dev/null +++ b/factorial.java @@ -0,0 +1,14 @@ +class FactorialExample2{ + static int factorial(int n){ + if (n == 0) + return 1; + else + return(n * factorial(n-1)); + } + public static void main(String args[]){ + int i,fact=1; + int number=4;//It is the number to calculate factorial + fact = factorial(number); + System.out.println("Factorial of "+number+" is: "+fact); + } +} \ No newline at end of file diff --git a/factorial3.cpp b/factorial3.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/factorial3.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/factorialnumber.java b/factorialnumber.java new file mode 100644 index 00000000..ae621fea --- /dev/null +++ b/factorialnumber.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/fdsadf.cpp b/fdsadf.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/fdsadf.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/fhghmkolalfg.c b/fhghmkolalfg.c new file mode 100644 index 00000000..9bf5e075 --- /dev/null +++ b/fhghmkolalfg.c @@ -0,0 +1,9 @@ +#include +int main() +{ +float radius; +printf("enter radius:"); +scanf("%f", &radius); +printf("area of circle is: %f", 3.14 * radius * radius); +return 0; +} \ No newline at end of file diff --git a/fibonacci b/fibonacci new file mode 100644 index 00000000..76f5bd91 --- /dev/null +++ b/fibonacci @@ -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;i0){ + n3 = n1 + n2; + n1 = n2; + n2 = n3; + System.out.print(" "+n3); + printFibo(count-1); + } + } + +public static void main(String[] args) { + int count=15; + System.out.print(n1+" "+n2);//printing 0 and 1 + printFibo(count-2);//n-2 because 2 numbers are already printed +} +} diff --git a/fileHandler.java b/fileHandler.java new file mode 100644 index 00000000..362bb9e3 --- /dev/null +++ b/fileHandler.java @@ -0,0 +1,36 @@ +package gomes.fernando.robson; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; + +public class ManipuladorArquivo { + + public static void leitor(String path) throws IOException { + BufferedReader buffRead = new BufferedReader(new FileReader(path)); + String linha = ""; + while (true) { + if (linha != null) { + System.out.println(linha); + + } else + break; + linha = buffRead.readLine(); + } + buffRead.close(); + } + + public static void escritor(String path) throws IOException { + BufferedWriter buffWrite = new BufferedWriter(new FileWriter(path)); + String linha = ""; + Scanner in = new Scanner(System.in); + System.out.println("Escreva algo: "); + linha = in.nextLine(); + buffWrite.append(linha + "\n"); + buffWrite.close(); + } + +} \ No newline at end of file diff --git a/fileextension.java b/fileextension.java new file mode 100644 index 00000000..30b18e48 --- /dev/null +++ b/fileextension.java @@ -0,0 +1,17 @@ +import java.io.File; + +class Main { + + public static void main(String[] args) { + File file = new File("Test.java"); + + // convert the file name into string + String fileName = file.toString(); + + int index = fileName.lastIndexOf('.'); + if(index > 0) { + String extension = fileName.substring(index + 1); + System.out.println("File extension is " + extension); + } + } +} diff --git a/findduplicate.java b/findduplicate.java new file mode 100644 index 00000000..2d727827 --- /dev/null +++ b/findduplicate.java @@ -0,0 +1,25 @@ +public class DuplicateCharacters { + public static void main(String[] args) { + String string1 = "Great responsibility"; + int count; + + //Converts given string into character array + char string[] = string1.toCharArray(); + + System.out.println("Duplicate characters in a given string: "); + //Counts each character present in the string + for(int i = 0; i 1 && string[i] != '0') + System.out.println(string[i]); + } + } +} diff --git a/fizzbuzz.java b/fizzbuzz.java new file mode 100644 index 00000000..1e4c61ff --- /dev/null +++ b/fizzbuzz.java @@ -0,0 +1,22 @@ +import java.util.*; +public class Main +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int n,i; + System.out.println("Enter the range"); + n=sc.nextInt(); + for (i=1;i<=n;i++) + { + if (i%15==0) + System.out.println("FizzBuzz"); + else if (i%5==0) + System.out.println("Buzz"); + else if (i%3==0) + System.out.println("Fizz"); + else + System.out.println(i); + } + } +} \ No newline at end of file diff --git a/floyydwarshal.java b/floyydwarshal.java new file mode 100644 index 00000000..1ebdffba --- /dev/null +++ b/floyydwarshal.java @@ -0,0 +1,101 @@ +// Java program for Floyd Warshall All Pairs Shortest +// Path algorithm. +import java.io.*; +import java.lang.*; +import java.util.*; + +class AllPairShortestPath { + final static int INF = 99999, V = 4; + + void floydWarshall(int graph[][]) + { + int dist[][] = new int[V][V]; + int i, j, k; + + /* Initialize the solution matrix + same as input graph matrix. + Or we can say the initial values + of shortest distances + are based on shortest paths + considering no intermediate + vertex. */ + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + dist[i][j] = graph[i][j]; + + /* Add all vertices one by one + to the set of intermediate + vertices. + ---> Before start of an iteration, + we have shortest + distances between all pairs + of vertices such that + the shortest distances consider + only the vertices in + set {0, 1, 2, .. k-1} as + intermediate vertices. + ----> After the end of an iteration, + vertex no. k is added + to the set of intermediate + vertices and the set + becomes {0, 1, 2, .. k} */ + for (k = 0; k < V; k++) { + // Pick all vertices as source one by one + for (i = 0; i < V; i++) { + // Pick all vertices as destination for the + // above picked source + for (j = 0; j < V; j++) { + // If vertex k is on the shortest path + // from i to j, then update the value of + // dist[i][j] + if (dist[i][k] + dist[k][j] + < dist[i][j]) + dist[i][j] + = dist[i][k] + dist[k][j]; + } + } + } + + // Print the shortest distance matrix + printSolution(dist); + } + + void printSolution(int dist[][]) + { + System.out.println( + "The following matrix shows the shortest " + + "distances between every pair of vertices"); + for (int i = 0; i < V; ++i) { + for (int j = 0; j < V; ++j) { + if (dist[i][j] == INF) + System.out.print("INF "); + else + System.out.print(dist[i][j] + " "); + } + System.out.println(); + } + } + + // Driver's code + public static void main(String[] args) + { + /* Let us create the following weighted graph + 10 + (0)------->(3) + | /|\ + 5 | | + | | 1 + \|/ | + (1)------->(2) + 3 */ + int graph[][] = { { 0, 5, INF, 10 }, + { INF, 0, 3, INF }, + { INF, INF, 0, 1 }, + { INF, INF, INF, 0 } }; + AllPairShortestPath a = new AllPairShortestPath(); + + // Function call + a.floydWarshall(graph); + } +} + diff --git a/fractional_knapsack.c b/fractional_knapsack.c new file mode 100644 index 00000000..c42af5ed --- /dev/null +++ b/fractional_knapsack.c @@ -0,0 +1,107 @@ +#include + +void calculateRatio(float profit_arr[], float weight_arr[], float profit_weight_ratio[]) +{ + + for (int i = 0; i < 3; i++) + { + profit_weight_ratio[i] = (profit_arr[i] / weight_arr[i]); + } +} + +void selectionSort(float profit_arr[], float weight_arr[], float ratio_arr[], int n) +{ + + for (int o = 0; o < n; o++) + { + int max = o; + for (int i = o; i < n; i++) + { + + if (ratio_arr[i] > ratio_arr[max]) + { + max = i; + } + } + + float temp = ratio_arr[o]; + ratio_arr[o] = ratio_arr[max]; + ratio_arr[max] = temp; + + float temp2 = profit_arr[o]; + profit_arr[o] = profit_arr[max]; + profit_arr[max] = temp2; + + float temp3 = weight_arr[o]; + weight_arr[o] = weight_arr[max]; + weight_arr[max] = temp3; + } +} + +void printArray(float arr[], int n) +{ + for (int i = 0; i < n; i++) + { + printf("%.2f ", arr[i]); + } +} + +void fractionalKnapsack(float weight_array[], float profit[], float capacity, int n) +{ + float value = 0; + + for (int i = 0; i < n; i++) + { + + if (weight_array[i] <= capacity) + { + value = value + profit[i]; + capacity = capacity - weight_array[i]; + } + else if (capacity > 0 && weight_array[i] > capacity) + { + value = value + profit[i] * (capacity / weight_array[i]); + capacity = capacity - capacity; + } + } + + printf("\n\nFinal value - %.2f", value); +} + +void addToArray(float array[], int n) +{ + for (int i = 0; i < n; i++) + { + scanf("%2f", &array[i]); + } +} + +int main() +{ + + printf("\nName - Shubhankar Nautiyal\nSap id - 1000014085\n\n"); + + printf("\nEnter no. items avialable: "); + int n; + scanf("%d", &n); + float profit_array[n]; + float weight_array[n]; + float profit_weight_ratio[n]; + float capacity; + + printf("Enter profit elements : "); + addToArray(profit_array, n); + + printf("Enter weight elements : "); + addToArray(weight_array, n); + + printf("Enter Knapsack capacity : "); + scanf("%f", &capacity); + + calculateRatio(profit_array, weight_array, profit_weight_ratio); + selectionSort(profit_array, weight_array, profit_weight_ratio, 3); + + fractionalKnapsack(weight_array, profit_array, capacity, 3); + + return 0; +} diff --git a/functional_trees.java b/functional_trees.java new file mode 100644 index 00000000..7b52fe04 --- /dev/null +++ b/functional_trees.java @@ -0,0 +1,86 @@ +import java.util.Scanner; + +public class TreeUse { + //CALCULATE LARGEST ELEMENT + public static int largest(TreeNode root){ + if (root==null){ + return Integer.MIN_VALUE; + + } + int ans=root.data; + for(int i=0;ians){ + ans=childLargest; + } + } + return ans; + + } + + //CALCULATE NUMBER NODES + public static int numNodes(TreeNode root){ + if(root==null){ + return 0; + } + int count =1; + for(int i=0; i takeInput(){ + int n; + Scanner s=new Scanner(System.in); + System.out.println("Enter new node data "); + n=s.nextInt(); + TreeNoderoot=new TreeNode(n); + System.out.println("Enter no of children " +n); + int childcount=s.nextInt(); + for(int i=0;i child =takeInput(); + root.children.add(child); + } + return root; + + } + + //TO PRINT + public static void print(TreeNode root){ + String s=root.data +":"; + for(int i=0;i root=takeInput(); + System.out.println(numNodes(root)); + System.out.println(largest(root)); + + print(root); + // TreeNode root=new TreeNode(4); + // TreeNode node1=new TreeNode(5); + // TreeNode node2=new TreeNode(6); + // TreeNode node3=new TreeNode(7); + // TreeNode node4=new TreeNode(2); + // root.children.add(node1); + // root.children.add(node2); + // root.children.add(node3); + // node2.children.add(node4); + + // System.out.println(root); + + + } + +} diff --git a/functions.cpp b/functions.cpp new file mode 100644 index 00000000..b216d068 --- /dev/null +++ b/functions.cpp @@ -0,0 +1,26 @@ +// C++ Program to demonstrate working of a function +#include +using namespace std; + +// Following function that takes two parameters 'x' and 'y' +// as input and returns max of two input numbers +int max(int x, int y) +{ + if (x > y) + return x; + else + return y; +} + +// main function that doesn't receive any parameter and +// returns integer +int main() +{ + int x = 10, y = 20; + + // Calling above function to find max of 'a' and 'b' + int m = max(x, y); + + cout << "m is " << m; + return 0; +} diff --git a/g7guguy.cpp b/g7guguy.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/g7guguy.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/gcdnumber.java b/gcdnumber.java new file mode 100644 index 00000000..5df7c26b --- /dev/null +++ b/gcdnumber.java @@ -0,0 +1,19 @@ +class Main { + public static void main(String[] args) { + + // find GCD between n1 and n2 + int n1 = 81, n2 = 153; + + // initially set to gcd + int gcd = 1; + + for (int i = 1; i <= n1 && i <= n2; ++i) { + + // check if i perfectly divides both n1 and n2 + if (n1 % i == 0 && n2 % i == 0) + gcd = i; + } + + System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd); + } +} diff --git a/geekandnumberstrings.java b/geekandnumberstrings.java new file mode 100644 index 00000000..d455ca3f --- /dev/null +++ b/geekandnumberstrings.java @@ -0,0 +1,20 @@ +class Solution { + public int minLength(String s, int n) { + // code here + Stackst=new Stack<>(); + int pair[]=new int[]{9,2,1,4,3,6,5,8,7,0}; + for(char ch:s.toCharArray()){ + int key=ch-'0'; + if(st.size()==0){ + st.push(key); + }else{ + if(st.peek()==pair[key]){ + st.pop(); + }else{ + st.push(key); + } + } + } + return st.size(); + } +} diff --git a/giftallocation.c b/giftallocation.c new file mode 100644 index 00000000..78a348a1 --- /dev/null +++ b/giftallocation.c @@ -0,0 +1,27 @@ +#include +int main() +//gift allocation +{ + int maths,science; + printf(" maths and science" ); + scanf("%d %d",&maths,&science); + printf("marks obtained in maths=%d and marks obtained in science=%d\n",maths,science ); + if(maths==30 && science==30) + { + printf("you get a gift of $45"); + } + else if(maths==30 && science<30) + { + printf("you get a gift of $15"); + + } + else if(maths<30 && science==30) + { + printf("you get a gift of $15"); + } + else + { + printf("not eligible for gift"); + } + return 0; +} diff --git a/good.cpp b/good.cpp new file mode 100644 index 00000000..1186c403 --- /dev/null +++ b/good.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; +class Employee { + public: + int id; //data member (also instance variable) + string name; //data member(also instance variable) + float salary; + Employee(int id, string name, float salary) + { + this->id = id; + this->name = name; + this->salary = salary; + } + void display() + { + cout< +using namespace std; + +// function to swap the the position of two elements +void swap(int *a, int *b) { + int temp = *a; + *a = *b; + *b = temp; +} + +// function to print an array +void printArray(int array[], int size) { + for (int i = 0; i < size; i++) { + cout << array[i] << " "; + } + cout << endl; +} + +void selectionSort(int array[], int size) { + for (int step = 0; step < size - 1; step++) { + int min_idx = step; + for (int i = step + 1; i < size; i++) { + + // To sort in descending order, change > to < in this line. + // Select the minimum element in each loop. + if (array[i] < array[min_idx]) + min_idx = i; + } + + // put min at the correct position + swap(&array[min_idx], &array[step]); + } +} + +// driver code +int main() { + int data[] = {20, 12, 10, 15, 2}; + int size = sizeof(data) / sizeof(data[0]); + selectionSort(data, size); + cout << "Sorted array in Acsending Order:\n"; + printArray(data, size); +} diff --git a/hacktoberfest-2022 b/hacktoberfest-2022 new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/hacktoberfest-2022 @@ -0,0 +1 @@ + diff --git a/hactoberfest 1.html b/hactoberfest 1.html new file mode 100644 index 00000000..a26e691e --- /dev/null +++ b/hactoberfest 1.html @@ -0,0 +1,31 @@ +• +• +• +• Hacktoberfest 2022 +• +• +• +•
+•

+• Figma +•

+•

+• UI/UX +•

+•

+• Canva +•

+•
+•
+•

+• ReactJs +•

+•

+• Django +•

+•

+• Flask +•

+•
+• + diff --git a/handling_files.cpp b/handling_files.cpp new file mode 100644 index 00000000..e8c0d1f4 --- /dev/null +++ b/handling_files.cpp @@ -0,0 +1,11 @@ +#include +#include +using namespace std; + +int main () { + ofstream file; + file.open ("codebind.txt"); + file << "Please writr this text to a file.\n this text is written using C++\n"; + file.close(); + return 0; +} diff --git a/harsh 1.txt b/harsh 1.txt new file mode 100644 index 00000000..4b778a5d --- /dev/null +++ b/harsh 1.txt @@ -0,0 +1,50 @@ +#include +using namespace std; + +int main(){ + + int n; + + cin>>n; + + int b[n]; + + int max=b[0]; + + for(int i=0;i>b[i]; + } + + for(int i=1;imax){ + max=b[i]; + } + } + cout< +using namespace std; + +int main(){ + + int n; + + cin>>n; + + int b[n]; + + int max=b[0]; + + for(int i=0;i>b[i]; + } + + for(int i=1;imax){ + max=b[i]; + } + } + cout<= 0; i--) + heapify(arr, N, i); + + // One by one extract an element from heap + for (int i = N - 1; i > 0; i--) { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int N, int i) + { + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < N && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < N && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, N, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int N = arr.length; + + for (int i = 0; i < N; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver's code + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int N = arr.length; + + // Function call + HeapSort ob = new HeapSort(); + ob.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } +} diff --git a/heap_sort.java b/heap_sort.java new file mode 100644 index 00000000..b301fe1e --- /dev/null +++ b/heap_sort.java @@ -0,0 +1,84 @@ +import java.util.*; + +public class heap_sort { + public static void main(String[] args) { + + // int a[]={78,22,54,25,65}; + // int n=a.length; + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int a[]=new int[n]; + for(int i=0;i a[largest]) + + { + largest=l; + } + + if(r < n && a[r] > a[largest]) + + { + largest=r; + } + if(largest!=i) + { + int temp=a[i]; + a[i]=a[largest]; + a[largest]=temp; + + max_heapify(a, n, largest); + + } + + + + + + } + public void sort(int a[]) + { + int n=a.length; + for(int i=n / 2 - 1;i>=0;i--) + { + max_heapify(a, n, i); + } + for(int i=n-1; i>0;i--) + { + int t=a[0]; + a[0]=a[i]; + a[i]=t; + + max_heapify(a, i, 0); + } + + } + + + +} diff --git a/heapsort.java b/heapsort.java new file mode 100644 index 00000000..8f6f466a --- /dev/null +++ b/heapsort.java @@ -0,0 +1,74 @@ +// Java program for implementation of Heap Sort +public class HeapSort +{ + public void sort(int arr[]) + { + int n = arr.length; + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int n, int i) + { + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i to < in this line. + // Select the minimum element in each loop. + if (array[i] < array[min_idx]) { + min_idx = i; + } + } + + // put min at the correct position + int temp = array[step]; + array[step] = array[min_idx]; + array[min_idx] = temp; + } + } + + // driver code + public static void main(String args[]) { + int[] data = { 20, 12, 10, 15, 2 }; + SelectionSort ss = new SelectionSort(); + ss.selectionSort(data); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} diff --git a/hpvedant.cpp b/hpvedant.cpp new file mode 100644 index 00000000..4d94f3c2 --- /dev/null +++ b/hpvedant.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +int main() +{ + int n,r,sum=0,temp; + cout<<"Enter the Number="; + cin>>n; + temp=n; + while(n>0) +{ + r=n%10; + sum=(sum*10)+r; + n=n/10; +} +if(temp==sum) +cout<<"Number is Palindrome."; +else +cout<<"Number is not Palindrome."; + return 0; +} diff --git a/human_resourses.cpp b/human_resourses.cpp new file mode 100644 index 00000000..89f57410 --- /dev/null +++ b/human_resourses.cpp @@ -0,0 +1,603 @@ +#include +#include +#include +#include + +using namespace std; + + + +class Person +{ +private : + + string FirstName; // student name, max 49 characters + string LastName; // student family name + int PersonalID ; + double Salary ; + double WorkingHours ; + double CostPerHour ; + +public : + + void set_FieldName(); + void get_FieldName(); + void gett_FieldName(); + void set_PersonalID(); + void set_Name(); + void LastNamesortList(); + void in_FirstName(); + void in_FamilyName(); + void in_Workinghour(); + void in_Costperhour(); +}; + + +class HRM +{ +private : + + + Person e[100] ; + Person temp[100]; +public : + + void AddPerson(); + void DeletePerson(); + void SearchPerson(); + void UpdatePerson(); + void ReportList(); + +}; + +////global variables declared +int n=0,i=0,x=8248001,y[100]; +bool flag=0; +int z[100]; +string h[100]; +double sal[100]; +int check=0; + + +///////////////////////////////////////////////////////////////////// +// Definition of the AddPerson() method of the Company class +// This method will add an employee to the Company class instance. +// The attributes of the employee should be those of the user's +// own choosing. + +void ::HRM::AddPerson() { + + int x; + char redo; + + do + { + n++; + e[i].set_FieldName(); + i++; + + cout<<"\nThe employee with the following information has been added to the system:"<>redo; + } + while((redo=='y'||redo=='Y')); + +} + + + +///////////////////////////////////////////////////////////////////// +// Definition of the DeletePerson() method of the Company class. +// This method will delete the employee of the user's choosing from +// the Company class instance. + +void HRM::DeletePerson() { + // Show all of the current employees + // Ask the user the ID of which employee that they wish to + // delete. + + int empId; + bool lol; + char redo1,redo2; + lol =false; +lebel: + cout << "ID of employee to remove: "; + + while(!(cin>>empId)) //Reciving vaiables from input : is it no/character ? + { + cout << "Please enter a number! Try again: "; + cin.clear (); + cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, + // whichever comes first. + } + + + + + for ( i = 0; i < n; ++i) { + + + if (y[i]==empId) { + e[i]=e[i+1]; + lol=true; + e[i].set_Name(); + cin>>redo2; + if(redo2=='Y'||redo2=='y'){ + int a; + a=n; + + cout<<"\nThe employee with the following information has been added to the system:"<>redo1; + if(redo1=='Y'||redo1=='y'){ + goto lebel; + cout<>empId)) //Reciving vaiables from input : is it no/character ? + { + cout << "Please enter a number! Try again: "; + cin.clear (); + cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, + // whichever comes first. + } + + + + + int flag1=0; + for (int i = 0; i < n; ++i) { + + if (y[i]!=empId) { + flag1++; + + } + } + /* if (flag1==n){ + + // cout<<" not matching="<< y[i]; +cout<<"Sorry, there is not any employee with requested personal number. Do you want to repeat delete by entering the new personal number (y/n)?:"; + cin>>redo1; + if(redo1=='Y'||redo1=='y'){ + goto lebel; + } + } */ + + cout <> choice; + if (choice == 1) { + cout << " First name: "; + e[i].in_FirstName(); + } + else if (choice == 2) { + cout << " Family name: "; + e[i].in_FamilyName(); + } + else if (choice == 3) { + cout << " Working hours per week: "; + e[i].in_Workinghour(); + } + else if (choice == 4) { + cout << " Payment for one hour: "; + e[i].in_Costperhour(); + } + cout<<"Do you want to update another field (Y/N)="; + cin>>redo; + } while (redo=='y'||redo=='Y'); + } + } + int a; + a=n; + cout<<"\nThe employee with the following information has been added to the system:"<>op; + while(!(cin>>op)) //Reciving vaiables from input : is it no/character ? + { + cout << "Please enter a number! Try again: "; + cin.clear (); + cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, + // whichever comes first. + } + + + switch(op) + { + case '1': + cout<<"\nSorting based on Family Name\n"<h[i+1]) + { + temp[i]=e[i]; + e[i]=e[j]; + e[j]=temp[i]; + } + } + } + + + for(int i=0;isal[h+1]); + { + temp[h]=e[h]; + e[h]=e[q]; + e[q]=temp[h]; + } + } + } + for(int j=0;jmin && z[i]>familyname; + cout<<"\nThe employee with the following information has been added to the system:"<>redo1; + }while(redo1=='y'||redo1=='Y'); + + +} + + +void ::Person::LastNamesortList() { + int temp2; + char temp,temp1; +} + +void::Person ::set_Name(){ + cout<<"Do you really want to delete employee"<>c)) //Reciving vaiables from input : is it no/character ? + { + cout << "Please enter a number! Try again: "; + cin.clear (); + cin.ignore (1000, '\n'); // Skip to next newline or 1000 chars, + // whichever comes first. + } + switch(c) + { + case 1: + cout<<"\nEnter the information of the new employee"<>ch; + } + while(ch=='y'||ch=='Y'); + + + system("pause"); + return 0; +} diff --git a/index (2).cpp b/index (2).cpp new file mode 100644 index 00000000..ffc768b4 --- /dev/null +++ b/index (2).cpp @@ -0,0 +1,75 @@ +//...AKASH KESHRI...// +#include +using namespace std; +#define gc getchar_unlocked +#define fo(i,n) for(i=0;in;k + + + + + + FOODIEZ + + + + + + + +
+ + + +
+ + +

Best Food In Town

+

Lahore might be nicknamed the city of love, + but it could easily be called the city of + food. And while it's easy to associate + Paris with fancy, fine dining —
a hub of Michelin-starred eateries — + there's SO much more to this culinary city

+Visit for More.
+ + + +
+

Food We Offer

+

Healthy food keeps children fresh and rejuvenated. + Food, when eaten in proper intervals and in the right amount, can make children fitter. + Healhy food is delicious. + Kids must be told and trained on how to eat healthily

+
+
+

Burger

+ It's All That only juicier. One thinks he's + all that. The other's not all there. + The best burgers offer a combination of tastes + and textures – sweet, + sour, salt – with a bit of crunch. +
+
+

Pizza

+ + "Pizza is not a 'trend' it's a way of life" + Pizza is my favourite food because it tastes + and smells fabulous. The pizza + itself looks so yummy, crispy and so cheesy +
+
+

Pasta

+ + Dying for a bowl of pasta. + Good pasta will have a chewy texture that + has a bounce to it when chewed. These are + qualities that you cannot determine until + the pasta has been cooked. +
+
+
+ + +
+

Our Locations to Visit

+

Gulberg| Johar Town| Badshahi Mosque| MM Alam Road

+ +
+ +
+ +
+

GULBERG

+
+
+
+ +
+

JOHAR TOWN

+
+
+
+ +
+

MM ALAM ROAD

+
+
+
+
+ + + + +

+ +
+
+

Reviews

+

Gulberg| Johar Town| Badshahi Mosque| MM Alam Road

+
+
+ +
+

Staff and speed of service was extremely good. + It is very clean, calm and has a nice ambiance. + Thai pizzas are delicious and of good quality. + You can also choose steak, as I prefered, it's also really good. + I definetely recommend this restaurant in Lahore.

+

Ayesha Farooqi

+ + + + + +
+
+ + +
+ +
+

Delicious food, good service, and great hygiene + mixed with the atmosphere is all that a good + restaurant needs and Napoli almost fulfilled + every single one of them. The food and service + was great and made me want to go there again + but the atmosphere was the only thing that was + a bit off which kind of makes me skeptical about visiting it again.

+

Nayab Ejaz

+ + + + + +
+
+
+
+ + +
+
+
+
+ azna +
+

AZNA IJAZ

+

Raiwind Road Mughalpura, Lahore.

+

090878601 +

+

B-24684@usa.edu.pk

+

+
+
+
+
+

NEWSLETTER

+
+ +
+
+ + +
+
+ +
+
+
+
+
+
+
+

Copyright ©Azna Ijaz 2021 All right reserved | Azna Ijaz

+ + + + + + + \ No newline at end of file diff --git a/infix_to_postfix.cpp b/infix_to_postfix.cpp new file mode 100644 index 00000000..3ae8e59d --- /dev/null +++ b/infix_to_postfix.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; + +int prec(char c){ + if(c=='^'){ + return 3; + } + else if(c=='*' || c=='/'){ + return 2; + } + else if(c=='+' || c=='-'){ + return 1; + } + else{ + return -1; + } +} + +string infixToPostfix(string s){ + + stack st; + string res; + + for(int i=0;i='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ + res+=s[i]; + } + else if(s[i]=='('){ + st.push(s[i]); + } + else if(s[i]==')'){ + while(!st.empty() && st.top()!='('){ + res+=st.top(); + st.pop(); + } + if(!st.empty()){ + st.pop(); + } + } + else{ + while(!st.empty() && prec(st.top())>=prec(s[i])){ + res+=st.top(); + st.pop(); + } + st.push(s[i]); + } + } + while(!st.empty()){ + res+=st.top(); + st.pop(); + } + return res; +} + +int main(){ + + cout< +using namespace std; + +struct Node{ +int data; +Node *next; +Node *prev; +}; +void insertAtHead(Node **head_ref ,int mydata) +{ + Node* temp=new Node(); + temp->data=mydata; + temp->next=*head_ref; + temp->prev=NULL; + if(*head_ref!=NULL) + { + (*head_ref)->prev=temp; + } + + (*head_ref)=temp; + +} +void insertAtMiddle(Node *previous,int mydata) +{ + Node *temp=new Node(); + temp->data=mydata; + temp->next=previous->next; + + temp->prev=previous; + previous->next=temp; + if(temp->next!=NULL) + { + temp->next->prev=temp; + } +} +void print(Node *head) +{ + Node*temp=head; + while( temp!=NULL) + { + cout<data<<" "; + temp=temp->next; + } +} +int main(){ + Node *head=NULL; + insertAtHead(&head,2); + insertAtHead(&head,5); + insertAtHead(&head,8); + insertAtMiddle(head->next,10); + print(head); + return 0; +} \ No newline at end of file diff --git a/insertion.java b/insertion.java new file mode 100644 index 00000000..a3659bb7 --- /dev/null +++ b/insertion.java @@ -0,0 +1,20 @@ +import java.util.*; +public class Main { +public static void main(String[] args) { + //declare an array and print the original contents + int[] numArray = {10,6,15,4,1,45}; + System.out.println("Original Array:" + Arrays.toString(numArray)); + //apply insertion sort algorithm on the array + for(int k=1; k=0 && temp <= numArray[j]) { + numArray[j+1] = numArray[j]; + j = j-1; + } + numArray[j+1] = temp; + } + //print the sorted array + System.out.println("Sorted Array:" + Arrays.toString(numArray)); +} +} \ No newline at end of file diff --git a/insertion_sort.java b/insertion_sort.java new file mode 100644 index 00000000..8e90f824 --- /dev/null +++ b/insertion_sort.java @@ -0,0 +1,41 @@ +class InsertionSort { + /*Function to sort array using insertion sort*/ + void sort(int arr[]) + { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} diff --git a/intervals.cpp b/intervals.cpp new file mode 100644 index 00000000..fa8d9f2c --- /dev/null +++ b/intervals.cpp @@ -0,0 +1,72 @@ +// A C++ program for merging overlapping intervals +#include +using namespace std; + +// An interval has start time and end time +struct Interval { + int start, end; +}; + +// Compares two intervals according to their starting time. +// This is needed for sorting the intervals using library +// function std::sort(). See http://goo.gl/iGspV +bool compareInterval(Interval i1, Interval i2) +{ + return (i1.start < i2.start); +} + +// The main function that takes a set of intervals, merges +// overlapping intervals and prints the result +void mergeIntervals(Interval arr[], int n) +{ + // Test if the given set has at least one interval + if (n <= 0) + return; + + // Create an empty stack of intervals + stack s; + + // sort the intervals in increasing order of start time + sort(arr, arr + n, compareInterval); + + // push the first interval to stack + s.push(arr[0]); + + // Start from the next interval and merge if necessary + for (int i = 1; i < n; i++) { + // get interval from stack top + Interval top = s.top(); + + // if current interval is not overlapping with stack + // top, push it to the stack + if (top.end < arr[i].start) + s.push(arr[i]); + + // Otherwise update the ending time of top if ending + // of current interval is more + else if (top.end < arr[i].end) { + top.end = arr[i].end; + s.pop(); + s.push(top); + } + } + + // Print contents of stack + cout << "\n The Merged Intervals are: "; + while (!s.empty()) { + Interval t = s.top(); + cout << "[" << t.start << "," << t.end << "] "; + s.pop(); + } + return; +} + +// Driver program +int main() +{ + Interval arr[] + = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; + int n = sizeof(arr) / sizeof(arr[0]); + mergeIntervals(arr, n); + return 0; +} diff --git a/irec.cpp b/irec.cpp new file mode 100644 index 00000000..d97f5691 --- /dev/null +++ b/irec.cpp @@ -0,0 +1,69 @@ +#include +using namespace std; +void swapping(int &a, int &b) { //swap the content of a and b + int temp; + temp = a; + a = b; + b = temp; +} +void display(int *array, int size) { + for(int i = 0; i> n; + int arr[n]; //create an array with given number of elements + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + mergeSort(arr, 0, n-1); //(n-1) for last index + cout << "Array after Sorting: "; + display(arr, n); +} diff --git a/isbnnumber.java b/isbnnumber.java new file mode 100644 index 00000000..a704c7b8 --- /dev/null +++ b/isbnnumber.java @@ -0,0 +1,74 @@ +//import required classes and packages +import java.util.*; +import java.io.*; +import java.util.Scanner; + +//create ISBNNumberExample class to check whether the given number is a valid ISBN or not +class ISBNNumberExample { + + static boolean checkISBNNumber(long number) + { + int sum = 0; + int i, t, intNumber, dNumber; + String strNumber; + + strNumber = ""+number; + + if (strNumber.length() != 10) { + return false; + } + + for (i = 0; i < strNumber.length(); i++) { + intNumber = Integer.parseInt(strNumber.substring(i, i+1)); + dNumber = i + 1; + t = dNumber * intNumber; + sum = sum + t; + } + + // check whether the sum is divisible by 11 or not + + if ((sum % 11) == 0) { + return true; + } + + return false; + + } + + // main() method start + public static void main(String args[]) + { +long n1, n2; + + try { + + //create BufferedReader class object to get input from user + InputStreamReader in = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(in); + + //show custom message + System.out.println("Enter first 10 digit ISBN number"); + + //store user entered value into variable n1 + n1 = Long.parseLong(br.readLine()); + + //show custom message + System.out.println("Enter second 10 digit ISBN number"); + + //store user entered value into variable n2 + n2 = Long.parseLong(br.readLine()); + + if (checkISBNNumber(n1)) + System.out.println(n1 + " is a valid ISBN number"); + else + System.out.println(n1 + " is not a valid ISBN number"); + if (checkISBNNumber(n2)) + System.out.println(n2 + " is a a valid ISBN number"); + else + System.out.println(n2 + " is not a valid ISBN number"); + + }catch(java.lang.Exception e) { + System.out.println("Error while reading the data."); + } + } +} diff --git a/iterative heapsort b/iterative heapsort new file mode 100644 index 00000000..45631488 --- /dev/null +++ b/iterative heapsort @@ -0,0 +1,92 @@ +// Java implementation of Iterative Heap Sort +public class HeapSort { + +// function build Max Heap where value +// of each child is always smaller +// than value of their parent +static void buildMaxHeap(int arr[], int n) +{ + for (int i = 1; i < n; i++) + { + // if child is bigger than parent + if (arr[i] > arr[(i - 1) / 2]) + { + int j = i; + + // swap child and parent until + // parent is smaller + while (arr[j] > arr[(j - 1) / 2]) + { + swap(arr, j, (j - 1) / 2); + j = (j - 1) / 2; + } + } + } +} + +static void heapSort(int arr[], int n) +{ + buildMaxHeap(arr, n); + + for (int i = n - 1; i > 0; i--) + { + // swap value of first indexed + // with last indexed + swap(arr, 0, i); + + // maintaining heap property + // after each swapping + int j = 0, index; + + do + { + index = (2 * j + 1); + + // if left child is smaller than + // right child point index variable + // to right child + if (index < (i - 1) && arr[index] < arr[index + 1]) + index++; + + // if parent is smaller than child + // then swapping parent with child + // having higher value + if (index < i && arr[j] < arr[index]) + swap(arr, j, index); + + j = index; + + } while (index < i); + } +} + +public static void swap(int[] a, int i, int j) { + int temp = a[i]; + a[i]=a[j]; + a[j] = temp; +} + +/* A utility function to print array of size n */ +static void printArray(int arr[]) +{ + int n = arr.length; + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + System.out.println(); +} + +// Driver program +public static void main(String args[]) +{ + int arr[] = {10, 20, 15, 17, 9, 21}; + int n = arr.length; + + System.out.print("Given array: "); + printArray(arr); + + heapSort(arr, n); + + System.out.print("Sorted array: "); + printArray(arr); +} +} diff --git a/java b/java new file mode 100644 index 00000000..f0f7b29f --- /dev/null +++ b/java @@ -0,0 +1,25 @@ +class BinarySearchExample{ + public static void binarySearch(int arr[], int first, int last, int key){ + int mid = (first + last)/2; + while( first <= last ){ + if ( arr[mid] < key ){ + first = mid + 1; + }else if ( arr[mid] == key ){ + System.out.println("Element is found at index: " + mid); + break; + }else{ + last = mid - 1; + } + mid = (first + last)/2; + } + if ( first > last ){ + System.out.println("Element is not found!"); + } + } + public static void main(String args[]){ + int arr[] = {10,20,30,40,50}; + int key = 30; + int last=arr.length-1; + binarySearch(arr,0,last,key); + } +} diff --git a/java1.txt b/java1.txt new file mode 100644 index 00000000..78974b8a --- /dev/null +++ b/java1.txt @@ -0,0 +1,58 @@ + + +import java.util.*; +class Shape{ + public int area() { + return 0; + } + public int volume() { + return 0; + } +} + +class Rectangle extends Shape{ + private int w, h; +//implement Rectangle class + public Rectangle(int wid, int hei){ + this.w = wid; + this.h = hei; + } + + public int area(){ + return w * h; + } +} + +class Cube extends Shape{ + private int a; + //implement Cube class + public Cube(int len){ + this.a = len; + } + + public int volume(){ + return a*a*a; + } +} + +class FClass{ + private static void caller(Shape s) { + //check if s is of type Rectangle + if (s instanceof Rectangle){ + System.out.println(s.area()); + } + //check if s is of type Cube + if (s instanceof Cube){ + System.out.println(s.volume()); + } + } + +public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int w = sc.nextInt(); + int h = sc.nextInt(); + int a = sc.nextInt(); + caller(new Rectangle(w, h)); + caller(new Cube(a)); + } +} \ No newline at end of file diff --git a/java197.java b/java197.java new file mode 100644 index 00000000..398535c0 --- /dev/null +++ b/java197.java @@ -0,0 +1,36 @@ +//sliding window maximum problem +ArrayDeque deq = new ArrayDeque(); + int [] A; + + public void clean_deque(int i, int K) { + if (!deq.isEmpty() && deq.getFirst() == i - K) + deq.removeFirst(); + + + while (!deq.isEmpty() && nums[i] > A[deq.getLast()]){ + deq.removeLast(); + } + } + + public int[] SlidingWindowMaximum(int[] A, int K) { + int n = A.length; + if (n * B=K == 0) return new int[0]; + if (K == 1) return A; + + this.A = A; + int max_idx = 0; + for (int i = 0; i < K; i++) { + clean_deque(i, K); + deq.addLast(i); + if (A[i] > A[max_idx]) max_idx = i; + } + int [] output = new int[n - K + 1]; + output[0] = A[max_idx]; + + for (int i = K; i < n; i++) { + clean_deque(i, K); + deq.addLast(i); + output[i - K + 1] = A[deq.getFirst()]; + } + return output; + } diff --git a/javaAlgo.java b/javaAlgo.java new file mode 100644 index 00000000..a6a49c08 --- /dev/null +++ b/javaAlgo.java @@ -0,0 +1,19 @@ +public class PrimeExample{ + public static void main(String args[]){ + int i,m=0,flag=0; + int n=3;//it is the number to be checked + m=n/2; + if(n==0||n==1){ + System.out.println(n+" is not prime number"); + }else{ + for(i=2;i<=m;i++){ + if(n%i==0){ + System.out.println(n+" is not prime number"); + flag=1; + break; + } + } + if(flag==0) { System.out.println(n+" is prime number"); } + }//end of else +} +} diff --git a/javabook.java b/javabook.java new file mode 100644 index 00000000..3edcc774 --- /dev/null +++ b/javabook.java @@ -0,0 +1,26 @@ +// A Java program to demonstrate +// working of recursion + +class GFG { + static void printFun(int test) + { + if (test < 1) + return; + + else { + System.out.printf("%d ", test); + + // Statement 2 + printFun(test - 1); + + System.out.printf("%d ", test); + return; + } + } + + public static void main(String[] args) + { + int test = 3; + printFun(test); + } +} diff --git a/javaiterator.java b/javaiterator.java new file mode 100644 index 00000000..7acd9feb --- /dev/null +++ b/javaiterator.java @@ -0,0 +1,19 @@ +import java.util.ArrayList; +import java.util.Iterator; + +public class Main { + public static void main(String[] args) { + + // Make a collection + ArrayList animes = new ArrayList(); + animes.add("Fullmetal Alchemist: Brotherhood"); + animes.add("Gintama"); + animes.add("Mushoku Tensei"); + + // Get the iterator + Iterator it = animes.iterator(); + + // Print the first item + System.out.println(it.next()); + } +} diff --git a/javaoperators.java b/javaoperators.java new file mode 100644 index 00000000..d697e926 --- /dev/null +++ b/javaoperators.java @@ -0,0 +1,42 @@ +public class Main { + public static void main(String[] args) { + // Adding + int a = 1; + int b = 99; + int c = a + b; + System.out.println(c); + + // Subtracting + int d = 100; + int e = 99; + int f = d - e; + System.out.println(f); + + // Multiplying + int g = 20; + int h = 5; + int i = g * h; + System.out.println(i); + + // Increment and Decrement + int j = 2; + j++; + int k = 4; + k--; + int l = i + k; + System.out.println(l); + + // Dividing + int m = 100; + int n = 10; + int o = m / n; + System.out.println(o); + + // Remainder + int p = 10; + int q = 2; + int r = p % q; + System.out.println(r); + + } +} diff --git a/javaprog b/javaprog new file mode 100644 index 00000000..76f5bd91 --- /dev/null +++ b/javaprog @@ -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;imax) + { + max=c[i]; + } + } + String x[]=new String[max]; + int m[]=new int[max]; + int profit=0; + for(int i=0;i"); + } + + } + System.out.println("\n"); + System.out.print("Profit Earned "+profit); // printing total profit + } +} \ No newline at end of file diff --git a/jointwolists.java b/jointwolists.java new file mode 100644 index 00000000..268478fc --- /dev/null +++ b/jointwolists.java @@ -0,0 +1,24 @@ +import java.util.ArrayList; +import java.util.List; + +public class JoinLists { + + public static void main(String[] args) { + + List list1 = new ArrayList(); + list1.add("a"); + + List list2 = new ArrayList(); + list2.add("b"); + + List joined = new ArrayList(); + + joined.addAll(list1); + joined.addAll(list2); + + System.out.println("list1: " + list1); + System.out.println("list2: " + list2); + System.out.println("joined: " + joined); + + } +} diff --git a/kadanesalgoinjava0099887.java b/kadanesalgoinjava0099887.java new file mode 100644 index 00000000..5b85e760 --- /dev/null +++ b/kadanesalgoinjava0099887.java @@ -0,0 +1,133 @@ +import java.util.*; +public class array{ + + public static void printarray(int arr[]){ + for(int i = 0 ; imax){ + max=currsum; + } + + } + + // System.out.println(); + + + } + System.out.print("max SUM IS :- "+max+" "); + // System.out.print(sum); + } + + + public static void maxsubarraySumprefix(int arr[]){ + int currsum=0; + int max = Integer.MIN_VALUE; + int prefix[] = new int[arr.length]; + prefix[0]=arr[0]; + for(int i= 1; imax){ + max=currsum; + } + + } + } + System.out.print("max SUM IS :- "+max+" "); + // System.out.print(sum); + } + + public static void kadanesalgo(int arr[]){ + int maxsum = Integer.MIN_VALUE; + int currsum = 0; + for(int i = 0 ; i= (M - j)) { + if (path.charAt(j) == txt.charAt(i)) { + j++; + i++; + } + if (j == M) { + System.out.println("Found pattern " + + "at index " + (i - j)); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && path.charAt(j) != txt.charAt(i)) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } + } + + void computeLPSArray(String path, int M, int lps[]) + { + // length of the previous longest prefix suffix + int len = 0; + int i = 1; + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + while (i < M) { + if (path.charAt(i) == path.charAt(len)) { + len++; + lps[i] = len; + i++; + } + else // (path[i] != path[len]) + { + if (len != 0) { + len = lps[len - 1]; + + } + else // if (len == 0) + { + lps[i] = len; + i++; + } + } + } + } +} \ No newline at end of file diff --git a/knapsack.java b/knapsack.java new file mode 100644 index 00000000..c54b2d3f --- /dev/null +++ b/knapsack.java @@ -0,0 +1,29 @@ +class Knapsack { + + + static int max(int a, int b) { return (a > b) ? a : b; } + + static int knapSack(int W, int wt[], int val[], int n) + { + // Base Case + if (n == 0 || W == 0) + return 0; + + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + else + return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), + knapSack(W, wt, val, n - 1)); + } + + + public static void main(String args[]) + { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +} diff --git a/knapsack_problem.java b/knapsack_problem.java new file mode 100644 index 00000000..e0993a67 --- /dev/null +++ b/knapsack_problem.java @@ -0,0 +1,28 @@ + +class Knapsack { + static int max(int a, int b) { return (a > b) ? a : b; } + + static int knapSack(int W, int wt[], int val[], int n) + { + + if (n == 0 || W == 0) + return 0; + + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + else + return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), + knapSack(W, wt, val, n - 1)); + } + + public static void main(String args[]) + { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +} + diff --git a/kroneckerproduct.java b/kroneckerproduct.java new file mode 100644 index 00000000..0aecd1f1 --- /dev/null +++ b/kroneckerproduct.java @@ -0,0 +1,63 @@ +// Java code to find the Kronecker Product of +// two matrices and stores it as matrix C +import java.io.*; +import java.util.*; + +class GFG { + + // rowa and cola are no of rows and columns + // of matrix A + // rowb and colb are no of rows and columns + // of matrix B + static int cola = 2, rowa = 3, colb = 3, rowb = 2; + + // Function to computes the Kronecker Product + // of two matrices + static void Kroneckerproduct(int A[][], int B[][]) + { + + int[][] C= new int[rowa * rowb][cola * colb]; + + // i loops till rowa + for (int i = 0; i < rowa; i++) + { + + // k loops till rowb + for (int k = 0; k < rowb; k++) + { + + // j loops till cola + for (int j = 0; j < cola; j++) + { + + // l loops till colb + for (int l = 0; l < colb; l++) + { + + // Each element of matrix A is + // multiplied by whole Matrix B + // resp and stored as Matrix C + C[i + l + 1][j + k + 1] = A[i][j] * B[k][l]; + System.out.print( C[i + l + 1][j + k + 1]+" "); + } + } + System.out.println(); + } + } + } + + // Driver program + public static void main (String[] args) + { + int A[][] = { { 1, 2 }, + { 3, 4 }, + { 1, 0 } }; + + int B[][] = { { 0, 5, 2 }, + { 6, 7, 3 } }; + + Kroneckerproduct(A, B); + } +} + +// This code is contributed by Gitanjali. diff --git a/kruskal.java b/kruskal.java new file mode 100644 index 00000000..1fcaeb1d --- /dev/null +++ b/kruskal.java @@ -0,0 +1,190 @@ +// Java program for Kruskal's algorithm to +// find Minimum Spanning Tree of a given +// connected, undirected and weighted graph + +import java.io.*; +import java.lang.*; +import java.util.*; + +class Graph { + + // A class to represent a graph edge + class Edge implements Comparable { + int src, dest, weight; + + // Comparator function used for + // sorting edgesbased on their weight + public int compareTo(Edge compareEdge) + { + return this.weight - compareEdge.weight; + } + }; + + // A class to represent a subset for + // union-find + class subset { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i = 0; i < e; ++i) + edge[i] = new Edge(); + } + + // A utility function to find set of an + // element i (uses path compression technique) + int find(subset subsets[], int i) + { + // find root and make root as parent of i + // (path compression) + if (subsets[i].parent != i) + subsets[i].parent + = find(subsets, subsets[i].parent); + + return subsets[i].parent; + } + + // A function that does union of two sets + // of x and y (uses union by rank) + void Union(subset subsets[], int x, int y) + { + int xroot = find(subsets, x); + int yroot = find(subsets, y); + + // Attach smaller rank tree under root + // of high rank tree (Union by Rank) + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as + // root and increment its rank by one + else { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's + // algorithm + void KruskalMST() + { + // This will store the resultant MST + Edge result[] = new Edge[V]; + + // An index variable, used for result[] + int e = 0; + + // An index variable, used for sorted edges + int i = 0; + for (i = 0; i < V; ++i) + result[i] = new Edge(); + + // Step 1: Sort all the edges in non-decreasing + // order of their weight. If we are not allowed to + // change the given graph, we can create a copy of + // array of edges + Arrays.sort(edge); + + // Allocate memory for creating V subsets + subset subsets[] = new subset[V]; + for (i = 0; i < V; ++i) + subsets[i] = new subset(); + + // Create V subsets with single elements + for (int v = 0; v < V; ++v) { + subsets[v].parent = v; + subsets[v].rank = 0; + } + + i = 0; // Index used to pick next edge + + // Number of edges to be taken is equal to V-1 + while (e < V - 1) { + // Step 2: Pick the smallest edge. And increment + // the index for next iteration + Edge next_edge = edge[i++]; + + int x = find(subsets, next_edge.src); + int y = find(subsets, next_edge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + result[e++] = next_edge; + Union(subsets, x, y); + } + // Else discard the next_edge + } + + // print the contents of result[] to display + // the built MST + System.out.println("Following are the edges in " + + "the constructed MST"); + int minimumCost = 0; + for (i = 0; i < e; ++i) { + System.out.println(result[i].src + " -- " + + result[i].dest + + " == " + result[i].weight); + minimumCost += result[i].weight; + } + System.out.println("Minimum Cost Spanning Tree " + + minimumCost); + } + + // Driver's Code + public static void main(String[] args) + { + + /* Let us create following weighted graph + 10 + 0--------1 + | \ | + 6| 5\ |15 + | \ | + 2--------3 + 4 */ + int V = 4; // Number of vertices in graph + int E = 5; // Number of edges in graph + Graph graph = new Graph(V, E); + + // add edge 0-1 + graph.edge[0].src = 0; + graph.edge[0].dest = 1; + graph.edge[0].weight = 10; + + // add edge 0-2 + graph.edge[1].src = 0; + graph.edge[1].dest = 2; + graph.edge[1].weight = 6; + + // add edge 0-3 + graph.edge[2].src = 0; + graph.edge[2].dest = 3; + graph.edge[2].weight = 5; + + // add edge 1-3 + graph.edge[3].src = 1; + graph.edge[3].dest = 3; + graph.edge[3].weight = 15; + + // add edge 2-3 + graph.edge[4].src = 2; + graph.edge[4].dest = 3; + graph.edge[4].weight = 4; + + // Function call + graph.KruskalMST(); + } +} +// This code is contributed by Aakash Hasija diff --git a/kthLargestElement.java b/kthLargestElement.java new file mode 100644 index 00000000..e36c6e08 --- /dev/null +++ b/kthLargestElement.java @@ -0,0 +1,19 @@ +class Solution { + public int findKthLargest(int[] nums, int k) { + + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + + for(int i : nums){ + pq.add(i); + } + + int res = 0; + + while(k-- > 0){ + res = pq.poll(); + } + + + return res; + } +} diff --git a/leap_year.java b/leap_year.java new file mode 100644 index 00000000..17c1925c --- /dev/null +++ b/leap_year.java @@ -0,0 +1,15 @@ +import java.util.*; +public class Main +{ + public static void main(String args[]) + { + int year; + Scanner sc=new Scanner(System.in); + System.out.println("Enter the year"); + year=sc.nextInt(); + if (((year % 4 == 0)&&(year % 100!= 0))||(year%400 == 0)) + System.out.println("Leap Year"); + else + System.out.println("Not a Leap Year"); + } +} diff --git a/leapyear.java b/leapyear.java new file mode 100644 index 00000000..eba831e9 --- /dev/null +++ b/leapyear.java @@ -0,0 +1,52 @@ +// Java program to find a leap year + +// Importing Classes/Files +import java.io.*; + +// Class for leap-year dealing +public class GeeksforGeeks { + + // Method to check leap year + public static void isLeapYear(int year) + { + // flag to take a non-leap year by default + boolean is_leap_year = false; + + // If year is divisible by 4 + if (year % 4 == 0) { + is_leap_year = true; + // To identify whether it + // is a century year or + // not + if (year % 100 == 0) { + // Checking if year is divisible by 400 + // therefore century leap year + if (year % 400 == 0) + is_leap_year = true; + else + is_leap_year = false; + } + } + // We land here when corresponding if fails + // If year is not divisible by 4 + else + // Flag dealing- Non leap-year + is_leap_year = false; + if (!is_leap_year) + System.out.println(year + " : Non Leap-year"); + else + System.out.println(year + " : Leap-year"); + } + + // Main Driver Code + public static void main(String[] args) + { + // Calling our function by + // passing century year not divisible by 400 + isLeapYear(2000); + + // Calling our function by + // passing Non-century year + isLeapYear(2002); + } +} diff --git a/linearsearch.java b/linearsearch.java new file mode 100644 index 00000000..2eb303c8 --- /dev/null +++ b/linearsearch.java @@ -0,0 +1,34 @@ +public class Main +{ + + public static int linearSearch (int[]arr, int key) + { + + for (int i = 0; i < arr.length; i++) + { + + if (arr[i] == key) + { + + return i; + + } + + } + + return -1; + + } + + public static void main (String a[]) + { + + int[] a1 = { 11, 22, 33, 45, 76, 98 }; + + int key = 33; + + System.out.println (key + " is found at index: " + + linearSearch (a1, key)); + + } +} diff --git a/linked list b/linked list new file mode 100644 index 00000000..5dd0f42a --- /dev/null +++ b/linked list @@ -0,0 +1,37 @@ +import java.util.LinkedList; + +public class HelloLinkedList { + + public static void main(String[] args) { + LinkedList list = new LinkedList(); + + list.add("F"); + list.add("B"); + list.add("D"); + list.add("E"); + list.addLast("Z"); + list.addFirst("A"); + list.add(1, "A2"); + + System.out.println("Original contents of list: " + list); + + list.remove("F"); + list.remove(2); + + + System.out.println("Contents of list after deletion: " + list); + + + list.removeFirst(); + list.removeLast(); + + + System.out.println("List after deleting first and last: " + list); + + Object val = list.get(2); + + list.set(2, (String) val + " Changed"); + System.out.println("List after change: " + list); + } + +} diff --git a/linked.cpp b/linked.cpp new file mode 100644 index 00000000..f9a8a1eb --- /dev/null +++ b/linked.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; +struct Node { + int data; + Node* next; +}; +struct Node* newNode(int data) { + Node* node = new Node; + node->data = data; + node->next = NULL; + return node; +} +void insertNewNode(Node** root, int data) { + Node* node = newNode(data); + Node* ptr; + if (*root == NULL) { + *root = node; + } + else { + ptr = *root; + while (ptr->next != NULL) { + ptr = ptr->next; + } + ptr->next = node; + } +} +void printLinkedList(Node* root) { + while (root != NULL) { + cout << root->data << " -> "; + root = root->next; + } + cout << "NULL" << endl; +} +Node* createLinkedList(int arr[], int n) { + Node *root = NULL; + for (int i = 0; i < n; i++) { + insertNewNode(&root, arr[i]); + } + return root; +} +int main() { + int arr[] = { 1, 2, 3, 4, 5 }, n = 5; + Node* root = createLinkedList(arr, n); + printLinkedList(root); + return 0; +} diff --git a/linked_list.c b/linked_list.c new file mode 100644 index 00000000..5ea2b729 --- /dev/null +++ b/linked_list.c @@ -0,0 +1,241 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct node +{ + int data; + struct node *next; +}; + +struct node *head = NULL; + +void display() +{ + struct node *p = (struct node *)malloc(sizeof(struct node *)); + p = head; + while (p != NULL) + { + printf("%d ", p->data); + + p = p->next; + } + printf("\n"); +} + +void insert() +{ + int pos; + printf("Enter the position where you want to insert : "); + scanf("%d", &pos); + + struct node *ptr = (struct node *)malloc(sizeof(struct node)); + + printf("Enter the number : "); + scanf("%d", &ptr->data); + + struct node *p = (struct node *)malloc(sizeof(struct node)); + p = head; + + if (pos == 1) + { + // ptr->data = val; + ptr->next = p; + head = ptr; + } + else + { + + for (int i = 0; i < pos - 2; i++) + { + p = p->next; + } + ptr->next = p->next; + // ptr->data = val; + + p->next = ptr; + } +} + +void delete () +{ + if(head==NULL) + { + printf("List is empty\n"); + } + else + { + int pos; + printf("Enter the position where you want to delete : "); + scanf("%d", &pos); + + struct node *p = (struct node *)malloc(sizeof(struct node)); + struct node *temp = (struct node *)malloc(sizeof(struct node)); + p = head; + + if (pos == 1) + { + temp = head; + head = head->next; + free(temp); + } + else + { + for (int i = 0; i < pos - 2; i++) + { + p = p->next; + } + temp = p->next; + p->next = temp->next; + free(temp); + } + } +} + +void sort() +{ + struct node *p = (struct node *)malloc(sizeof(struct node *)); + struct node *p1 = (struct node *)malloc(sizeof(struct node *)); + p = head; + int temp; + + while (p->next != NULL) + { + p1 = p->next; + + while (p1 != NULL) + { + if (p->data > p1->data) + { + temp = p->data; + p->data = p1->data; + p1->data = temp; + } + p1 = p1->next; + } + p = p->next; + } +} + +void create() +{ + struct node *p = (struct node *)malloc(sizeof(struct node *)); + struct node *ptr = (struct node *)malloc(sizeof(struct node *)); + int num; + p = head; + printf("Enter the number : "); + scanf("%d", &ptr->data); + ptr->next = NULL; + + if (head == NULL) + { + head = ptr; + } + else + { + while (p->next != NULL) + { + p = p->next; + } + + p->next = ptr; + } +} + +void search() +{ + struct node *p = (struct node *)malloc(sizeof(struct node *)); + p = head; + printf("Enter the number you want to search : "); + int num, count = 1; + scanf("%d", &num); + bool flag = false; + + while (p != NULL) + { + if (p->data == num) + { + printf("%d found at position %d\n", num, count); + flag = true; + } + p = p->next; + count++; + } + + if (!flag) + { + printf("%d not found\n", num); + } +} + +void reverse() +{ + struct node *p = (struct node *)malloc(sizeof(struct node *)); + struct node *t1 = (struct node *)malloc(sizeof(struct node *)); + struct node *t2 = (struct node *)malloc(sizeof(struct node *)); + p = head; + t1 = t2 = NULL; + + while(p!=NULL) + { + t2 = p->next; + p->next = t1; + t1 = p; + p = t2; + } + head = t1; +} + +int main() +{ + printf("1. Create\n2. Insert\n3. Delete\n4. Display\n5. Search\n6. Sort\n7. Reverse\n8. Exit\n"); + int c, a = 0; + + while (a == 0) + { + printf("Enter your choice : "); + scanf("%d", &c); + if (c == 8) + { + break; + } + else + { + if (c == 1) + { + create(); + } + else if (c == 2) + { + insert(); + } + else if (c == 3) + { + delete (); + } + else if (c == 4) + { + display(); + } + else if (c == 5) + { + search(); + } + else if(c==6) + { + sort(); + } + else if(c==7) + { + reverse(); + } + } + } diff --git a/linked_list/AppendLastToFirst.java b/linked_list/AppendLastToFirst.java new file mode 100644 index 00000000..ce399f1d --- /dev/null +++ b/linked_list/AppendLastToFirst.java @@ -0,0 +1,37 @@ +package linked_list; + +import java.util.Scanner; + +public class AppendLastToFirst { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Node head = LinkedList.takeInput(); + int n = scanner.nextInt(); + head = appendLastNToFirst(head, n); + LinkedList.printLL(head); + } + + static Node appendLastNToFirst(Node head, int n){ + if (n == 0 || head == null){ + return head; + } + Node fast = head; + Node slow = head; + Node initialHead = head; + + for (int i = 0; i < n; i++){ + fast = fast.next; + } + while (fast.next != null){ + slow = slow.next; + fast = fast.next; + } + + Node temp = slow.next; + slow.next = null; + fast.next = initialHead; + head = temp; + + return head; + } +} diff --git a/linked_list/DeleteNodeRecursively.java b/linked_list/DeleteNodeRecursively.java new file mode 100644 index 00000000..705b8154 --- /dev/null +++ b/linked_list/DeleteNodeRecursively.java @@ -0,0 +1,26 @@ +package linked_list; + +public class DeleteNodeRecursively { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + LinkedList.printLL(head); + System.out.println(); + head = deleteNode(head, 4); + LinkedList.printLL(head); + } + + static Node deleteNode(Node head, int pos){ + if (head == null && pos > 0){ + return head; + } + + if (pos == 0){ + assert head != null; + head = head.next; + } else { + Node newNode = deleteNode(head.next, pos - 1); + head.next = newNode; + } + return head; + } +} diff --git a/linked_list/EliminateConsDuplicates.java b/linked_list/EliminateConsDuplicates.java new file mode 100644 index 00000000..b4ec11f1 --- /dev/null +++ b/linked_list/EliminateConsDuplicates.java @@ -0,0 +1,28 @@ +package linked_list; + +import java.util.Objects; + +public class EliminateConsDuplicates { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + LinkedList.printLL(head); + System.out.println(); + removeDuplicates(head); + LinkedList.printLL(head); + } + static Node removeDuplicates(Node head){ + if (head == null){ + return null; + } + Node currNode = head; + while (currNode.next != null){ + if (currNode.data.equals(currNode.next.data)) { + // remove node + currNode.next = currNode.next.next; + } else { + currNode = currNode.next; + } + } + return head; + } +} diff --git a/linked_list/FindNode.java b/linked_list/FindNode.java new file mode 100644 index 00000000..4054245b --- /dev/null +++ b/linked_list/FindNode.java @@ -0,0 +1,25 @@ +package linked_list; + +import java.util.Scanner; + +public class FindNode { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + System.out.println("Index of given value in the linked list is: " + findNode(head, n)); + } + + static int findNode(Node head, int data){ + Node temp = head; + int pos = 0; + while (temp != null){ + if (temp.data == data){ + return pos; + } + pos++; + temp = temp.next; + } + return -1; + } +} diff --git a/linked_list/InsertNodeRecursively.java b/linked_list/InsertNodeRecursively.java new file mode 100644 index 00000000..e5b8a984 --- /dev/null +++ b/linked_list/InsertNodeRecursively.java @@ -0,0 +1,28 @@ +package linked_list; + +public class InsertNodeRecursively { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + LinkedList.printLL(head); + System.out.println(); + head = insert(head, 20, 8); + LinkedList.printLL(head); + } + + static Node insert(Node head, int data, int pos){ + Node newNode; + if (head == null && pos > 0){ + return head; + } + if (pos == 0){ + newNode = new Node<>(data); + newNode.next = head; + head = newNode; + } else { + assert head != null; + newNode = insert(head.next, data, pos - 1); + head.next = newNode; + } + return head; + } +} diff --git a/linked_list/LinkedList.java b/linked_list/LinkedList.java new file mode 100644 index 00000000..b556dacc --- /dev/null +++ b/linked_list/LinkedList.java @@ -0,0 +1,140 @@ +package linked_list; + +import java.util.Scanner; + +public class LinkedList { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Node head = takeInput(); + printLL(head); + System.out.println(); + /** + // the value of head is incremented + increment(head); + System.out.println(head.data); + */ +// System.out.println(lengthOfLL(head)); + printIthNode(head, 0); + + int pos = scanner.nextInt(); +// int data = scanner.nextInt(); +// head = insertNode(head, data, pos); + head = deleteNode(head, pos); + printLL(head); + } + + static int lengthOfLL(Node head) { + Node temp = head; + int len = 0; + while (temp != null) { + len++; + temp = temp.next; + } + return len; + } + + static void printLL(Node head) { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + } + + static void increment(Node head) { + head.data++; + } + + static void printIthNode(Node head, int i) { + Node temp = head; + int j = 0; + while (temp != null && j < i) { + temp = temp.next; + j++; + } + if (temp != null) { + System.out.println(temp.data); + } else { + System.out.println("Index out of bounds"); + } + } + + static Node takeInput() { + Scanner scanner = new Scanner(System.in); + int data = scanner.nextInt(); + Node head = null; + Node tail = null; + while (data != -1) { + Node currentNode = new Node<>(data); + if (head == null) { + head = currentNode; + tail = head; + } else { + tail.next = currentNode; + tail = tail.next; + } + data = scanner.nextInt(); + } + return head; + } + + static Node insertNode(Node head, int data, int pos) { + int currPos = 0; + Node temp = head; + Node newNode = new Node<>(data); + // case 1: insertion at head/beginning + if (pos == 0) { + newNode.next = head; + head = newNode; + return head; + } + + while (temp != null && currPos < (pos - 1)) { + temp = temp.next; + currPos++; + } + if (temp == null) { + return head; + } + + newNode.next = temp.next; + temp.next = newNode; + return head; + } + + static Node deleteNode(Node head, int pos) { + int currPos = 0; + Node temp = head; + if (pos == 0) { + head = head.next; + return head; + } + while (temp != null && currPos < pos - 1) { + temp = temp.next; + currPos++; + } + if (temp == null) { + return head; + } + temp.next = temp.next.next; + return head; + } + + static Node createLinkedList() { + Node n1 = new Node<>(3); + Node n2 = new Node<>(4); + Node n3 = new Node<>(5); + Node n4 = new Node<>(2); + Node n5 = new Node<>(6); + Node n6 = new Node<>(1); + Node n7 = new Node<>(9); + n1.next = n2; + n2.next = n3; + n3.next = n4; + n4.next = n5; + n5.next = n6; + n6.next = n7; + + return n1; + } +} diff --git a/linked_list/MergeTwoSortedLists.java b/linked_list/MergeTwoSortedLists.java new file mode 100644 index 00000000..0fbbb6d5 --- /dev/null +++ b/linked_list/MergeTwoSortedLists.java @@ -0,0 +1,50 @@ +package linked_list; + +public class MergeTwoSortedLists { + public static void main(String[] args) { + + } + + private Node solve(Node list1, Node list2){ + if(list1.next == null){ + list1.next = list2; + } else { + Node curr1 = list1; + Node next1 = curr1.next; + Node curr2 = list2; + Node next2; + + while (next1 != null && curr2 != null){ + if (curr2.data >= curr1.data && curr2.data <= next1.data){ + curr1.next = curr2; + next2 = curr2.next; + curr2.next = next1; + curr1 = curr2; + curr2 = next2; + } else { + curr1 = next1; + next1 = next1.next; + if (next1 == null){ + curr1.next = curr2; + return list1; + } + } + } + } + return list1; + } + + Node merge(Node list1, Node list2){ + if (list1 == null){ + return list2; + } + if (list2 == null){ + return list1; + } + if (list1.data <= list2.data){ + return solve(list1, list2); + } else { + return solve(list2, list1); + } + } +} diff --git a/linked_list/MidPointLinkedList.java b/linked_list/MidPointLinkedList.java new file mode 100644 index 00000000..8059c422 --- /dev/null +++ b/linked_list/MidPointLinkedList.java @@ -0,0 +1,19 @@ +package linked_list; + +public class MidPointLinkedList { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + System.out.println(midPoint(head).data); + } + + static Node midPoint(Node head){ + // We use Floyd's Tortoise and Hare algorithm to solve this problem (a cycle detection algo) + Node fast = head; + Node slow = head; + while (fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + } + return slow; + } +} diff --git a/linked_list/Node.java b/linked_list/Node.java new file mode 100644 index 00000000..5e6501be --- /dev/null +++ b/linked_list/Node.java @@ -0,0 +1,11 @@ +package linked_list; + +public class Node { + public T data; + public Node next; + + public Node(T data){ + this.data = data; + next = null; + } +} diff --git a/linked_list/PalindromeList.java b/linked_list/PalindromeList.java new file mode 100644 index 00000000..4b85dba9 --- /dev/null +++ b/linked_list/PalindromeList.java @@ -0,0 +1,68 @@ +package linked_list; + +public class PalindromeList { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + LinkedList.printLL(head); + System.out.println(); + System.out.println(Solution.isPalindrome(head)); + } +} + +class Solution{ + // method to reverse the linked list + private static Node reverseList(Node head){ + if (head == null || head.next == null){ + return head; + } + Node currNode = head; + Node prevNode = null; + while (currNode != null){ + Node tempNode = currNode.next; + currNode.next = prevNode; + prevNode = currNode; + currNode = tempNode; + } + return prevNode; + } + + // method to check palindrome + public static Boolean isPalindrome(Node head){ + if (head == null || head.next == null){ + return true; + } + + Node fast = head; + // this pointer will reach the middle of the list + Node slow = head; + + while (fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + } + + // reverse the list + slow = reverseList(slow); + Node tempNode = head; + + while (slow != null){ + if (slow.data == tempNode.data){ + slow = slow.next; + tempNode = tempNode.next; + } else { + return false; + } + } + return true; + } + + /* + A non-optimised solution could be using a stack to store all the elements of the list and then popping the + elements one by one and comparing to the elements of the list. + This would take O(n) space and time complexity + + Whereas here I have coded the optimised solution which uses a space complexity of O(1) and time complexity of + O(n). Here we use the Hare - Tortoise approach to get to the middle of the list and then reverse the list in + order to compare the last elements to the starting elements of the list. + */ +} diff --git a/linked_list/PrintReverseLL.java b/linked_list/PrintReverseLL.java new file mode 100644 index 00000000..d5da81bb --- /dev/null +++ b/linked_list/PrintReverseLL.java @@ -0,0 +1,38 @@ +package linked_list; + +public class PrintReverseLL { + public static void main(String[] args) { + Node head = LinkedList.takeInput(); + LinkedList.printLL(head); + System.out.println(); + head = printReverse(head); + LinkedList.printLL(head); + System.out.println(); + head = printReverseIterative(head); + LinkedList.printLL(head); + } + + // recursive approach has more complexity + static Node printReverse(Node head){ + if (head == null || head.next == null){ + return head; + } + Node newHead = printReverse(head.next); + head.next.next = head; + head.next = null; + return newHead; + } + + // iterative approach + static Node printReverseIterative(Node head){ + Node currNode = head; + Node prevNode = null; + while (currNode != null){ + Node tempNode = currNode.next; + currNode.next = prevNode; + prevNode = currNode; + currNode = tempNode; + } + return prevNode; + } +} diff --git a/linked_list/ReverseLinkList.java b/linked_list/ReverseLinkList.java new file mode 100644 index 00000000..e745143c --- /dev/null +++ b/linked_list/ReverseLinkList.java @@ -0,0 +1,62 @@ +// Java program for reversing the linked list + +class LinkedList { + + static Node head; + + static class Node { + + int data; + Node next; + + Node(int d) + { + data = d; + next = null; + } + } + + /* Function to reverse the linked list */ + Node reverse(Node node) + { + Node prev = null; + Node current = node; + Node next = null; + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + node = prev; + return node; + } + + // prints content of double linked list + void printList(Node node) + { + while (node != null) { + System.out.print(node.data + " "); + node = node.next; + } + } + + // Driver Code + public static void main(String[] args) + { + LinkedList list = new LinkedList(); + list.head = new Node(85); + list.head.next = new Node(15); + list.head.next.next = new Node(4); + list.head.next.next.next = new Node(20); + + System.out.println("Given Linked list"); + list.printList(head); + head = list.reverse(head); + System.out.println(""); + System.out.println("Reversed linked list "); + list.printList(head); + } +} + +// This code has been contributed by Mayank Jaiswal diff --git a/linked_list/Two_Sum.java b/linked_list/Two_Sum.java new file mode 100644 index 00000000..78e6f892 --- /dev/null +++ b/linked_list/Two_Sum.java @@ -0,0 +1,24 @@ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + ListNode temp =dummy; + int carry=0; + while(l1!= null || l2!= null || carry==1){ + int sum=0; + if(l1!=null){ + sum+=l1.val; + l1=l1.next; + } + if(l2!=null){ + sum+=l2.val; + l2=l2.next; + } + sum+=carry; + carry=sum/10; + ListNode node =new ListNode(sum%10); + temp.next=node; + temp=temp.next; + } + return dummy.next; + } +} diff --git a/linked_list/nth_noderemove_from_end.java b/linked_list/nth_noderemove_from_end.java new file mode 100644 index 00000000..dedcb77f --- /dev/null +++ b/linked_list/nth_noderemove_from_end.java @@ -0,0 +1,30 @@ +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + + if(head.next==null) + return null; + + ListNode slow=head; + ListNode fast=head; + + for(int i=1;i<=n;i++) + fast=fast.next; + + // edge case handeled when we have to delete the 1st node i.e n=size of linked list + + if(fast==null) + return head.next; + + while(fast!=null && fast.next!=null) + { + fast=fast.next; + slow=slow.next; + } + + slow.next=slow.next.next; + return head; + + + + } +} diff --git a/linkedlist in java.java b/linkedlist in java.java new file mode 100644 index 00000000..d5b1b57c --- /dev/null +++ b/linkedlist in java.java @@ -0,0 +1,24 @@ +import java.util.*; + +public class rishit { + + public static void main(String args[]) + { + LinkedList ll = new LinkedList(); + + ll.add("A"); + ll.add("B"); + ll.addLast("C"); + ll.addFirst("D"); + ll.add(2, "E"); + + System.out.println(ll); + + ll.remove("B"); + ll.remove(3); + ll.removeFirst(); + ll.removeLast(); + + System.out.println(ll); + } +} diff --git a/linkedlist_Implementatino.java b/linkedlist_Implementatino.java new file mode 100644 index 00000000..87c7f3c4 --- /dev/null +++ b/linkedlist_Implementatino.java @@ -0,0 +1,84 @@ +import java.io.*; + +public class LinkedList { + + Node head; // head of list + + static class Node { + + int data; + Node next; + + // Constructor + Node(int d) + { + data = d; + next = null; + } + } + + // Method to insert a new node + public static LinkedList insert(LinkedList list, int data) + { + // Create a new node with given data + Node new_node = new Node(data); + + + // If the Linked List is empty, + // then make the new node as head + if (list.head == null) { + list.head = new_node; + } + else { + // Else traverse till the last node + // and insert the new_node there + Node last = list.head; + while (last.next != null) { + last = last.next; + } + + // Insert the new_node at last node + last.next = new_node; + } + + // Return the list by head + return list; + } + + // Method to print the LinkedList. + public static void printList(LinkedList list) + { + Node currNode = list.head; + + System.out.print("LinkedList: "); + + // Traverse through the LinkedList + while (currNode != null) { + // Print the data at current node + System.out.print(currNode.data + " "); + + // Go to next node + currNode = currNode.next; + } + } + + // Driver code + public static void main(String[] args) + { + /* Start with the empty list. */ + LinkedList list = new LinkedList(); + + // Insert the values + list = insert(list, 1); + list = insert(list, 2); + list = insert(list, 3); + list = insert(list, 4); + list = insert(list, 5); + list = insert(list, 6); + list = insert(list, 7); + list = insert(list, 8); + + // Print the LinkedList + printList(list); + } +} diff --git a/linkes_45.cpp b/linkes_45.cpp new file mode 100644 index 00000000..1af04a72 --- /dev/null +++ b/linkes_45.cpp @@ -0,0 +1,76 @@ +// Iterative C++ program to reverse a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +struct LinkedList { + Node* head; + LinkedList() { head = NULL; } + + /* Function to reverse the linked list */ + void reverse() + { + // Initialize current, previous and next pointers + Node* current = head; + Node *prev = NULL, *next = NULL; + + while (current != NULL) { + // Store next + next = current->next; + // Reverse current node's pointer + current->next = prev; + // Move pointers one position ahead. + prev = current; + current = next; + } + head = prev; + } + + /* Function to print linked list */ + void print() + { + struct Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + } + + void push(int data) + { + Node* temp = new Node(data); + temp->next = head; + head = temp; + } +}; + +/* Driver code*/ +int main() +{ + /* Start with the empty list */ + LinkedList ll; + ll.push(20); + ll.push(4); + ll.push(15); + ll.push(85); + + cout << "Given linked list\n"; + ll.print(); + + ll.reverse(); + + cout << "\nReversed Linked list \n"; + ll.print(); + return 0; +} + diff --git a/linklist_implementation.java b/linklist_implementation.java new file mode 100644 index 00000000..885617b1 --- /dev/null +++ b/linklist_implementation.java @@ -0,0 +1,289 @@ +/** + * LinkedList class implements a doubly-linked list. + */ +public class MyLinkedList implements Iterable +{ + /** + * Construct an empty LinkedList. + */ + public MyLinkedList( ) + { + doClear( ); + } + + private void clear( ) + { + doClear( ); + } + + /** + * Change the size of this collection to zero. + */ + public void doClear( ) + { + beginMarker = new Node<>( null, null, null ); + endMarker = new Node<>( null, beginMarker, null ); + beginMarker.next = endMarker; + + theSize = 0; + modCount++; + } + + /** + * Returns the number of items in this collection. + * @return the number of items in this collection. + */ + public int size( ) + { + return theSize; + } + + public boolean isEmpty( ) + { + return size( ) == 0; + } + + /** + * Adds an item to this collection, at the end. + * @param x any object. + * @return true. + */ + public boolean add( AnyType x ) + { + add( size( ), x ); + return true; + } + + /** + * Adds an item to this collection, at specified position. + * Items at or after that position are slid one position higher. + * @param x any object. + * @param idx position to add at. + * @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive. + */ + public void add( int idx, AnyType x ) + { + addBefore( getNode( idx, 0, size( ) ), x ); + } + + /** + * Adds an item to this collection, at specified position p. + * Items at or after that position are slid one position higher. + * @param p Node to add before. + * @param x any object. + * @throws IndexOutOfBoundsException if idx is not between 0 and size(), inclusive. + */ + private void addBefore( Node p, AnyType x ) + { + Node newNode = new Node<>( x, p.prev, p ); + newNode.prev.next = newNode; + p.prev = newNode; + theSize++; + modCount++; + } + + + /** + * Returns the item at position idx. + * @param idx the index to search in. + * @throws IndexOutOfBoundsException if index is out of range. + */ + public AnyType get( int idx ) + { + return getNode( idx ).data; + } + + /** + * Changes the item at position idx. + * @param idx the index to change. + * @param newVal the new value. + * @return the old value. + * @throws IndexOutOfBoundsException if index is out of range. + */ + public AnyType set( int idx, AnyType newVal ) + { + Node p = getNode( idx ); + AnyType oldVal = p.data; + + p.data = newVal; + return oldVal; + } + + /** + * Gets the Node at position idx, which must range from 0 to size( ) - 1. + * @param idx index to search at. + * @return internal node corresponding to idx. + * @throws IndexOutOfBoundsException if idx is not between 0 and size( ) - 1, inclusive. + */ + private Node getNode( int idx ) + { + return getNode( idx, 0, size( ) - 1 ); + } + + /** + * Gets the Node at position idx, which must range from lower to upper. + * @param idx index to search at. + * @param lower lowest valid index. + * @param upper highest valid index. + * @return internal node corresponding to idx. + * @throws IndexOutOfBoundsException if idx is not between lower and upper, inclusive. + */ + private Node getNode( int idx, int lower, int upper ) + { + Node p; + + if( idx < lower || idx > upper ) + throw new IndexOutOfBoundsException( "getNode index: " + idx + "; size: " + size( ) ); + + if( idx < size( ) / 2 ) + { + p = beginMarker.next; + for( int i = 0; i < idx; i++ ) + p = p.next; + } + else + { + p = endMarker; + for( int i = size( ); i > idx; i-- ) + p = p.prev; + } + + return p; + } + + /** + * Removes an item from this collection. + * @param idx the index of the object. + * @return the item was removed from the collection. + */ + public AnyType remove( int idx ) + { + return remove( getNode( idx ) ); + } + + /** + * Removes the object contained in Node p. + * @param p the Node containing the object. + * @return the item was removed from the collection. + */ + private AnyType remove( Node p ) + { + p.next.prev = p.prev; + p.prev.next = p.next; + theSize--; + modCount++; + + return p.data; + } + + /** + * Returns a String representation of this collection. + */ + public String toString( ) + { + StringBuilder sb = new StringBuilder( "[ " ); + + for( AnyType x : this ) + sb.append( x + " " ); + sb.append( "]" ); + + return new String( sb ); + } + + /** + * Obtains an Iterator object used to traverse the collection. + * @return an iterator positioned prior to the first element. + */ + public java.util.Iterator iterator( ) + { + return new LinkedListIterator( ); + } + + /** + * This is the implementation of the LinkedListIterator. + * It maintains a notion of a current position and of + * course the implicit reference to the MyLinkedList. + */ + private class LinkedListIterator implements java.util.Iterator + { + private Node current = beginMarker.next; + private int expectedModCount = modCount; + private boolean okToRemove = false; + + public boolean hasNext( ) + { + return current != endMarker; + } + + public AnyType next( ) + { + if( modCount != expectedModCount ) + throw new java.util.ConcurrentModificationException( ); + if( !hasNext( ) ) + throw new java.util.NoSuchElementException( ); + + AnyType nextItem = current.data; + current = current.next; + okToRemove = true; + return nextItem; + } + + public void remove( ) + { + if( modCount != expectedModCount ) + throw new java.util.ConcurrentModificationException( ); + if( !okToRemove ) + throw new IllegalStateException( ); + + MyLinkedList.this.remove( current.prev ); + expectedModCount++; + okToRemove = false; + } + } + + /** + * This is the doubly-linked list node. + */ + private static class Node + { + public Node( AnyType d, Node p, Node n ) + { + data = d; prev = p; next = n; + } + + public AnyType data; + public Node prev; + public Node next; + } + + private int theSize; + private int modCount = 0; + private Node beginMarker; + private Node endMarker; +} + +class TestLinkedList +{ + public static void main( String [ ] args ) + { + MyLinkedList lst = new MyLinkedList<>( ); + + for( int i = 0; i < 10; i++ ) + lst.add( i ); + for( int i = 20; i < 30; i++ ) + lst.add( 0, i ); + + lst.remove( 0 ); + lst.remove( lst.size( ) - 1 ); + + System.out.println( lst ); + + java.util.Iterator itr = lst.iterator( ); + while( itr.hasNext( ) ) + { + itr.next( ); + itr.remove( ); + System.out.println( lst ); + } + } +} \ No newline at end of file diff --git a/magicsquare.java b/magicsquare.java new file mode 100644 index 00000000..17717b04 --- /dev/null +++ b/magicsquare.java @@ -0,0 +1,69 @@ +// Java program to generate odd sized magic squares +import java.io.*; + +class GFG { + // Function to generate odd sized magic squares + static void generateSquare(int n) + { + int[][] magicSquare = new int[n][n]; + + // Initialize position for 1 + int i = n / 2; + int j = n - 1; + + // One by one put all values in magic square + for (int num = 1; num <= n * n;) { + if (i == -1 && j == n) // 3rd condition + { + j = n - 2; + i = 0; + } + else { + // 1st condition helper if next number + // goes to out of square's right side + if (j == n) + j = 0; + + // 1st condition helper if next number is + // goes to out of square's upper side + if (i < 0) + i = n - 1; + } + + // 2nd condition + if (magicSquare[i][j] != 0) { + j -= 2; + i++; + continue; + } + else + // set number + magicSquare[i][j] = num++; + + // 1st condition + j++; + i--; + } + + // print magic square + System.out.println("The Magic Square for " + n + + ":"); + System.out.println("Sum of each row or column " + + n * (n * n + 1) / 2 + ":"); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) + System.out.print(magicSquare[i][j] + " "); + System.out.println(); + } + } + + // driver program + public static void main(String[] args) + { + // Works only when n is odd + int n = 7; + generateSquare(n); + } +} + +// Contributed by Pramod Kumar diff --git a/main54.c b/main54.c new file mode 100644 index 00000000..3c5f47ec --- /dev/null +++ b/main54.c @@ -0,0 +1,15 @@ +#include +void main() +{ //6 11 8 13 10 15 12 + int a=6; + printf("%d ",a); + label: + a=a+5; + printf("%d ",a); + a=a-3; + printf("%d ",a); + if(a<12) + { + goto label; + } +} diff --git a/marksToPercent.java b/marksToPercent.java new file mode 100644 index 00000000..9d5a9a56 --- /dev/null +++ b/marksToPercent.java @@ -0,0 +1,27 @@ +import java.util.Scanner; + +public class marksToPercent { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter marks of hindi"); + float marks1 = sc.nextFloat(); + System.out.println("Enter marks of english"); + float marks2 = sc.nextFloat(); + System.out.println("Enter marks of mathematics"); + float marks3 = sc.nextFloat(); + System.out.println("Enter marks of science"); + float marks4 = sc.nextFloat(); + System.out.println("Enter marks of SST"); + float marks5 = sc.nextFloat(); + + float total = marks1 + marks2 + marks3 + marks4 + marks5; + System.out.println("Total marks = "); + System.out.println(total); + float average = (total / 5.0f); + System.out.println("Average marks = "); + System.out.println(average); + float percentage = (total / 500.0f) * 100; + System.out.print("Percentage = " + percentage); + System.out.println(percentage); + } +} \ No newline at end of file diff --git a/matrix chain multiplication b/matrix chain multiplication new file mode 100644 index 00000000..2a496e87 --- /dev/null +++ b/matrix chain multiplication @@ -0,0 +1,61 @@ +// Dynamic Programming Java implementation of Matrix +// Chain Multiplication. +// See the Cormen book for details of the following +// algorithm +class MatrixChainMultiplication +{ + + // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n + static int MatrixChainOrder(int p[], int n) + { + /* For simplicity of the + program, one extra row and + one extra column are allocated in m[][]. 0th row + and 0th column of m[][] are not used */ + int m[][] = new int[n][n]; + + int i, j, k, L, q; + + /* m[i, j] = Minimum number of scalar + multiplications needed to compute the matrix + A[i]A[i+1]...A[j] = A[i..j] where + dimension of A[i] is p[i-1] x p[i] */ + + // cost is zero when multiplying one matrix. + for (i = 1; i < n; i++) + m[i][i] = 0; + + // L is chain length. + for (L = 2; L < n; L++) + { + for (i = 1; i < n - L + 1; i++) + { + j = i + L - 1; + if (j == n) + continue; + m[i][j] = Integer.MAX_VALUE; + for (k = i; k <= j - 1; k++) + { + // q = cost/scalar multiplications + q = m[i][k] + m[k + 1][j] + + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) + m[i][j] = q; + } + } + } + + return m[1][n - 1]; + } + + // Driver code + public static void main(String args[]) + { + int arr[] = new int[] { 1, 2, 3, 4 }; + int size = arr.length; + + System.out.println( + "Minimum number of multiplications is " + + MatrixChainOrder(arr, size)); + } +} diff --git a/matrixTranspose.java b/matrixTranspose.java new file mode 100644 index 00000000..7c72e6e2 --- /dev/null +++ b/matrixTranspose.java @@ -0,0 +1,33 @@ +package ArrayQuestions.src; + +import java.util.Arrays; + +public class matrixTranspose { + public static void main(String[] args) { + int[][] matrix = { + {1,2,3}, + {4,5,6}, + + }; + + System.out.println(Arrays.toString((transpose(matrix)))); + } + static int[][] transpose(int[][] matrix) { + int[][] temp = matrix; + int[][] res = new int [matrix[0].length][matrix.length]; + + for (int i = 0; i < res.length; i++) { + for(int j = 0; j < matrix.length; j++){ + res[i][j] = matrix[j][i]; + + } + } + + for(int i = 0; i < res.length; i++){ + System.out.println(Arrays.toString(res[i])); + } + return res; + } + + } + diff --git a/merge-sort.java b/merge-sort.java new file mode 100644 index 00000000..f417242f --- /dev/null +++ b/merge-sort.java @@ -0,0 +1,77 @@ +/* Java program for Merge Sort */ +class MergeSort { + + void merge(int arr[], int l, int m, int r) + { + int n1 = m - l + 1; + int n2 = r - m; + int L[] = new int[n1]; + int R[] = new int[n2]; + for (int i = 0; i < n1; ++i) + L[i] = arr[l + i]; + for (int j = 0; j < n2; ++j) + R[j] = arr[m + 1 + j]; + int i = 0, j = 0; + int k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } + else { + arr[k] = R[j]; + j++; + } + k++; + } + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } + } + + + void sort(int arr[], int l, int r) + { + if (l < r) { + + int m = l + (r - l) / 2; + + sort(arr, l, m); + sort(arr, m + 1, r); + + + merge(arr, l, m, r); + } + } + + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6, 7 }; + + System.out.println("Given Array"); + printArray(arr); + + MergeSort ob = new MergeSort(); + ob.sort(arr, 0, arr.length - 1); + + System.out.println("\nSorted array"); + printArray(arr); + } +} + diff --git a/merge.c b/merge.c new file mode 100644 index 00000000..45622c65 --- /dev/null +++ b/merge.c @@ -0,0 +1,101 @@ + + +#include +#include + + + + +void merge(int arr[], int l, int m, int r) +{ + int i, j, k; + int n1 = m - l + 1; + int n2 = r - m; + + + int L[n1], R[n2]; + + + for (i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + + i = 0; + j = 0; + k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } + else { + arr[k] = R[j]; + j++; + } + k++; + } + + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + + +void mergeSort(int arr[], int l, int r) +{ + if (l < r) { + + int m = l + (r - l) / 2; + + + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + + +void printArray(int A[], int size) +{ + int i; + for (i = 0; i < size; i++) + printf("%d ", A[i]); + printf("\n"); +} + + +int main() +{ + printf("enter size"); + int s; + scanf("%d",&s); + + int arr[s]; + for(int jj=0;jj m - 1) + { + nums[i] = nums2[j]; + j = +1; + } else { + nums[i] = nums1[i]; + } + + } + System.out.println(Arrays.toString(nums)); + + int temp; + for(int k=0;k= 0) { + MinHeapify(i); + i--; + } + } + + // A recursive method to heapify a subtree + // with the root at given index This method + // assumes that the subtrees are already heapified + void MinHeapify(int i) + { + int l = left(i); + int r = right(i); + int smallest = i; + + if (l < heap_size + && harr[l].element < harr[i].element) + smallest = l; + + if (r < heap_size + && harr[r].element < harr[smallest].element) + smallest = r; + + if (smallest != i) { + swap(harr, i, smallest); + MinHeapify(smallest); + } + } + + // to get index of left child of node at index i + int left(int i) { return (2 * i + 1); } + + // to get index of right child of node at index i + int right(int i) { return (2 * i + 2); } + + // to get the root + MinHeapNode getMin() + { + if (heap_size <= 0) { + System.out.println("Heap underflow"); + return null; + } + return harr[0]; + } + + // to replace root with new node + // "root" and heapify() new root + void replaceMin(MinHeapNode root) + { + harr[0] = root; + MinHeapify(0); + } + + // A utility function to swap two min heap nodes + void swap(MinHeapNode[] arr, int i, int j) + { + MinHeapNode temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + // A utility function to print array elements + static void printArray(int[] arr) + { + for (int i : arr) + System.out.print(i + " "); + System.out.println(); + } + + // This function takes an array of + // arrays as an argument and All + // arrays are assumed to be sorted. + // It merges them together and + // prints the final sorted output. + static void mergeKSortedArrays(int[][] arr, int K) + { + MinHeapNode[] hArr = new MinHeapNode[K]; + int resultSize = 0; + for (int i = 0; i < arr.length; i++) { + MinHeapNode node + = new MinHeapNode(arr[i][0], i, 1); + hArr[i] = node; + resultSize += arr[i].length; + } + + // Create a min heap with k heap nodes. Every heap + // node has first element of an array + MinHeap mh = new MinHeap(hArr, K); + + int[] result + = new int[resultSize]; // To store output array + + // Now one by one get the minimum element from min + // heap and replace it with next element of its + // array + for (int i = 0; i < resultSize; i++) { + + // Get the minimum element and store it in + // result + MinHeapNode root = mh.getMin(); + result[i] = root.element; + + // Find the next element that will replace + // current root of heap. The next element + // belongs to same array as the current root. + if (root.j < arr[root.i].length) + root.element = arr[root.i][root.j++]; + // If root was the last element of its array + else + root.element = Integer.MAX_VALUE; + + // Replace root with next element of array + mh.replaceMin(root); + } + + printArray(result); + } + + // Driver's code + public static void main(String args[]) + { + int[][] arr = { { 2, 6, 12, 34 }, + { 1, 9, 20, 1000 }, + { 23, 34, 90, 2000 } }; + + System.out.println("Merged array is :"); + + // Function call + mergeKSortedArrays(arr, arr.length); + } +}; + +// This code is contributed by harsh diff --git a/merge_sort.java b/merge_sort.java new file mode 100644 index 00000000..4184fe68 --- /dev/null +++ b/merge_sort.java @@ -0,0 +1,97 @@ +class merge_sort +{ + + void merge(int arr[], int l, int m, int r) + { + + int n1 = m - l + 1; + int n2 = r - m; + + int L[] = new int [n1]; + int R[] = new int [n2]; + + for (int i=0; i=0;i--) +{ +//stores the reverse of the string +string=string+str.charAt(i); +} +//converts the string into integer +int rev=Integer.parseInt(str); +//returns the reverse number +return rev; +} +//function that checks the number is mystery or not +static boolean isMysteryNo(int num) +{ +for (int i=1; i <= num/2; i++) +{ +//calling the function that reverse a number and assign it to j +int j = reverse(i); +//compares the sum of two numbers is equal to given number or not +if (i + j == num) +{ +//prints a pair of numbers whose sum is the given number +System.out.println( i + " " + j); +System.out.println(num+ " is a mystery number."); +//returns a boolean value if pair is found +return true; +} +} +System.out.println("The given number is not a mystery number."); +//returns false if pair is not found +return false; +} +//driver code +public static void main(String args[]) +{ +Scanner sc=new Scanner(System.in); +System.out.print("Enter a number: "); +//reading an integer from the user +int num = sc.nextInt(); +//calling the user-defined function to check the number is a mystery or not +isMysteryNo(num); +} +} diff --git a/netconf-server-mr.py b/netconf-server-mr.py new file mode 100644 index 00000000..c8eeb4a8 --- /dev/null +++ b/netconf-server-mr.py @@ -0,0 +1,239 @@ +from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes +import io +import logging +import os +import sys +import threading +import paramiko as ssh +from lxml import etree +import sshutil.server + +from netconf import base +import netconf.error as ncerror +from netconf import NSMAP +from netconf import qmap +from netconf import util + +if sys.platform == 'win32' and sys.version_info < (3, 5): + import backports.socketpair # pylint: disable=E0401,W0611 + +logger = logging.getLogger(__name__) + +try: + import pam + have_pam = True +except ImportError: + have_pam = False + + +class SSHAuthorizedKeysController(ssh.ServerInterface): + """An implementation of paramiko `ServerInterface` that utilizes users + authorized keys file for authentication. + :param users: A list of usernames whose authorized keys will allow access. + """ + def __init__(self, users=None): + self.event = threading.Event() + self.users = users + self.users_keys = {} + if have_pam: + self.pam = pam.pam() + else: + self.pam = None + + def get_user_auth_keys(self, username): + """Parse the users's authorized_keys file if any to look for authorized keys""" + if username in self.users_keys: + return self.users_keys[username] + + self.users_keys[username] = [] + + userdir = os.path.expanduser("~" + username) + if not userdir: + return self.users_keys[username] + + keyfile = os.path.join(userdir, ".ssh/authorized_keys") + if not keyfile or not os.path.exists(keyfile): + return self.users_keys[username] + + with open(keyfile) as f: + for line in f.readlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + values = [x.strip() for x in line.split()] + + exp = None + try: + int(values[0]) # bits value? + except ValueError: + # Type 1 or type 2, type 1 is bits in second value + options_ktype = values[0] + try: + int(values[1]) # bits value? + except ValueError: + # type 2 with options + ktype = options_ktype + data = values[1] + else: + # Type 1 no options. + exp = int(values[1]) + data = values[2] + else: + # Type 1 no options. + exp = int(values[1]) + data = values[2] + + # XXX For now skip type 1 keys + if exp is not None: + continue + + if data: + import base64 + if ktype == "ssh-rsa": + key = ssh.RSAKey(data=base64.decodebytes(data.encode('ascii'))) + elif ktype == "ssh-dss": + key = ssh.DSSKey(data=base64.decodebytes(data.encode('ascii'))) + else: + key = None + if key: + self.users_keys[username].append(key) + return self.users_keys[username] + + def get_allowed_auths(self, username): + # This is only called after the user fails some other authentication type. + if self.users is None: + users = [username] + else: + users = self.users + allowed = [] + if username in users: + if self.pam: + allowed.append("password") + + if self.get_user_auth_keys(username): + allowed.append("publickey") + + allowed = ",".join(allowed) + logger.debug("Allowed methods for user %s: %s", str(username), allowed) + return allowed + + def check_auth_none(self, unused_username): + return ssh.AUTH_FAILED + + def check_auth_publickey(self, username, key): + if not self.get_user_auth_keys(username): + return ssh.AUTH_FAILED + for ukey in self.users_keys[username]: + if ukey == key: + return ssh.AUTH_SUCCESSFUL + return ssh.AUTH_FAILED + + def check_auth_password(self, username, password): + # Don't allow empty user or empty passwords + if not username or not password: + return ssh.AUTH_FAILED + if self.pam and self.pam.authenticate(username, password): + return ssh.AUTH_SUCCESSFUL + return ssh.AUTH_FAILED + + def check_channel_request(self, kind, chanid): + if kind == "session": + return ssh.OPEN_SUCCEEDED + return ssh.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED + + def check_channel_subsystem_request(self, channel, name): + self.event.set() + return name == "netconf" + + +# Backward compat +SSHAuthController = SSHAuthorizedKeysController + + +class SSHUserPassController(ssh.ServerInterface): + """An implementation of paramiko `ServerInterface` that authorizes a single user + and password. + :param username: The username to allow. + :param password: The password to allow. + """ + def __init__(self, username=None, password=None): + self.username = username + self.password = password + self.event = threading.Event() + + def get_allowed_auths(self, username): + del username # unused + return "password" + + def check_auth_none(self, username): + del username # unused + return ssh.AUTH_FAILED + + def check_auth_password(self, username, password): + if self.username == username and self.password == password: + return ssh.AUTH_SUCCESSFUL + return ssh.AUTH_FAILED + + def check_channel_request(self, kind, chanid): + if kind == "session": + return ssh.OPEN_SUCCEEDED + return ssh.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED + + def check_channel_subsystem_request(self, channel, name): + self.event.set() + return name == "netconf" + + +class NetconfServerSession(base.NetconfSession): + """Netconf Server-side session with a client. + This object will be passed to a the server RPC methods. + """ + handled_rpc_methods = set(["close-session", "lock", "kill-session", "unlock"]) + + def __init__(self, channel, server, unused_extra_args, debug): + self.server = server + + sid = self.server._allocate_session_id() + if debug: + logger.debug("NetconfServerSession: Creating session-id %s", str(sid)) + + self.methods = server.server_methods + super(NetconfServerSession, self).__init__(channel, debug, sid) + super(NetconfServerSession, self)._open_session(True) + + if self.debug: + logger.debug("%s: Client session-id %s created", str(self), str(sid)) + + def __del__(self): + self.close() + super(NetconfServerSession, self).__del__() + + def __str__(self): + return "NetconfServerSession(sid:{})".format(self.session_id) + + def close(self): + """Close the servers side of the session.""" + # XXX should be invoking a method in self.methods? + if self.debug: + logger.debug("%s: Closing.", str(self)) + + # Cleanup any locks + locked = self.server.unlock_target_any(self) + method = getattr(self.methods, "rpc_unlock", None) + if method is not None: + try: + # Let the user know. + for target in locked: + method(self, None, target) + except Exception as ex: + if self.debug: + logger.debug("%s: Ignoring exception in rpc_unlock during close: %s", str(self), + str(ex)) + try: + super(NetconfServerSession, self).close() + except EOFError: + if self.debug: + logger.debug("%s: EOF error while closing", str(self)) + + if self.debug: + logger.debug("%s: Closed.", str(self)) \ No newline at end of file diff --git a/netconf-static-route b/netconf-static-route new file mode 100644 index 00000000..6601e10a --- /dev/null +++ b/netconf-static-route @@ -0,0 +1,35 @@ +from ncclient import manager +import xmltodict +import json +import yaml +from jinja2 import Template + +with open('inventory.yml') as f: + inventory = f.read() + +inventory_dict = yaml.load(inventory) +# print(json.dumps(inventory_dict,indent=4)) + +device_list = inventory_dict['CORE'] + +netconf_template = Template(open('static_route_template.xml').read()) + +for device in device_list: + host = device['host'] + route_list = device['static_route'] + + print('----------------------------------------') + print(f'Configuring Static Route on {host}') + print('----------------------------------------') + + netconf_payload = netconf_template.render(route_list=route_list) + + # print(netconf_payload) + + # send the payload to the host + with manager.connect(host=host, port='830', + username='cisco', password='cisco', + hostkey_verify=False) as m: + + netconf_reply = m.edit_config(netconf_payload, target='running') + print(netconf_reply) \ No newline at end of file diff --git a/netmiko-ospf.py b/netmiko-ospf.py new file mode 100644 index 00000000..a57f8009 --- /dev/null +++ b/netmiko-ospf.py @@ -0,0 +1,79 @@ +import yaml +from pprint import pprint +from netmiko import ConnectHandler + + +def read_yaml(yaml_file): + with open(yaml_file) as f: + inventory = f.read() + + inventory_dict = yaml.load(inventory) + return inventory_dict + +def device_connection(router_ip): + device = { + "device_type" : "cisco_ios", + "ip" : router_ip, + "username" : "cisco", + "password" : "cisco" + } + + conn = ConnectHandler(**device) + return conn + +def conf_ip(conn, ip_config): + interface = ip_config['interface'] + ip_addr = ip_config['ip_address'] + config_list = ['interface {}'.format(interface), + 'ip address {}'.format(ip_addr), + 'no shutdown'] + print conn.send_config_set(config_list) + +def conf_dhcp(conn, dhcp_config): + pool = dhcp_config['pool'] + network = dhcp_config['network'] + gateway = dhcp_config['gateway'] + config_list = ['ip dhcp pool {}'.format(pool), + 'network {}'.format(network), + 'default-router {}'.format(gateway)] + print conn.send_config_set(config_list) + +def conf_ospf(conn, ospf_config): + area = ospf_config['area'] + network_list = ospf_config['network'] + config_list = ['router ospf 1'] + for network in network_list: + config_list.append('network {} area {}'.format(network, area)) + + print conn.send_config_set(config_list) + +def main(): + yaml_file = 'inventory.yaml' + inventory_dict = read_yaml(yaml_file) + pprint(inventory_dict) + + for router in inventory_dict['CORE']: + + router_ip = router['host'] + print "-------------------------------" + print "Configuring {}".format(router_ip) + print "-------------------------------" + #connection + conn = device_connection(router_ip) + + #configure ip address + ip_config = router['int_config'] + for conf in ip_config: + conf_ip(conn, conf) + + #configure dhcp + dhcp_config = router['dhcp_config'] + for config in dhcp_config: + conf_dhcp(conn, config) + + #configure ospf + ospf_config = router['ospf_config'] + for config in ospf_config: + conf_ospf(conn, config) + +main() \ No newline at end of file diff --git a/newbubblesort.java b/newbubblesort.java new file mode 100644 index 00000000..436662e3 --- /dev/null +++ b/newbubblesort.java @@ -0,0 +1,35 @@ +public class BubbleSortExample { + static void bubbleSort(int[] arr) { + int n = arr.length; + int temp = 0; + for(int i=0; i < n; i++){ + for(int j=1; j < (n-i); j++){ + if(arr[j-1] > arr[j]){ + //swap elements + temp = arr[j-1]; + arr[j-1] = arr[j]; + arr[j] = temp; + } + + } + } + + } + public static void main(String[] args) { + int arr[] ={3,60,35,2,45,320,5}; + + System.out.println("Array Before Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + System.out.println(); + + bubbleSort(arr);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for(int i=0; i < arr.length; i++){ + System.out.print(arr[i] + " "); + } + + } +} diff --git a/newnodecircularlinkedlist.java b/newnodecircularlinkedlist.java new file mode 100644 index 00000000..ca38cb31 --- /dev/null +++ b/newnodecircularlinkedlist.java @@ -0,0 +1,71 @@ +public class InsertAtStart { + //Represents the node of list. + public class Node{ + int data; + Node next; + public Node(int data) { + this.data = data; + } + } + + //Declaring head and tail pointer as null. + public Node head = null; + public Node tail = null; + + //This function will add the new node at the end of the list. + public void addAtStart(int data){ + //Create new node + Node newNode = new Node(data); + //Checks if the list is empty. + if(head == null) { + //If list is empty, both head and tail would point to new node. + head = newNode; + tail = newNode; + newNode.next = head; + } + else { + //Store data into temporary node + Node temp = head; + //New node will point to temp as next node + newNode.next = temp; + //New node will be the head node + head = newNode; + //Since, it is circular linked list tail will point to head. + tail.next = head; + } + } + + //Displays all the nodes in the list + public void display() { + Node current = head; + if(head == null) { + System.out.println("List is empty"); + } + else { + System.out.println("Adding nodes to the start of the list: "); + do{ + //Prints each node by incrementing pointer. + System.out.print(" "+ current.data); + current = current.next; + }while(current != head); + System.out.println(); + } + } + + public static void main(String[] args) { + InsertAtStart cl = new InsertAtStart(); + + //Adding 1 to the list + cl.addAtStart(1); + cl.display(); + //Adding 2 to the list + cl.addAtStart(2); + cl.display(); + //Adding 3 to the list + cl.addAtStart(3); + cl.display(); + //Adding 4 to the list + cl.addAtStart(4); + cl.display(); + } +} diff --git a/number_system.java b/number_system.java new file mode 100644 index 00000000..2d79738e --- /dev/null +++ b/number_system.java @@ -0,0 +1,40 @@ +import java.util.*; +public class FascinatingNumberExample1 +{ +public static void main(String args[]) +{ +int num, n2, n3; +Scanner sc=new Scanner(System.in); +System.out.print("Enter any Number: "); +num = sc.nextInt(); +n2 = num * 2; +n3 = num * 3; +//concatenating num, n2, and n3 +String concatstr = num + "" + n2 + n3; +boolean found = true; +//checks all digits from 1 to 9 are present or not +for(char c = '1'; c <= '9'; c++) +{ +int count = 0; +//loop counts the frequency of each digit +for(int i = 0; i < concatstr.length(); i++) +{ +char ch = concatstr.charAt(i); +//compares the character of concatstr with i +if(ch == c) +//incerments the count by 1 if the specified condition returns true +count++; +} +//returns true if any of the condition returns true +if(count > 1 || count == 0) +{ +found = false; +break; +} +} +if(found) +System.out.println(num + " is a fascinating number."); +else +System.out.println(num + " is not a fascinating number."); +} +} diff --git a/oddOrEvenNumber.java b/oddOrEvenNumber.java new file mode 100644 index 00000000..b856ccee --- /dev/null +++ b/oddOrEvenNumber.java @@ -0,0 +1,21 @@ +import java.util.Scanner; + +public class oddOrEvenNumber { + public static void main(String[] args) throws Exception { + + Scanner inputNumber = new Scanner(System.in); + + // Check whether a number is even or odd using if else statement + System.out.print("Enter a number:\t"); + int num = inputNumber.nextInt(); + + if (num % 2 == 0) { + System.out.print(num + " is even"); + } else { + System.out.print(num + " is odd"); + } + + inputNumber.close(); + } + +} diff --git a/overidding_MR.java b/overidding_MR.java new file mode 100644 index 00000000..2a6e0c9e --- /dev/null +++ b/overidding_MR.java @@ -0,0 +1,62 @@ + +//example of the overriding method +//return type and signature(parameter) same means the overriding method + +class a1 +{ + void hell() + { + System.out.println("hello i am from i1"); + } +} + +class b1 extends a1 +{ + void hell() + { + + System.out.println("hello i am from i1"); + } +} + +class c1 extends b1{ + void hell() + { + System.out.println("hello i am from i1"); + } +} + +public class polymorph { + + public static void main(String[] args) + { + //where c1 is called reference + // where c1() is called instance + + + //c1 obj1=new c1(); + // obj1.hell(); + + // now we take the reference of b1 and instance c1 as same + + // b1 obj1=new c1(); + // obj1.hell(); + + //it's means that if we change the instance than automatically + //sentence will be changed or method /function will be change + + //reference is a1 and instance c1 + //output is of c1 method is display + + // a1 obj1=new c1(); + //obj1.hell(); + + //reference is a1 and instance b1 + //output is of b1 method is display + + // a1 obj1=new b1(); + // obj1.hell(); + + + } +} diff --git a/overriding.java b/overriding.java new file mode 100644 index 00000000..252f6fea --- /dev/null +++ b/overriding.java @@ -0,0 +1,39 @@ +// A Simple Java program to demonstrate +// method overriding in java + +// Base Class +class Parent { + void show() + { + System.out.println("Parent's show()"); + } +} + +// Inherited class +class Child extends Parent { + // This method overrides show() of Parent + @Override + void show() + { + System.out.println("Child's show()"); + } +} + +// Driver class +class Main { + public static void main(String[] args) + { + // If a Parent type reference refers + // to a Parent object, then Parent's + // show is called + Parent obj1 = new Parent(); + obj1.show(); + + // If a Parent type reference refers + // to a Child object Child's show() + // is called. This is called RUN TIME + // POLYMORPHISM. + Parent obj2 = new Child(); + obj2.show(); + } +} diff --git a/overriding12.java b/overriding12.java new file mode 100644 index 00000000..252f6fea --- /dev/null +++ b/overriding12.java @@ -0,0 +1,39 @@ +// A Simple Java program to demonstrate +// method overriding in java + +// Base Class +class Parent { + void show() + { + System.out.println("Parent's show()"); + } +} + +// Inherited class +class Child extends Parent { + // This method overrides show() of Parent + @Override + void show() + { + System.out.println("Child's show()"); + } +} + +// Driver class +class Main { + public static void main(String[] args) + { + // If a Parent type reference refers + // to a Parent object, then Parent's + // show is called + Parent obj1 = new Parent(); + obj1.show(); + + // If a Parent type reference refers + // to a Child object Child's show() + // is called. This is called RUN TIME + // POLYMORPHISM. + Parent obj2 = new Child(); + obj2.show(); + } +} diff --git a/palindrome b/palindrome new file mode 100644 index 00000000..dc3ad552 --- /dev/null +++ b/palindrome @@ -0,0 +1,17 @@ +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"); +} +} diff --git a/palindrome.java b/palindrome.java new file mode 100644 index 00000000..61b2f1b2 --- /dev/null +++ b/palindrome.java @@ -0,0 +1,27 @@ +import java.util.*; +public class Main +{ + public static void palindrome(int n) + { + int d,sum=0; + int copy=n; + while(n>0) + { + d=n%10; + sum=sum*10+d; + n/=10; + } + if(copy==sum) + System.out.println("Palindrome Number"); + else + System.out.println("Not a Palindrome Number"); + } + public static void main(String args[]) + { + int num; + Scanner sc=new Scanner(System.in); + System.out.println("Enter the number"); + num=sc.nextInt(); + palindrome(num); + } +} diff --git a/palindrome1.java b/palindrome1.java new file mode 100644 index 00000000..c3e60805 --- /dev/null +++ b/palindrome1.java @@ -0,0 +1,31 @@ +import java.util.*; +public class Main +{ + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + System.out.println("check palindrome"); + System.out.println("enter n"); + int nn=sc.nextInt(); + for(int i=1;i<=nn;i++){ + System.out.println("Enter number"); + int num=sc.nextInt(); + String newnum=""; + int n=num; + int d; + while(n!=0){ + d=n%10; + n=n/10; + newnum = newnum+d; + } + if(num==0 || num/10==0){ + System.out.println("not palindrome"); + } + else if(Integer.valueOf(newnum) == num){ + System.out.println("Palindrome"); + } + else{ + System.out.println("not palindrome"); + } + } + } +} diff --git a/palindrome12.java b/palindrome12.java new file mode 100644 index 00000000..dc3ad552 --- /dev/null +++ b/palindrome12.java @@ -0,0 +1,17 @@ +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"); +} +} diff --git a/palindromenumber.java b/palindromenumber.java new file mode 100644 index 00000000..eeae7a5d --- /dev/null +++ b/palindromenumber.java @@ -0,0 +1,9 @@ +public boolean isPalindrome(int x) { + if (x<0 || (x!=0 && x%10==0)) return false; + int rev = 0; + while (x>rev){ + rev = rev*10 + x%10; + x = x/10; + } + return (x==rev || x==rev/10); +} diff --git a/parameterized_recursion.java b/parameterized_recursion.java new file mode 100644 index 00000000..e6f4dc1b --- /dev/null +++ b/parameterized_recursion.java @@ -0,0 +1,28 @@ + +//sum of n numbers + + + +public class parameterized_recursion { + + static int f(int i, int sum){ + if(i<0){ + System.out.println(sum); + return 0; + + } + f(i-1,sum+i); + return 0; + + } + + public static void main(String[] args){ + + int n =5; + int sum =0; + f(n,sum); + + + + } +} diff --git a/parentComponent.html b/parentComponent.html new file mode 100644 index 00000000..cad8b584 --- /dev/null +++ b/parentComponent.html @@ -0,0 +1,10 @@ + \ No newline at end of file diff --git a/pascal triangle in c.c b/pascal triangle in c.c new file mode 100644 index 00000000..ce7ad9b9 --- /dev/null +++ b/pascal triangle in c.c @@ -0,0 +1,19 @@ +#include +int main() { + int rows, coef = 1, space, i, j; + printf("Enter the number of rows: "); + scanf("%d", &rows); + for (i = 0; i < rows; i++) { + for (space = 1; space <= rows - i; space++) + printf(" "); + for (j = 0; j <= i; j++) { + if (j == 0 || i == 0) + coef = 1; + else + coef = coef * (i - j + 1) / j; + printf("%4d", coef); + } + printf("\n"); + } + return 0; +} diff --git a/pattern4.cpp b/pattern4.cpp new file mode 100644 index 00000000..deaa592b --- /dev/null +++ b/pattern4.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main(){ + int n; + cin>>n; + + for(int i=1;i<=n;i++){ + for(int j=1;j<=n;j++){ + if(j<=n-i){ + cout<<" "; + }else{ + cout<<"*"; + } + } + cout< 0) +{ +//determines the last digit of the given number +int digit = n % 10; +//determines the factorial of the digit and add it to the variable sum +sum += factorial[digit]; +//removes the last digit of the given number +n = n / 10; +} +//compares sum with num if they are equal returns the number itself +return (sum == num); +} +} diff --git a/polymorphism.java b/polymorphism.java new file mode 100644 index 00000000..d8d78b95 --- /dev/null +++ b/polymorphism.java @@ -0,0 +1,70 @@ +package vid24oops; + +//Method Overloading or Run time Polymorphism (Functions can be called as per required in any type of Polymorphism) +// class Student{ +// String name; +// int age; + +// public void displayInfo(String name) { +// System.out.println(name); +// } + +// public void displayInfo(int age) { +// System.out.println(age); +// } + +// public void displayInfo(String name, int age) { +// System.out.println(name); +// System.out.println(age); +// } +// } + +// public class polymorphism { +// public static void main(String[] args) { +// Student s1 = new Student(); + +// s1.name = "Adi"; +// s1.age= 21; + +// s1.displayInfo(s1.name); //If we want only name to display + +// s1.displayInfo(s1.age); //If we want only age to display + +// s1.displayInfo(s1.name,s1.age); //If we want name and age to display +// } +// } + +//Run time polymorphism +// abstract class Animal { +// abstract void walk(); +// void breathe() { +// System.out.println("This animal breathes air"); +// } + +// Animal() { +// System.out.println("You are about to create an Animal."); +// } +// } + +// class Horse extends Animal { +// void walk() { +// System.out.println("Horse walks on 4 legs"); +// } +// } + +// class Chicken extends Animal { +// void walk() { +// System.out.println("Chicken walks on 2 legs"); +// } +// } + +// public class polymorphism { +// public static void main(String args[]) { +// Horse horse = new Horse(); +// horse.walk(); +// horse.breathe(); + +// Animal animal = new Animal(); +// animal.walk(); //Gives error when you run, but not when you compile +// } +// } diff --git a/positiveornegative.java b/positiveornegative.java new file mode 100644 index 00000000..1eb50ef0 --- /dev/null +++ b/positiveornegative.java @@ -0,0 +1,19 @@ +public class PositiveNegative { + + public static void main(String[] args) { + + double number = 12.3; + + // true if number is less than 0 + if (number < 0.0) + System.out.println(number + " is a negative number."); + + // true if number is greater than 0 + else if ( number > 0.0) + System.out.println(number + " is a positive number."); + + // if both test expression is evaluated to false + else + System.out.println(number + " is 0."); + } +} diff --git a/pp.cpp b/pp.cpp new file mode 100644 index 00000000..1f27a5f6 --- /dev/null +++ b/pp.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; + +int main(){ + int marks[4]={88,99,66,34}; + int i=0; + // while(i<4){ + // cout< + +!DOCTYPE html> + + + + +

GeeksforGeeks

+ +

It is a Computer Science portal For Geeks

+ + + + + + +
  • Works
  • +
  • Contact
  • +
    +
    +
    97%
    +
    + Adobe Photoshop +
    +
    +
    +
    + These tutorials are excellent. I've learned so much. I can't wait to try more! +
    +
    + testimonial author avatar + Mark Johnson + Envato Tuts+ user +
    +
    +
    + +html> + + + + HTML table border Attribute + + + + +

    GeeksforGeeks

    + +

    HTML table border Attribute

    + + + + + + + + + + + + + + + + + + + + +
    Author Details
    NAMEAGEBRANCH
    BITTU22CSE
    RAMRAM21ECE
    + + + diff --git a/program to add two numbers b/program to add two numbers new file mode 100644 index 00000000..5fcf93a5 --- /dev/null +++ b/program to add two numbers @@ -0,0 +1,15 @@ +class Main { + + public static void main(String[] args) { + + System.out.println("Enter two numbers"); + int first = 10; + int second = 20; + + System.out.println(first + " " + second); + + // add two numbers + int sum = first + second; + System.out.println("The sum is: " + sum); + } +} diff --git a/puzzleGame.java b/puzzleGame.java new file mode 100644 index 00000000..8a4c161c --- /dev/null +++ b/puzzleGame.java @@ -0,0 +1,178 @@ +import java.awt.*; +import java.awt.event.*; +import javax.swing.JOptionPane; +public class Puzzle extends Frame implements ActionListener{ +Button b1,b2,b3,b4,b5,b6,b7,b8,b9; +Puzzle(){ + super("Puzzle - JavaTpoint"); + b1=new Button("1"); + b1.setBounds(50,100,40,40); + b2=new Button("2"); + b2.setBounds(100,100,40,40); + b3=new Button("3"); + b3.setBounds(150,100,40,40); + b4=new Button("4"); + b4.setBounds(50,150,40,40); + b5=new Button("5"); + b5.setBounds(100,150,40,40); + b6=new Button("6"); + b6.setBounds(150,150,40,40); + b7=new Button("7"); + b7.setBounds(50,200,40,40); + b8=new Button(""); + b8.setBounds(100,200,40,40); + b9=new Button("8"); + b9.setBounds(150,200,40,40); + + b1.addActionListener(this); + b2.addActionListener(this); + b3.addActionListener(this); + b4.addActionListener(this); + b5.addActionListener(this); + b6.addActionListener(this); + b7.addActionListener(this); + b8.addActionListener(this); + b9.addActionListener(this); + + add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); + setSize(400,400); + setLayout(null); + setVisible(true); +} +public void actionPerformed(ActionEvent e){ + if(e.getSource()==b1){ + String label=b1.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b1.setLabel(""); + } + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b1.setLabel(""); + } + } + if(e.getSource()==b2){ + String label=b2.getLabel(); + if(b1.getLabel().equals("")){ + b1.setLabel(label); + b2.setLabel(""); + } + if(b3.getLabel().equals("")){ + b3.setLabel(label); + b2.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b2.setLabel(""); + } + } + if(e.getSource()==b3){ + String label=b3.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b3.setLabel(""); + } + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b3.setLabel(""); + } + } + if(e.getSource()==b4){ + String label=b4.getLabel(); + if(b1.getLabel().equals("")){ + b1.setLabel(label); + b4.setLabel(""); + } + if(b7.getLabel().equals("")){ + b7.setLabel(label); + b4.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b4.setLabel(""); + } + } + if(e.getSource()==b5){ + String label=b5.getLabel(); + if(b2.getLabel().equals("")){ + b2.setLabel(label); + b5.setLabel(""); + } + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b5.setLabel(""); + } + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b5.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b5.setLabel(""); + } + } + if(e.getSource()==b6){ + String label=b6.getLabel(); + if(b9.getLabel().equals("")){ + b9.setLabel(label); + b6.setLabel(""); + } + if(b3.getLabel().equals("")){ + b3.setLabel(label); + b6.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b6.setLabel(""); + } + } + if(e.getSource()==b7){ + String label=b7.getLabel(); + if(b4.getLabel().equals("")){ + b4.setLabel(label); + b7.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b7.setLabel(""); + } + } + if(e.getSource()==b8){ + String label=b8.getLabel(); + if(b9.getLabel().equals("")){ + b9.setLabel(label); + b8.setLabel(""); + } + if(b7.getLabel().equals("")){ + b7.setLabel(label); + b8.setLabel(""); + } + if(b5.getLabel().equals("")){ + b5.setLabel(label); + b8.setLabel(""); + } + } + if(e.getSource()==b9){ + String label=b9.getLabel(); + if(b6.getLabel().equals("")){ + b6.setLabel(label); + b9.setLabel(""); + } + if(b8.getLabel().equals("")){ + b8.setLabel(label); + b9.setLabel(""); + } + } + + //congrats code + if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")&&b3.getLabel() + .equals("3")&&b4.getLabel().equals("4")&&b5.getLabel().equals("5") + &&b6.getLabel().equals("6")&&b7.getLabel().equals("7")&&b8.getLabel() + .equals("8")&&b9.getLabel().equals("")){ + JOptionPane.showMessageDialog(this,"Congratulations! You won."); + } +} +public static void main(String[] args) { + new Puzzle(); +} +} diff --git a/pyramid.java b/pyramid.java new file mode 100644 index 00000000..0dd55c66 --- /dev/null +++ b/pyramid.java @@ -0,0 +1,19 @@ +import java.util.*; +public class Pyramid +{ + public static void main(String args[]) + { + int rows,i,k,j; + Scanner sc=new Scanner(System.in); + System.out.println("Enter the no. of rows"); + rows=sc.nextInt(); + for(i=0;i<=rows;i++) + { + for(j=0;j q + = new LinkedList<>(); + for (int i = 0; i < 5; i++) + q.add(i); + + System.out.println("Elements of queue " + + q); + + int removedele = q.remove(); + System.out.println("removed element-" + + removedele); + + System.out.println(q); + + int head = q.peek(); + System.out.println("head of queue-" + + head); + + int size = q.size(); + System.out.println("Size of queue-" + + size); + } +} diff --git a/quickSort_Last_Pivot.cpp b/quickSort_Last_Pivot.cpp new file mode 100644 index 00000000..9f0939dc --- /dev/null +++ b/quickSort_Last_Pivot.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; + return; +} +int partition(int arr[], int start, int end) +{ + int pivot = arr[end]; + int i = start - 1; + for (int j = start; j < end; j++) + { + if (arr[j] <= pivot) + { + i++; + swap(arr[i], arr[j]); + } + } + i++; + swap(arr[i], arr[end]); + return i; +} + +void quickSort(int arr[], int start, int end) +{ + if (start < end) + { + int part = partition(arr, start, end); + quickSort(arr, start, part - 1); + quickSort(arr, part + 1, end); + } +} + +int main() +{ + int size; + cout << "Enter size: "; + cin >> size; + int arr[size]; + cout << "Enter array: "; + for (int i = 0; i < size; i++) + { + cin >> arr[i]; + } + + quickSort(arr, 0, size - 1); + + cout << "Sorted array is: "; + for (int i = 0; i < size; i++) + { + cout << arr[i] << " "; + } + cout << endl; +} \ No newline at end of file diff --git a/quick_sort.java b/quick_sort.java new file mode 100644 index 00000000..595fd0d9 --- /dev/null +++ b/quick_sort.java @@ -0,0 +1,89 @@ +import java.util.*; +public class quick_sort { + static pt=0; + + int partition( int a[], int lb, int ub) + + { + int pivot=a[lb]; + int start=lb; + int end=ub; + + while(startpivot) + { + end--; + } + if(start pattern + txt -> text + q -> A prime number + */ + static void search(String pat, String txt, int q) + { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + // The value of h would be "pow(d, M-1)%q" + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + // Calculate the hash value of pattern and first + // window of text + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; + } + + // Slide the pattern over text one by one + for (i = 0; i <= N - M; i++) { + + // Check the hash values of current window of text + // and pattern. If the hash values match then only + // check for characters on by one + if (p == t) { + /* Check for characters one by one */ + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + System.out.println("Pattern found at index " + i); + } + + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + + // We might get negative value of t, converting it + // to positive + if (t < 0) + t = (t + q); + } + } + } + + public static void main(String[] args) + { + String txt = "Yash Seth"; + String pat = "Seth"; + int q = 101; // A prime number + search(pat, txt, q); + } +} diff --git a/radix sort b/radix sort new file mode 100644 index 00000000..c19a396f --- /dev/null +++ b/radix sort @@ -0,0 +1,80 @@ +// Radix sort Java implementation + +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/radix.java b/radix.java new file mode 100644 index 00000000..c19a396f --- /dev/null +++ b/radix.java @@ -0,0 +1,80 @@ +// Radix sort Java implementation + +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/radix_Sort.java b/radix_Sort.java new file mode 100644 index 00000000..8c1316f8 --- /dev/null +++ b/radix_Sort.java @@ -0,0 +1,70 @@ + +import java.io.*; +import java.util.*; + +class Radix { + + + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} diff --git a/raghav1.cpp b/raghav1.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/raghav1.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/recursion.java b/recursion.java new file mode 100644 index 00000000..3edcc774 --- /dev/null +++ b/recursion.java @@ -0,0 +1,26 @@ +// A Java program to demonstrate +// working of recursion + +class GFG { + static void printFun(int test) + { + if (test < 1) + return; + + else { + System.out.printf("%d ", test); + + // Statement 2 + printFun(test - 1); + + System.out.printf("%d ", test); + return; + } + } + + public static void main(String[] args) + { + int test = 3; + printFun(test); + } +} diff --git a/removewhitespaces.java b/removewhitespaces.java new file mode 100644 index 00000000..9927d832 --- /dev/null +++ b/removewhitespaces.java @@ -0,0 +1,10 @@ +public class Whitespaces { + + public static void main(String[] args) { + String sentence = "T his is b ett er."; + System.out.println("Original sentence: " + sentence); + + sentence = sentence.replaceAll("\\s", ""); + System.out.println("After replacement: " + sentence); + } +} diff --git a/repeat.java b/repeat.java new file mode 100644 index 00000000..96b0de6c --- /dev/null +++ b/repeat.java @@ -0,0 +1,39 @@ +package sorting; + +import java.util.Scanner; + +public class Repeat { + + /** Function for repeated squaring **/ + public double expBySquaring(double x, int n) + { + if (n < 0) + return expBySquaring(1 / x, -n); + else if (n == 0) + return 1; + else if (n == 1) + return x; + else if (n % 2 == 0) + return expBySquaring(x * x, n / 2); + else + return x * expBySquaring(x * x, (n - 1)/2); + } + /** Main function **/ + public static void main (String[] args) + { + Scanner scan = new Scanner(System.in); + System.out.println("Repeated Squaring Algorithm Test\n"); + /** Make an object of RepeatedSquaring class **/ + Repeat rs = new Repeat(); + + /** Accept n , k **/ + System.out.println("\nEnter n and k of (N ^ K)"); + double n = scan.nextDouble(); + int k = scan.nextInt(); + double result = rs.expBySquaring(n, k); + + System.out.println("\nResult : "+ result); + } + + +} diff --git a/rev_arr_recursion.java b/rev_arr_recursion.java new file mode 100644 index 00000000..d4d9ca7f --- /dev/null +++ b/rev_arr_recursion.java @@ -0,0 +1,35 @@ +public class rev_arr_recursion { + + static void printArr(int arr[],int n){ + System.out.println("new array is: \n"); + for (int i =0; i Optional[ListNode]: + prev, curr = None, head + + while curr: + nxt = curr.next + curr.next = prev + prev = curr + curr = nxt + + return prev + + + diff --git a/reverseString.java b/reverseString.java new file mode 100644 index 00000000..44d87522 --- /dev/null +++ b/reverseString.java @@ -0,0 +1,10 @@ +class Solution { + public void reverseString(char[] s) { + char temp; + for(int i=0;i None: + """ + Do not return anything, modify s in-place instead. + """ + for i in range(len(s)//2): + s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] + diff --git a/reversestringusingloop.java b/reversestringusingloop.java new file mode 100644 index 00000000..f764ccf6 --- /dev/null +++ b/reversestringusingloop.java @@ -0,0 +1,16 @@ +import java.util.Scanner; +class ReverseStringExample1 +{ +public static void main(String args[]) +{ +String s; +Scanner sc=new Scanner(System.in); +System.out.print("Enter a String: "); +s=sc.nextLine(); //reading string from user +System.out.print("After reverse string is: "); +for(int i=s.length();i>0;--i) //i is the length of the string +{ +System.out.print(s.charAt(i-1)); //printing the character at index i-1 +} +} +} diff --git a/reversing arry.java b/reversing arry.java new file mode 100644 index 00000000..e95e4d12 --- /dev/null +++ b/reversing arry.java @@ -0,0 +1,28 @@ +// Basic Java program that reverses an array + +public class reverseArray { + + // function that reverses array and stores it + // in another array + static void reverse(int a[], int n) + { + int[] b = new int[n]; + int j = n; + for (int i = 0; i < n; i++) { + b[j - 1] = a[i]; + j = j - 1; + } + + // printing the reversed array + System.out.println("Reversed array is: \n"); + for (int k = 0; k < n; k++) { + System.out.println(b[k]); + } + } + + public static void main(String[] args) + { + int [] arr = {10, 20, 30, 40, 50}; + reverse(arr, arr.length); + } +} diff --git a/righttrianglepatter.java b/righttrianglepatter.java new file mode 100644 index 00000000..cf49bd55 --- /dev/null +++ b/righttrianglepatter.java @@ -0,0 +1,21 @@ +public class RightTrianglePattern +{ +public static void main(String args[]) +{ +//i for rows and j for columns +//row denotes the number of rows you want to print +int i, j, row=6; +//outer loop for rows +for(i=0; i= s2) { + res = res + s1; + } + else { + res = res + s2 - s1; + i++; + } + } + else { + res = res + s1; + } + } + return res; + } + int value(char r) + { + if (r == 'I') + return 1; + if (r == 'V') + return 5; + if (r == 'X') + return 10; + if (r == 'L') + return 50; + if (r == 'C') + return 100; + if (r == 'D') + return 500; + if (r == 'M') + return 1000; + return -1; + } + public static void main(String args[]){ + Solution ob=new Solution(); + Scanner sc=new Scanner(System.in); + System.out.println("Enter a roman number"); + String x=sc.nextLine(); + int a=ob.romanToInt(x); + System.out.println(a); + + } +} \ No newline at end of file diff --git a/rotten_tomatoes.java b/rotten_tomatoes.java new file mode 100644 index 00000000..1a3bb682 --- /dev/null +++ b/rotten_tomatoes.java @@ -0,0 +1,48 @@ +public static boolean isSafe(int[][] grid, int i, int j) { + int n = grid.length; + int m = grid[0].length; + return (i >= 0 && j >= 0 && i < n && j < m); +} +public static int numberOfDays(int[][] grid) { + int days = 2; + boolean flag = false; + int n = grid.length; + int m = grid[0].length; + while (true) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j] == days) { + if (isSafe(grid, i + 1, j) && grid[i + 1][j] == 1) { + grid[i + 1][j] = grid[i][j] + 1; + flag = true; + } + if (isSafe(grid, i, j + 1) && grid[i][j + 1] == 1) { + grid[i][j + 1] = grid[i][j] + 1; + flag = true; + } + if (isSafe(grid, i - 1, j) && grid[i - 1][j] == 1) { + grid[i - 1][j] = grid[i][j] + 1; + flag = true; + } + if (isSafe(grid, i, j - 1) && grid[i][j - 1] == 1) { + grid[i][j - 1] = grid[i][j] + 1; + flag = true; + } + } + } + } + if (flag == false) { + break; + } + flag = false; + days++; + } + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j] == 1) { + days = -1; + } + } + } + return days == -1 ? days : days - 2; +} \ No newline at end of file diff --git a/seaching.cpp b/seaching.cpp new file mode 100644 index 00000000..b2673e0c --- /dev/null +++ b/seaching.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + + +int binarySearch(int arr[], int start, int end, int ele) +{ + if (end >= start) { + int mid = (start+end)/2; + + if (arr[mid] == ele) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + return binarySearch(arr, mid + 1, r, x); + } + return -1; +} + +int main(void) +{ + int n; + cout<<"Enter the size of Array: "; + cin>>n; + int A[n]; + cout<<" Enter the Array: "; + for(int i=0;i> A[i]; + + int ele; + cout<<"Enter the element you wants to search: "; + cin>>ele; + int result = binarySearch(arr, 0, n - 1, ele); + (result == -1) + ? cout << "Element is not present in array" + : cout << "Element is present at index " << result; + return 0; +} diff --git a/searching2dArray.java b/searching2dArray.java new file mode 100644 index 00000000..8da7838f --- /dev/null +++ b/searching2dArray.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +public class Searchin2D { + public static void main(String[] args) { + int[][] arr = { + {12, 34, 65, 87, 12, 32}, + {65, 347, 52, 6, 1, 35}, + {56, 1, 23, 10, 1, 2} + }; + int[] ans=Searchin2d(arr,1); + System.out.println(Arrays.toString(ans)); + } + + public static int[] Searchin2d(int[][] arr,int target) + { + for(int i=0;i< arr.length;i++) + { + for(int j=0;j< arr[i].length;j++) + { + if(arr[i][j]==target) + { + return new int[]{i,j}; + } + } + } + return new int[]{-1,-1}; + } +} + diff --git a/searchinsorted_array.java b/searchinsorted_array.java new file mode 100644 index 00000000..d5ff2da0 --- /dev/null +++ b/searchinsorted_array.java @@ -0,0 +1,51 @@ +import java.util.*; +import java.io.*; +import java.lang.*; + + + +class Main +{ + + static int search(int arr[], int n, int x) + { + int low = 0, high = n - 1; + + while(low <= high) + { + int mid = (low + high) / 2; + + if(arr[mid] == x) + return mid; + if(arr[low] < arr[mid]) + { + if(x >= arr[low] && x < arr[mid]) + high = mid - 1; + else + low = mid + 1; + } + else + { + if(x > arr[mid] && x <= arr[high]) + low = mid + 1; + else + high = mid - 1; + } + } + + + return -1; + } + + public static void main(String args[]) + { + + int arr[] = {10, 20, 40, 60, 5, 8}, n = 6; + + int x = 5; + + System.out.println(search(arr, n, x)); + + } + +} diff --git a/selection-sort.java b/selection-sort.java new file mode 100644 index 00000000..44b9d5e0 --- /dev/null +++ b/selection-sort.java @@ -0,0 +1,42 @@ + +// SelectionSort + +import java.util.*; + +public class SelectionSort { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("enter length"); + int n = sc.nextInt(); + int[] arr = new int[n]; + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + selection(arr); + System.out.println(Arrays.toString(arr)); + } + + static void selection(int[] arr) { + for(int i = 0; i < arr.length; ++i) { + int last = arr.length - i - 1; + int maxIndex = getMaxIndex(arr, 0, last); + swap(arr, maxIndex, last); + } + } + + static void swap(int[] arr, int first, int second) { + int temp = arr[first]; + arr[first] = arr[second]; + arr[second] = temp; + } + + static int getMaxIndex(int[] arr, int start, int end) { + int max = start; + for(int i = start; i <= end; ++i) { + if (arr[max] < arr[i]) { + max = i; + } + } + return max; + } +} diff --git a/selection_sort.java b/selection_sort.java new file mode 100644 index 00000000..6bd22849 --- /dev/null +++ b/selection_sort.java @@ -0,0 +1,32 @@ +public class SelectionSortExample { + public static void selectionSort(int[] arr){ + for (int i = 0; i < arr.length - 1; i++) + { + int index = i; + for (int j = i + 1; j < arr.length; j++){ + if (arr[j] < arr[index]){ + index = j;//searching for lowest index + } + } + int smallerNumber = arr[index]; + arr[index] = arr[i]; + arr[i] = smallerNumber; + } + } + + public static void main(String a[]){ + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + System.out.println(); + + selectionSort(arr1);//sorting array using selection sort + + System.out.println("After Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + } +} diff --git a/set.cpp b/set.cpp new file mode 100644 index 00000000..0217171e --- /dev/null +++ b/set.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; +void print(set &s) +{ + for(string value :s){ + cout< s; + s.insert("abc"); //O(log(n)) + s.insert("def"); + s.insert("ghi"); + s.insert("abc"); + //auto it= s.find("abc"); //O(log(n)) + //if(it!=s.end()){ + // s.erase(it); + //} + //s.erase("abc"); + print (s); + + /* unordered_set s; + s.insert(1); //O(1) + s.insert(4); + s.insert(2); + s.insert(3); + auto it= s.find(2); //O(1) + if(it!=s.end()){ + s.erase(it); + } + for(int value :s){ + cout< s; //it can store doublicate strings + s.insert("abc"); //O(log(n)) + s.insert("abc"); + s.insert("ghi"); + s.insert("jkl"); + + /* auto it= s.find("abc"); //O(log(n)) + if(it!=s.end()){ + s.erase(it); + }*/ + // s.erase("abc") //it will erase both "abc" from the set + + /*for(string value :s){ + cout< mylist = new ArrayList(); + + // Adding custom input elements to list object + mylist.add("Apple"); + mylist.add("Orange"); + mylist.add("Mangos"); + mylist.add("Banana"); + mylist.add("Plum"); + mylist.add("qa"); + + // list before shuffling + System.out.println("Original List : \n" + mylist); + + // Shuffling the list + Collections.shuffle(mylist); + + // list after shuffling + System.out.println("\nShuffled List : \n" + mylist); + } +} diff --git a/shuffling.java b/shuffling.java new file mode 100644 index 00000000..e05e4cb8 --- /dev/null +++ b/shuffling.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + // Creating an array list + ArrayList numbers = new ArrayList<>(); + + // Add elements + numbers.add(1); + numbers.add(2); + numbers.add(3); + System.out.println("Sorted ArrayList: " + numbers); + + // Using the shuffle() method + Collections.shuffle(numbers); + System.out.println("ArrayList using shuffle: " + numbers); + + } +} diff --git a/sierpinski.java b/sierpinski.java new file mode 100644 index 00000000..acc74e6a --- /dev/null +++ b/sierpinski.java @@ -0,0 +1,28 @@ +import java.util.*; +import java.io.*; +class sierpinski +{ + static void printSierpinski(int n) + { + for (int i = n - 1; i >= 0; i--) { + for (int j = 0; j < i; j++) { + System.out.print(" "); + } + for (int k = 0; k + i < n; k++) { + if ((k & i) != 0) + System.out.print(" "+" "); + else + System.out.print("* "); + } + System.out.print("\n"); + } + } + public static void main(String args[]) + { + int n; + Scanner s= new Scanner(System.in); + n= s.nextInt(); + printSierpinski(n); + } +} + \ No newline at end of file diff --git a/smithnumber.java b/smithnumber.java new file mode 100644 index 00000000..88482672 --- /dev/null +++ b/smithnumber.java @@ -0,0 +1,78 @@ +import java.util.*; +public class SmithNumberExample1 +{ +//function finds the sum of digits of its prime factors +static int findSumPrimeFactors(int n) +{ +int i=2, sum=0; +while(n>1) +{ +if(n%i==0) +{ +sum=sum+findSumOfDigit(i); +n=n/i; +} +else +{ +do +{ +i++; +} +while(!isPrime(i)); +} +} +//returns the sum of digits of prime factors +return sum; +} +//function finds the sum of digits of the given numbers +static int findSumOfDigit(int n) +{ +//stores the sum +int s=0; +while(n>0) +{ +//finds the last digit of the number and add it to the variable s +s=s+n%10; +//removes the last digit from the given number +n=n/10; +} +//returns the sum of digits of the number +return s; +} +//function checks if the factor is prime or not +static boolean isPrime(int k) +{ +boolean b=true; +int d=2; +while(d { + JFrame ex = new Snake(); + ex.setVisible(true); + }); + } +} \ No newline at end of file diff --git a/snake.pde b/snake.pde new file mode 100644 index 00000000..963531c0 --- /dev/null +++ b/snake.pde @@ -0,0 +1,88 @@ +ArrayListx=new ArrayList(),y=new ArrayList(); +int w=30,h=30,blocks=20,direction=2,fx=15,fy=15,fc1=255,fc2=255,fc3=255,speed=8; +int[] x_dir={0,0,1,-1},y_dir={1,-1,0,0}; +boolean gameover=false; + + + +void setup(){ + size(600,600); + x.add(0); + y.add(15); +} + + +void draw(){ + background(0); + fill(#084D15); + for(int i =0 ; i=w || y.get(0)>=h) gameover=true; + + for(int i =1; i=2) speed-=1; + fx=(int)random(0,w); + fy=(int)random(0,h); + fc1=(int)random(255); + fc2=(int)random(255); + fc3=(int)random(255); + + } + else{ + x.remove(x.size()-1); + y.remove(y.size()-1); + } +} + } + else{ + fill(200,200,0); + textSize(30); + textAlign(CENTER); + text("GAME OVER \n Your Score is : "+x.size()+"\n Press Enter", width/2,height/3); + if(keyCode == ENTER){ + x.clear(); + y.clear(); + x.add(0); + y.add(15); + direction=2; + speed=8; + gameover= false; + + } +} + + + //keyPressed(); + +} + + +void keyPressed(){ + +int newdir=keyCode==DOWN? 0:(keyCode==UP?1:(keyCode==RIGHT?2:(keyCode==LEFT?3:-1))); +if(newdir != -1){ +direction = newdir; +} + +} diff --git a/sodukoSolver.cpp b/sodukoSolver.cpp new file mode 100644 index 00000000..f106151d --- /dev/null +++ b/sodukoSolver.cpp @@ -0,0 +1,48 @@ +// Leetcode Problem :- 37 + +class Solution { +public: + void solveSudoku(vector>& board) { + sudokuSolver(board, 0, 0); + } + bool sudokuSolver(vector>& board, int currentRow, int currentCol){ + if(currentRow == board.size()) + return true; + // Checking for row and column + int nextRow, nextCol; + if(currentCol == 8){ + nextRow = currentRow + 1; + nextCol = 0; + } + else{ + nextRow = currentRow; + nextCol = currentCol + 1; + } + + // Recursive Function + if(board[currentRow][currentCol] != '.') + return sudokuSolver(board, nextRow, nextCol); + for(char value = '1'; value <= '9'; value++){ + if(isValid(board, currentRow, currentCol,value)){ + board[currentRow][currentCol] = value; + if(sudokuSolver(board, nextRow, nextCol) == true) + return true; + board[currentRow][currentCol] = '.'; + } + } + return false; + } + + // Checking validity + bool isValid(vector>& board, int currentRow, int currentCol, char value){ + for(int i = 0; i < 9; i++){ + if(board[currentRow][i] == value) + return false; + if(board[i][currentCol] == value) + return false; + if(board[3*(currentRow/3) + i/3][3*(currentCol/3) + i%3] == value) + return false; + } + return true; + } +}; diff --git a/soortarray.java b/soortarray.java new file mode 100644 index 00000000..3eadbd84 --- /dev/null +++ b/soortarray.java @@ -0,0 +1,17 @@ +import java.util.Arrays; +public class SortArrayExample1 +{ +public static void main(String[] args) +{ +//defining an array of integer type +int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34}; +//invoking sort() method of the Arrays class +Arrays.sort(array); +System.out.println("Elements of array sorted in ascending order: "); +//prints array using the for loop +for (int i = 0; i < array.length; i++) +{ +System.out.println(array[i]); +} +} +} diff --git a/sort_array.java b/sort_array.java new file mode 100644 index 00000000..7e9a420f --- /dev/null +++ b/sort_array.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +class GFG { + public static void main(String args[]) + { + int[] arr = { 5, -2, 23, 7, 87, -42, 509 }; + System.out.println("The original array is: "); + for (int num : arr) { + System.out.print(num + " "); + } + Arrays.sort(arr); + System.out.println("\nThe sorted array is: "); + for (int num : arr) { + System.out.print(num + " "); + } + } +} diff --git a/sort_queue.java b/sort_queue.java new file mode 100644 index 00000000..8bd0afcd --- /dev/null +++ b/sort_queue.java @@ -0,0 +1,85 @@ +// Java program to implement sorting a +// queue data structure +import java.util.LinkedList; +import java.util.Queue; +class GFG +{ + // Queue elements after sortIndex are + // already sorted. This function returns + // index of minimum element from front to + // sortIndex + public static int minIndex(Queue list, + int sortIndex) + { + int min_index = -1; + int min_value = Integer.MAX_VALUE; + int s = list.size(); + for (int i = 0; i < s; i++) + { + int current = list.peek(); + + // This is dequeue() in Java STL + list.poll(); + + // we add the condition i <= sortIndex + // because we don't want to traverse + // on the sorted part of the queue, + // which is the right part. + if (current <= min_value && i <= sortIndex) + { + min_index = i; + min_value = current; + } + list.add(current); + } + return min_index; +} + + // Moves given minimum element + // to rear of queue + public static void insertMinToRear(Queue list, + int min_index) + { + int min_value = 0; + int s = list.size(); + for (int i = 0; i < s; i++) + { + int current = list.peek(); + list.poll(); + if (i != min_index) + list.add(current); + else + min_value = current; + } + list.add(min_value); + } + + public static void sortQueue(Queue list) + { + for(int i = 1; i <= list.size(); i++) + { + int min_index = minIndex(list,list.size() - i); + insertMinToRear(list, min_index); + } + } + + //Driver function + public static void main (String[] args) + { + Queue list = new LinkedList(); + list.add(30); + list.add(11); + list.add(15); + list.add(4); + + //Sort Queue + sortQueue(list); + + //print sorted Queue + while(list.isEmpty()== false) + { + System.out.print(list.peek() + " "); + list.poll(); + } + } +} diff --git a/sortingUsingsort.java b/sortingUsingsort.java new file mode 100644 index 00000000..0bfebd01 --- /dev/null +++ b/sortingUsingsort.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collections; + +class Main { + public static void main(String[] args) { + + // Creating an array list + ArrayList numbers = new ArrayList<>(); + + // Add elements + numbers.add(4); + numbers.add(2); + numbers.add(3); + System.out.println("Unsorted ArrayList: " + numbers); + + // Using the sort() method + Collections.sort(numbers); + System.out.println("Sorted ArrayList: " + numbers); + + } +} diff --git a/sortmapbyvalue.java b/sortmapbyvalue.java new file mode 100644 index 00000000..c35e534f --- /dev/null +++ b/sortmapbyvalue.java @@ -0,0 +1,41 @@ +import java.util.*; +import java.util.Map.Entry; + +class Main { + + public static void main(String[] args) { + + // create a map and store elements to it + LinkedHashMap capitals = new LinkedHashMap(); + capitals.put("Nepal", "Kathmandu"); + capitals.put("India", "New Delhi"); + capitals.put("United States", "Washington"); + capitals.put("England", "London"); + capitals.put("Australia", "Canberra"); + + // call the sortMap() method to sort the map + Map result = sortMap(capitals); + + for (Map.Entry entry : result.entrySet()) { + System.out.print("Key: " + entry.getKey()); + System.out.println(" Value: " + entry.getValue()); + } + } + + public static LinkedHashMap sortMap(LinkedHashMap map) { + List > capitalList = new LinkedList<>(map.entrySet()); + + // call the sort() method of Collections + Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue())); + + // create a new map + LinkedHashMap result = new LinkedHashMap(); + + // get entry from list to the map + for (Map.Entry entry : capitalList) { + result.put(entry.getKey(), entry.getValue()); + } + + return result; + } +} diff --git a/stack_usingarrays.java b/stack_usingarrays.java new file mode 100644 index 00000000..dbe78b88 --- /dev/null +++ b/stack_usingarrays.java @@ -0,0 +1,47 @@ +import java.util.Stack; + +public class stack_usingarrays { + static int push(int k,int []arr,int i){ + int temp=i; + temp=temp+1; + arr[temp]=k; + + return temp; + } + static int pop(int []arr,int i){ + int temp=i; + temp=temp-1; + arr[i]=0; + return temp; + } + static int top(int arr[],int temp){ + return arr[temp+1]; + } + static boolean empty(int temp){ + boolean flags=false; + //if temp is pointing at imagnary point , i.e, -1 + if (temp==-1){ + flags=true; + } + + return flags; + } + + + + public static void main(String[] args) { + int[] arr=new int[4]; + //pushing the first + var temp=-1; + + //printing the array + + + System.out.println( push(3,arr,temp)); + System.out.println(push(4,arr,temp)); + + push(4,arr,temp); + push(4,arr,temp); + System.out.println( empty(temp));// + } +} diff --git a/stacks in java.java b/stacks in java.java new file mode 100644 index 00000000..4fddf215 --- /dev/null +++ b/stacks in java.java @@ -0,0 +1,53 @@ +import java.io.*; +import java.util.*; + +class Test +{ + static void stack_push(Stack stack) + { + for(int i = 0; i < 5; i++) + { + stack.push(i); + } + } + + static void stack_pop(Stack stack) + { + System.out.println("Pop Operation:"); + + for(int i = 0; i < 5; i++) + { + Integer y = (Integer) stack.pop(); + System.out.println(y); + } + } + + static void stack_peek(Stack stack) + { + Integer element = (Integer) stack.peek(); + System.out.println("Element on stack top: " + element); + } + + static void stack_search(Stack stack, int element) + { + Integer pos = (Integer) stack.search(element); + + if(pos == -1) + System.out.println("Element not found"); + else + System.out.println("Element is found at position: " + pos); + } + + + public static void main (String[] args) + { + Stack stack = new Stack(); + + stack_push(stack); + stack_pop(stack); + stack_push(stack); + stack_peek(stack); + stack_search(stack, 2); + stack_search(stack, 6); + } +} diff --git a/stacqueuek.cpp b/stacqueuek.cpp new file mode 100644 index 00000000..01189665 --- /dev/null +++ b/stacqueuek.cpp @@ -0,0 +1,70 @@ +/* Program to implement a stack using +two queue */ +#include + +using namespace std; + +class Stack { + // Two inbuilt queues + queue q1, q2; + +public: + void push(int x) + { + // Push x first in empty q2 + q2.push(x); + + // Push all the remaining + // elements in q1 to q2. + while (!q1.empty()) { + q2.push(q1.front()); + q1.pop(); + } + + // swap the names of two queues + queue q = q1; + q1 = q2; + q2 = q; + } + + void pop() + { + // if no elements are there in q1 + if (q1.empty()) + return; + q1.pop(); + } + + int top() + { + if (q1.empty()) + return -1; + return q1.front(); + } + + int size() + { + return q1.size(); + } +}; + +// Driver code +int main() +{ + Stack s; + s.push(1); + s.push(2); + s.push(3); + + cout << "current size: " << s.size() + << endl; + cout << s.top() << endl; + s.pop(); + cout << s.top() << endl; + s.pop(); + cout << s.top() << endl; + + cout << "current size: " << s.size() + << endl; + return 0; +} diff --git a/string_palindrome.cpp b/string_palindrome.cpp new file mode 100644 index 00000000..c8bd7393 --- /dev/null +++ b/string_palindrome.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +string isPalindrome(string s){ + string n=s; + + //reversing string n + reverse(n.begin(), n.end()); + + //condition to be palindrome + if (s==n){ + return "is a palindrome"; + } + else + return "is not a palindrome"; +} + +int main(){ + string s="abdedcba"; + cout<= 0; i--) { + + rev = rev + str.charAt(i); + + } + + + + // Checking if both the strings are equal + + if (str.equals(rev)) { + + ans = true; + + } + + return ans; + + } + + public static void main(String[] args) + + { + + // Input string + + String str = "geeks"; + + + + // Convert the string to lowercase + + str = str.toLowerCase(); + + boolean A = isPalindrome(str); + + System.out.println(A); + + } + +} diff --git a/style.css b/style.css new file mode 100644 index 00000000..5e008377 --- /dev/null +++ b/style.css @@ -0,0 +1,640 @@ +*{ + margin: 0; + padding: 0; + font-family: 'Noto Serif', serif; +} +.header{ + min-height: 100vh; + width:100% ; + background-image: linear-gradient(rgba(4,9,30,0.7),rgba(4,9,30,0.7)),url(food/background.jpg); +background-position: center; +background-size: cover; +} +nav{ + display: flex; + padding: 2% 6%; + justify-content: space-between; + align-items: center; + font-weight: bold; +} +nav img{ + width: 100px; +} +.nav-links{ + flex:1 ; + text-align: right; +} + +.nav-links ul li{ + list-style:none; +display:inline-block; +padding: 8px 12px; +position: relative; +} +.nav-links ul li a{ + color: azure; + text-decoration: none; + font-size: 13px; + } + + .nav-links ul li::after + { + content: ''; + width: 0%; + height: 2px; + background: #263063; + display: block; + margin: auto; + transition: 1.5s; + } + .nav-links ul li:hover::after + { + width: 100%; + } + + .text-box{ + width: 90%; + color: #ccc; + position: absolute; + top:43%; + left: 50%; + transform: translate(-50%,-50%); + text-align: center; + } +.text-box h1{ + font-size: 62px; +} +.text-box p{ + margin: 10px 0 40px; + font-size: 14px; + color: whitesmoke; +} +.hero-btn{ + display: inline-block; + text-decoration: none; + border: 1px solid #7f5e8f; + color: #f9f9f9; + padding: 12px 34px; + font-size: 13px; + background: transparent; + position: relative; + cursor: pointer; +} +.hero-btn:hover{ + background: rgb(26, 26, 110); + border:1px solid rgba(4,9,30,0.7);; + transition: 1s; +} +h2{ + color: #eee7e7; +} + + .Hot_Sale{ + display: flex; + width: auto; + height: 360px; + background-color: rgba(4,9,30,0.7); + position: relative; + top: 280px; + justify-content: space-around; + } + + .burger{ + background-image: url(food/burger.jpg); + background-size: 300px 300px; + background-repeat: no-repeat; + background-position: center; + width: 300px; + height: 300px; + } + + .Pizza{ + background-image: url(food/pizza.jpg); + background-size: 300px 300px; + background-repeat: no-repeat; + background-position: center; + width: 300px; + height: 300px; + + } + + .burger2{ + background-image: url(food/burger\ 2.jpg); + background-size: 300px 300px; + background-repeat: no-repeat; + background-position: center; + width: 300px; + height: 300px; + + } + .Cateogry{ + position: relative; + background-color: White; + top: 50px; + color: Black; + width: 300px; + height: 300px; + border: 1px solid white; + } + + .Hidden{ + position: relative; + + bottom: 100px; + display: none; + padding-left: 5px; + width: auto; + height: 100px; + font-family: 'Times New Roman'; + background: linear-gradient(360deg, rgba(4,9,30,0.7),rgba(4,9,30,0.7)); + } + + .burger:hover + .Hidden{ + display: flex; + color: black; + } + + .Hidden2{ + position: relative; + bottom: 100px; + font-family: 'Times New Roman', Times, serif; + display: none; + padding-left: 5px; + width: auto; + height: 100px; + background: linear-gradient(360deg, rgba(4,9,30,0.7),rgba(4,9,30,0.7)); + } + + .Pizza:hover + .Hidden2{ + display: flex; + color: black; + } + + .Hidden3{ + position: relative; + bottom: 100px; + display: none; + padding-left: 5px; + width: auto; + height: 100px; + background: linear-gradient(360deg, rgba(4,9,30,0.7),rgba(4,9,30,0.7)); + } + + .burger2:hover + .Hidden3{ + display: flex; + color: black; + } + + + + +.doggy img{ + width: 120px; height: 190px; + position: absolute; + left: 160px; + top: 560%; + animation-name: doggy; + animation-duration: s; + animation-timing-function: linear; + animation-iteration-count: 0; +} + +@keyframes doggy{ + + 0%{left: 70px} + 100%{ left: 700% } +} + + +/*food*/ +.food +{ + width: 80%; + margin: auto; + text-align: center; + padding-top:290px ; +} +h1{ + color: #ccc; + font-size: 36px; + font-weight: 600; +} +p{ + color: #ccc; + font-size: 14px; + font-weight: 300; + line-height: 22px; + padding: 10px; +} + +.row +{ + margin-top: 1%; + display: flex; + justify-content: space-between; +} +.food-col{ + flex-basis: 32%; + background: rgba(24, 41, 112, 0.7); + border-radius: 10px; + margin-bottom: 5%; + padding: 20px 12px; + box-sizing: border-box; +} + +h3{ + text-align: center; + color: #ccc; + font-weight:600 ; + margin: 10px 0; +} +.food-col:hover +{ + box-shadow: 0 0 20px 0px rgba(29, 63, 114, 0.4); +} +@media(max-width:700px){ +.row +{ + flex-direction:column; +} +} + + +/*Locations*/ +.location{ + width: 80%; + margin: auto; + text-align: center; + padding-top: 1waq0px; +} +.location-col{ + flex-basis: 32%; + border-radius: 10px; + margin-bottom:30px ; + position: relative; + overflow:hidden; +} + +.location-col img { + width: 100%; +} +.layer +{ + background: transparent; + height: 100%; + width:100%; + position: absolute; + top: 0; + left:0; + transition: 0.5s; + +} + +.layer:hover{ + + background:rgba(110, 83, 83, 0.7); +} + +.layer h3{ + color: #eee7e7; + bottom: 0; + left: 50%; + position: absolute; + width: 100%; + font-weight: 500; + font-size:26px; + transform: translateX(-50%); + opacity: 0; + transition: 0.5s; + +} +.layer:hover h3{ + bottom: 49%; + opacity: 1; +} + +/* menu*/ + +.menu{ + width: 80%; + margin:auto; + text-align: center; + padding-top: 5px; +} +.menu-col{ + flex-basis:31%; +border-radius: 10px; +margin-bottom:5%; +position: relative; + overflow:hidden; +} +.menu-col img{ + width: 100%; + border-radius: 10px; +} +.menu-col p{ + padding: 0; +} +.menu-col h3{ + margin-top: 16px; + margin-bottom: 15px; + text-align: left; +} +.testimonials{ + width: 92%; + margin: auto; + padding-top: 1px; + text-align: center; +} +.testimonials-col{ + flex-basis: 44%; + border-radius: 12px; + margin-bottom:5% ; + text-align: left; + background: #5b5269; + padding: 25px; + cursor: pointer; + display: flex; +} +.testimonials-col img +{ + height: 40px; + margin-left: 2px; + margin-right: 30px; + border-radius: 50%; +} + +.testimonials-col p{ + margin-top: 15px; +} + +.cta{ + margin:100px auto ; + width:80% ; + top: 80px; + background-image: linear-gradient(rgba(0,0,0,0.7),rgba(0,0,0,0.7)),url(images/banner2.jpg); + background-position:center ; + background-size: cover; + border-radius: 10px; + text-align: center ; + padding: 100px 0; +} +.cta h1{ + color: #fff; + margin-bottom: 40px; + padding: 0; +} +@media(max-width:700px){ + .cta h1{ + font-size: 24px; + } +} + + +.footer{ + width: 100%; + text-align: center; + padding: 30px 0; +} +.footer h4{ + margin-bottom: 25px; + margin-top: 20px; + font-weight: 600; +} +.icons .fa{ + color: #f44336; + margin: 0 13px; + cursor: pointer; + padding: 18px 0; +} +.fa-heart-o{ + color: #f44336; +} + + .signupbtn { + float: left; + width: 50%; + background-color: #04AA6D; + color: white; + padding: 10px 10px; + margin: 1px 0; + border: none; + cursor: pointer; + width: 100%; + opacity: 0.9; + } + .signupbtn:hover { + opacity: 2; + } + .azna2 { + height: 400px; + width: 650px; + padding-top: 20px; + background-color: maroon; + border-style: double; + border-color: white; + margin-right: 90px; + /* padding-left: 20px; */ + /* margin-left: 50px; + margin-top: 5px; */ + /* justify-content: space-between; */ + } + + +#azna-6 input[type="text"], +#azna-6 input[type="email"] +{ + width: 100%; + border: 1px solid #ccc; + background: #fff; + margin: 0 0 5px; + padding: 10px; + border-radius: 25px; +} + +#azna-6 input[type="text"]:hover, +#azna-6 input[type="email"]:hover +{ + transition: border-color 0.3s ease-in-out; + border: 1px solid #8a8989; +} + +#azna-6 button[type="submit"] { + cursor: pointer; + width: 100%; + border: none; + background: #6b188b; + color: #fff; + margin: 0 0 5px; + padding: 10px; + font-size: 15px; + margin-top: 10px; +} + +#azna-6 button[type="submit"]:hover { + background: #752196; +} +#azna-6 button[type="submit"]:active { + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5); +} +#azna-6 input:focus +{ + outline: 0; + border: 1px solid #aaa; +} + +.aznafooter +{ + background-color: orange; + text-align: center; + margin-top: 1px; +} + + +.azna-1 { + width: 100%; + height: auto; + overflow: hidden; + } + + .azna-2 { + width: 500px; + height: 300px; + float: left; + margin-left: 10px; + } + + .azna-2 img { + width: 250px; + height: 250px; + position: absolute; + left: 100px; + } + + .azna-3 { + width: 300px; + height: 300px; + margin-left: 270px; + margin-top: 30px; + } + + .azna-3 img { + width: 20px; + height: 20px; + position: relative; + left: -215px; + } + + .azna-5 { + float: right; + width: 350px; + margin-bottom:80px; + margin-right: 200px; + } + + .azna-5 h2 { + margin-bottom: 10px; + margin-left: 70px; + } + + #azna-6 { + background: #f9f9f9; + padding: 25px; + margin: 50px 0; + border-radius: 20px; + margin-bottom: 5px; + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 ; + } + + fieldset { + border: medium none !important; + margin: 0 0 10px; + min-width: 100%; + padding: 0; + width: 100%; + } + + #azna-6 input[type="text"], + #azna-6 input[type="email"] + { + width: 100%; + border: 1px solid #ccc; + background: #fff; + margin: 0 0 5px; + padding: 10px; + border-radius: 25px; + } + + #azna-6 input[type="text"]:hover, + #azna-6 input[type="email"]:hover + { + transition: border-color 0.3s ease-in-out; + border: 1px solid #8a8989; + } + + #azna-6 button[type="submit"] { + cursor: pointer; + width: 100%; + border: none; + background: #4e2177; + color: lightgray; + margin: 0 0 5px; + padding: 10px; + font-size: 15px; + margin-top: 10px; + } + + #azna-6 button[type="submit"]:hover { + background: #752196; + } + #azna-6 button[type="submit"]:active { + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5); + } + #azna-6 input:focus + { + outline: 0; + border: 1px solid #aaa; + } + + .aznafooter + { + background-color: #7f5e8f; + text-align: center; + margin-top: 1px; + } + +nav .fa{ + display: none ; +} + @media screen and (max-width: 400px) + { + .text-box h1{ + font-size: 20px; + } + .nav-links ul { + display: block; + } + .nav-links{ + position: absolute; + height: 100vh; + width: 200px; + top: 0; + right: -200px; + text-align: left; + z-index: 2; + transition: 1s; + } + .nav .fa{ + display: block; + color: #fff; + margin: 10px; + font-size: 22px; + cursor:pointer; + } + .nav-links ul { + padding: 30px; + } + + } + + \ No newline at end of file diff --git a/subscribe.java b/subscribe.java new file mode 100644 index 00000000..8484c95e --- /dev/null +++ b/subscribe.java @@ -0,0 +1,204 @@ +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ + +// int age; +// System.out.println("Enter your age"); +// Scanner sc =new Scanner(System.in); +// age = sc.nextInt(); +// // if(age>56){ +// // System.out.println("you are experienced"); +// // } +// // else if(age>46){ +// // System.out.println("You are semi experienced"); +// // } +// // else{ +// // System.out.println("you are not experienced"); +// // } +// switch(age){ +// case 18: +// System.out.println("you are going to be an adult"); +// break; +// case 23: +// System.out.println("you are going to be young"); +// break; +// case 60: +// System.out.println("you are going to be old"); +// break; +// default: +// System.out.println("enjoy life"); +// break; +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// int x=2; +// int y; +// System.out.println("Enter value of y:"); +// Scanner sc = new Scanner(System.in); +// y = sc.nextInt(); +// switch(y){ +// case 0 : +// System.out.println('1'); +// break; +// case 1 : +// System.out.println(x); +// break; +// case 2 : +// System.out.println( x * x); +// break; +// case 3 : +// System.out.println( x * x * x ); +// break; +// case 4 : +// System.out.println( x * x * x * x); +// break; +// default : +// System.out.println("No match exists."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// char LetterGrade; +// public static void main(String[] args){ +// System.out.println("Enter lettergrade"); +// Scanner sc = new Scanner(System.in); +// char LetterGrade = sc.next().charAt(0); +// switch (LetterGrade) { +// case 'a' : +// case 'A' : System.out.print( "Excellent"); +// break; +// case 'b' : +// case 'B' : System.out.print("Superior"); +// break; +// case 'C' : +// case 'c' : System.out.print("Average"); +// break; case 'd' : +// case 'D' : System.out.print(" Poor"); +// break; +// case 'f' : +// case 'F' : System.out.print( " Try again"); +// break; +// default : System.out.print("This is not a recognized letter grade."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// char What; +// System.out.println("Enter lettergrade"); +// Scanner sc = new Scanner(System.in); +// What = sc.next().charAt(0); +// switch (What) { +// case 'c' : +// case 'C' : System.out.print(" Bobo "); +// case 'y' : +// case 'P' : System.out.print(" Is a Dog "); +// break; +// case 'x' : +// case 'X' : System.out.print(" Try But "); +// case 'z' : +// case 'Z' : System.out.print(" Cannot"); +// default : System.out.print(" Help You."); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// public static void main(String[] args){ +// int Year; +// System.out.println("Enter your age"); +// Scanner sc =new Scanner(System.in); +// Year = sc.nextInt(); +// // if (Year == 1) +// // System.out.print(" Freshman "); else if (Year == 2) +// // System.out.print(" Sophomore "); +// // else if (Year == 3) +// // System.out.print(" Junior "); +// // else if (Year == 4) +// // System.out.print(" Senior "); +// // else +// // System.out.print(" Graduate "); +// switch(Year){ +// case 1: +// System.out.println("Freshman"); +// break; +// case 2: +// System.out.println("Sophomore"); +// break; +// case 3: +// System.out.println("Junior"); +// break; +// case 4: +// System.out.println("Senior"); +// break; +// default: +// System.out.println("Graduate"); +// } +// } +// } +// import java.util.Scanner; +// public class subscribe{ +// static void gp(int a,int r,int n){ +// int current_term; +// for(int i=0;i0, we iterate + // for next column + if (grid[row][col] != 0) + return solveSudoku(grid, row, col + 1); + + for (int num = 1; num < 10; num++) { + + // Check if it is safe to place + // the num (1-9) in the + // given row ,col ->we move to next column + if (isSafe(grid, row, col, num)) { + + /* assigning the num in the current + (row,col) position of the grid and + assuming our assigned num in the position + is correct */ + grid[row][col] = num; + + // Checking for next + // possibility with next column + if (solveSudoku(grid, row, col + 1)) + return true; + } + /* removing the assigned num , since our + assumption was wrong , and we go for next + assumption with diff num value */ + grid[row][col] = 0; + } + return false; + } + + /* A utility function to print grid */ + static void print(int[][] grid) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + System.out.print(grid[i][j] + " "); + System.out.println(); + } + } + + // Check whether it will be legal + // to assign num to the + // given row, col + static boolean isSafe(int[][] grid, int row, int col, + int num) + { + + // Check if we find the same num + // in the similar row , we + // return false + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; + + // Check if we find the same num + // in the similar column , + // we return false + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; + + // Check if we find the same num + // in the particular 3*3 + // matrix, we return false + int startRow = row - row % 3, startCol + = col - col % 3; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + startCol] == num) + return false; + + return true; + } + + // Driver Code + public static void main(String[] args) + { + int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + + if (solveSudoku(grid, 0, 0)) + print(grid); + else + System.out.println("No Solution exists"); + } + // This is code is contributed by Pradeep Mondal P +} diff --git a/sum of n natural no..cpp b/sum of n natural no..cpp new file mode 100644 index 00000000..0584e74f --- /dev/null +++ b/sum of n natural no..cpp @@ -0,0 +1,18 @@ +// 1). Write a program to calculate the sum of the +// first 10 natural numbers. +// +#include +using namespace std; + +int main() +{ + int n,i,sum=0; + cout<<"the value of n is : "; + cin>>n; + for(i=1;i<=n;i++) + { + sum+=i; + } + cout<<"sum="< j) { + System.out.println(count); + return 0; + + } else { + count=count+i; + i++; + f(i,j,count); + + } + + return 0; + } + + + + public static void main(String[] args){ + Scanner sc= new Scanner(System.in); + int inp = sc.nextInt(); + int i = 0; int j=inp; + int count = 0; + f(i,j,count); + + } +} diff --git a/sus.c++ b/sus.c++ new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/sus.c++ @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/swap without third variable b/swap without third variable new file mode 100644 index 00000000..42f6cb8e --- /dev/null +++ b/swap without third variable @@ -0,0 +1,18 @@ +import java.util.*; +class Swap +{ + public static void main(String a[]) + { + System.out.println("Enter the value of x and y"); + Scanner sc = new Scanner(System.in); + /*Define variables*/ + int x = sc.nextInt(); + int y = sc.nextInt(); + System.out.println("before swapping numbers: "+x +" "+ y); + /*Swapping*/ + x = x + y; + y = x - y; + x = x - y; + System.out.println("After swapping: "+x +" " + y); + } +} diff --git a/swapoftwonumber.java b/swapoftwonumber.java new file mode 100644 index 00000000..ff675dec --- /dev/null +++ b/swapoftwonumber.java @@ -0,0 +1,24 @@ +public class SwapNumbers { + + public static void main(String[] args) { + + float first = 1.20f, second = 2.45f; + + System.out.println("--Before swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + + // Value of first is assigned to temporary + float temporary = first; + + // Value of second is assigned to first + first = second; + + // Value of temporary (which contains the initial value of first) is assigned to second + second = temporary; + + System.out.println("--After swap--"); + System.out.println("First number = " + first); + System.out.println("Second number = " + second); + } +} diff --git a/switch.c b/switch.c new file mode 100644 index 00000000..baab601d --- /dev/null +++ b/switch.c @@ -0,0 +1,20 @@ +#include +int main() +{ + int age ; + printf("Enter the age:\n"); + scanf("%d", &age); + switch (age) + { + case 3 : + printf(" your age is 3 "); + break; + + default: + printf("your age is not 3,4, and 23 "); + break; + } + return 0 ; + + +} \ No newline at end of file diff --git a/thissis.java b/thissis.java new file mode 100644 index 00000000..3a65c4f1 --- /dev/null +++ b/thissis.java @@ -0,0 +1,16 @@ +class Main { + public static void main(String[] args) { + + int n = 10, firstTerm = 0, secondTerm = 1; + System.out.println("Fibonacci Series till " + n + " terms:"); + + for (int i = 1; i <= n; ++i) { + System.out.print(firstTerm + ", "); + + // compute the next term + int nextTerm = firstTerm + secondTerm; + firstTerm = secondTerm; + secondTerm = nextTerm; + } + } +} diff --git a/time.java b/time.java new file mode 100644 index 00000000..c8bbe69a --- /dev/null +++ b/time.java @@ -0,0 +1,9 @@ +// Calculate milliseconds in a year +const minute = 1000 * 60; +const hour = minute * 60; +const day = hour * 24; +const year = day * 365; + +// Divide Time with a year +const d = new Date(); +let years = Math.round(d.getTime() / year); \ No newline at end of file diff --git a/towerofhanoi.java b/towerofhanoi.java new file mode 100644 index 00000000..636d3a5e --- /dev/null +++ b/towerofhanoi.java @@ -0,0 +1,26 @@ +import java.util.Scanner; +public class TowersofHanoi { + public static final String SOURCE_PEG = "Source"; + public static final String TARGET_PEG = "Target"; + public static final String SPARE_PEG = "Spare"; + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Please enter number of discs:"); + int numberOfDiscs = scanner.nextInt(); + solveTowersOfHanoi(numberOfDiscs, SOURCE_PEG, TARGET_PEG, SPARE_PEG); + scanner.close(); + } + + + private static void solveTowersOfHanoi(int numberOfDiscs, String sourcePeg, String targetPeg, String sparePeg) { + if (numberOfDiscs == 1) { + System.out.println(sourcePeg + " => " + targetPeg); + } else { + solveTowersOfHanoi(numberOfDiscs - 1, sourcePeg, sparePeg, targetPeg); + System.out.println(sourcePeg + " => " + targetPeg); + solveTowersOfHanoi(numberOfDiscs - 1, sparePeg, targetPeg, sourcePeg); + } + + } +} \ No newline at end of file diff --git a/transpose.java b/transpose.java new file mode 100644 index 00000000..d86ccf1f --- /dev/null +++ b/transpose.java @@ -0,0 +1,31 @@ +public class Transpose { + + public static void main(String[] args) { + int row = 2, column = 3; + int[][] matrix = { {2, 3, 4}, {5, 6, 4} }; + + // Display current matrix + display(matrix); + + // Transpose the matrix + int[][] transpose = new int[column][row]; + for(int i = 0; i < row; i++) { + for (int j = 0; j < column; j++) { + transpose[j][i] = matrix[i][j]; + } + } + + // Display transposed matrix + display(transpose); + } + + public static void display(int[][] matrix) { + System.out.println("The matrix is: "); + for(int[] row : matrix) { + for (int column : row) { + System.out.print(column + " "); + } + System.out.println(); + } + } +} diff --git a/trapping_rainwater.java b/trapping_rainwater.java new file mode 100644 index 00000000..efca76c6 --- /dev/null +++ b/trapping_rainwater.java @@ -0,0 +1,40 @@ +class Test { + static int arr[] + = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + + + static int findWater(int n) + { + + int left[] = new int[n]; + + + int right[] = new int[n]; + + + int water = 0; + + + left[0] = arr[0]; + for (int i = 1; i < n; i++) + left[i] = Math.max(left[i - 1], arr[i]); + + + right[n - 1] = arr[n - 1]; + for (int i = n - 2; i >= 0; i--) + right[i] = Math.max(right[i + 1], arr[i]); + + + for (int i = 0; i < n; i++) + water += Math.min(left[i], right[i]) - arr[i]; + + return water; + } + + + public static void main(String[] args) + { + + System.out.println(findWater(arr.length)); + } +} \ No newline at end of file diff --git a/traversal.py b/traversal.py new file mode 100644 index 00000000..56cac6b8 --- /dev/null +++ b/traversal.py @@ -0,0 +1,27 @@ +class Node: + def __init__(self, dataval=None): + self.dataval = dataval + self.nextval = None + +class SLinkedList: + def __init__(self): + self.headval = None + + def listprint(self): + printval = self.headval + while printval is not None: + print (printval.dataval) + printval = printval.nextval + +list = SLinkedList() +list.headval = Node("Mon") +e2 = Node("Tue") +e3 = Node("Wed") + +# Link first Node to second node +list.headval.nextval = e2 + +# Link second Node to third node +e2.nextval = e3 + +list.listprint() diff --git a/trees in java.java b/trees in java.java new file mode 100644 index 00000000..128a0c6c --- /dev/null +++ b/trees in java.java @@ -0,0 +1,17 @@ +import java.util.*; + +class GFG { + + public static void main(String[] args) + { + Set ts1 = new TreeSet<>(); + + ts1.add("A"); + ts1.add("B"); + ts1.add("C"); + + ts1.add("C"); + + System.out.println(ts1); + } +} diff --git a/triangle.py b/triangle.py new file mode 100644 index 00000000..5ba10fd6 --- /dev/null +++ b/triangle.py @@ -0,0 +1,6 @@ +rows = int(input("Enter number of rows: ")) + +for i in range(rows): + for j in range(i+1): + print(j+1, end=" ") + print("\n") \ No newline at end of file diff --git a/tsp.java b/tsp.java new file mode 100644 index 00000000..619c58c4 --- /dev/null +++ b/tsp.java @@ -0,0 +1,73 @@ +// import required classes and packages +import Java.util.*; +import java.io.*; +import java.util.Scanner; + +// create TSPExample class to implement TSP code in Java +class TSPExample +{ + // create findHamiltonianCycle() method to get minimum weighted cycle + static int findHamiltonianCycle(int[][] distance, boolean[] visitCity, int currPos, int cities, int count, int cost, int hamiltonianCycle) + { + + if (count == cities && distance[currPos][0] > 0) + { + hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]); + return hamiltonianCycle; + } + + // BACKTRACKING STEP + for (int i = 0; i < cities; i++) + { + if (visitCity[i] == false && distance[currPos][i] > 0) + { + + // Mark as visited + visitCity[i] = true; + hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, cities, count + 1, cost + distance[currPos][i], hamiltonianCycle); + + // Mark ith node as unvisited + visitCity[i] = false; + } + } + return hamiltonianCycle; + } + + // main() method start + public static void main(String[] args) + { + int cities; + + //create scanner class object to get input from user + Scanner sc = new Scanner(System.in); + + // get total number of cities from the user + System.out.println("Enter total number of cities "); + cities = sc.nextInt(); + + + //get distance of cities from the user + int distance[][] = new int[cities][cities]; + for( int i = 0; i < cities; i++){ + for( int j = 0; j < cities; j++){ + System.out.println("Distance from city"+ (i+1) +" to city"+ (j+1) +": "); + distance[i][j] = sc.nextInt(); + } + } + + // create an array of type boolean to check if a node has been visited or not + boolean[] visitCity = new boolean[cities]; + + // by default, we make the first city visited + visitCity[0] = true; + + + int hamiltonianCycle = Integer.MAX_VALUE; + + // call findHamiltonianCycle() method that returns the minimum weight Hamiltonian Cycle + hamiltonianCycle = findHamiltonianCycle(distance, visitCity, 0, cities, 1, 0, hamiltonianCycle); + + // print the minimum weighted Hamiltonian Cycle + System.out.println(hamiltonianCycle); + } +} diff --git a/tut12.cpp b/tut12.cpp new file mode 100644 index 00000000..60c3a012 --- /dev/null +++ b/tut12.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +int main(){ + // pointer --> data type which holds the address of other data types. + int a=10; + int*b=&a; + cout<<"the address of a is "< (Address) of Operator + // * --> (Value at) Dereference Operator + + // Pointer to Pointer + int**c=&b; + cout<<"the address of b is "<<&b< +using namespace std; + +typedef struct employee +{ + /*data*/ + int eId; + float salary; + char favChar; + +}ep; + +int main(){ + + ep aditya; + aditya.eId=44; + aditya.salary=30000000; + aditya.favChar='s'; + + cout<<"the value is "< +#include +using namespace std; +void unionofArrays(int arr[],int arr2[], int size, int size1){ + set s; + + + for(int i=0;i::iterator it; + +// print the contents of our set +for (it=s.begin(); it!=s.end(); ++it) + cout << ' ' << *it; +cout << '\n'; + +} +int main(){ + int arr[]={1,2,3,4}; + int arr2[]={3,4,5,6}; + int size=4; + int size1=4; + unionofArrays(arr,arr2,size,size1); + + + return 0; +} diff --git a/user-manual.pdf b/user-manual.pdf new file mode 100644 index 00000000..0d4754fd Binary files /dev/null and b/user-manual.pdf differ diff --git a/value.java b/value.java new file mode 100644 index 00000000..936cbdbb --- /dev/null +++ b/value.java @@ -0,0 +1,13 @@ +public class AsciiValue { + + public static void main(String[] args) { + + char ch = 'a'; + int ascii = ch; + // You can also cast char to int + int castAscii = (int) ch; + + System.out.println("The ASCII value of " + ch + " is: " + ascii); + System.out.println("The ASCII value of " + ch + " is: " + castAscii); + } +} diff --git a/vjgfjgjy.cpp b/vjgfjgjy.cpp new file mode 100644 index 00000000..306c9cc5 --- /dev/null +++ b/vjgfjgjy.cpp @@ -0,0 +1,47 @@ +// Bubble sort in C++ + +#include +using namespace std; + +// perform bubble sort +void bubbleSort(int array[], int size) { + + // loop to access each array element + for (int step = 0; step < size; ++step) { + + // loop to compare array elements + for (int i = 0; i < size - step; ++i) { + + // compare two adjacent elements + // change > to < to sort in descending order + if (array[i] > array[i + 1]) { + + // swapping elements if elements + // are not in the intended order + int temp = array[i]; + array[i] = array[i + 1]; + array[i + 1] = temp; + } + } + } +} + +// print array +void printArray(int array[], int size) { + for (int i = 0; i < size; ++i) { + cout << " " << array[i]; + } + cout << "\n"; +} + +int main() { + int data[] = {-2, 45, 0, 11, -9}; + + // find array's length + int size = sizeof(data) / sizeof(data[0]); + + bubbleSort(data, size); + + cout << "Sorted Array in Ascending Order:\n"; + printArray(data, size); +} diff --git a/water_trap.java b/water_trap.java new file mode 100644 index 00000000..74b917f4 --- /dev/null +++ b/water_trap.java @@ -0,0 +1,35 @@ +public class water_trap { + + static int trap(int[]arr){ + int trapW=0; + + int n=arr.length; + for (int i=0;i=0){ + lm=Math.max(lm,arr[j]); + j--; + } + j=i; + while(j + + WEB DESIGNING + + +

    BLOCK LEVEL

    +

    there are two categories of block level. + block level elements or tags create largest structure then inline elements genrally block level elements may contain inline elements and + other blocks levels elements

    +
    +

    SOME EXAMPLE OF BLOCK LEVEL

    +
      +
    1. heading tag
    2. +
    3. table tag
    4. +
    5. paragraph tag
    6. +
    7. form tag
    8. +
    9. text level
    10. +
    +

    TEXT LEVEL ELEMENTS

    +

    inline elements create smaller srtucture than block level elements genrally inline elements may contain only data + and other inline elements. + inline elements do not begin on new line

    +

    some example of inline elements

    + this tag is in text level +
    + underline tag used in inline tag +
    + italic tag is used in inline tag +
    + small tag is used to small the tha character and it is used in inline tag +
    + big tag is used for big the character and also used in inline tag +
    + a2+b2 +

    this tag is used superscript like a power 2 + b power 2

    +
    + h2o +

    this tag is show subscript command and from above example

    +
    +
    +
    + hello sir + + + \ No newline at end of file diff --git a/webpage.html b/webpage.html new file mode 100644 index 00000000..957aed9a --- /dev/null +++ b/webpage.html @@ -0,0 +1,39 @@ + + + + + + + + PROFILE + + + The image is no longer available
+    +
    +

    NAME : Arpit Gupta

    +

    INSTA I'D : arpitg913

    +

    LINKEDIN I'D : Arpit gupta

    +
    +

    QUALIFICATIONS

    + + + + + + + + + + + + + + + + +
    CLASSBOARDPERCENTAGE
    XU.P. Board76%
    XIIU.P. Board 73%
    + + + \ No newline at end of file diff --git a/ygvcyghcvyhv.cpp b/ygvcyghcvyhv.cpp new file mode 100644 index 00000000..17a4da17 --- /dev/null +++ b/ygvcyghcvyhv.cpp @@ -0,0 +1,25 @@ +// Factorial of n = 1*2*3*...*n + +#include +using namespace std; + +int factorial(int); + +int main() { + int n, result; + + cout << "Enter a non-negative number: "; + cin >> n; + + result = factorial(n); + cout << "Factorial of " << n << " = " << result; + return 0; +} + +int factorial(int n) { + if (n > 1) { + return n * factorial(n - 1); + } else { + return 1; + } +} diff --git a/ytviddownloader.py b/ytviddownloader.py new file mode 100644 index 00000000..beab1a47 --- /dev/null +++ b/ytviddownloader.py @@ -0,0 +1,30 @@ +from tkinter import * +from pytube import YouTube + +window = Tk() +window.geometry("600x700") +window.config(bg="red") +window.title("Youtube Video Downloader by Tharuka") + +youtube_logo = PhotoImage(file="yt.png") +window.iconphoto(False, youtube_logo) + +Label(window, text="Video Downloader", font=("Arial 30 bold"), bg="lightgreen").pack(padx=5, pady=50) + +video_link = StringVar() + +Label(window, text="Enter the Link : ", font=("Arial",25,"bold")).place(x=170, y=150) + +Entry_link = Entry(window, width=50, font=35 , textvariable=video_link, bd=4).place(x=60, y=200) + +def video_download(): + video_url = YouTube(str(video_link.get())) + videos = video_url.streams.first() + videos.download() + + Label(window, text="Download Completed !!!", font=("Arial",35,"bold"),bg="lightpink",fg="Black").place(x=60, y=350) + Label(window, text="Check out Download Folder", font=("Arial", 30, "bold"), bg="yellow").place(x=60, y=400) + +Button(window, text=".DOWNLOAD.", font=("Arial", 25, "bold"), bg="lightblue", command=video_download).place(x=180, y=300) + +window.mainloop()