diff --git a/AES_algo.java b/AES_algo.java new file mode 100644 index 00000000..cb20a56b --- /dev/null +++ b/AES_algo.java @@ -0,0 +1,219 @@ +public class AES { + private static final byte[] sBox = new byte[] { + 0x63, 0x7c, 0x77, 0x7b, -0x0e, 0x6b, 0x6f, -0x3b, 0x30, 0x01, 0x67, 0x2b, -0x02, -0x29, -0x55, 0x76, + -0x36, -0x7e, -0x37, 0x7d, -0x06, 0x59, 0x47, -0x10, -0x53, -0x2c, -0x5e, -0x51, -0x64, -0x5c, 0x72, -0x40, + -0x49, -0x03, -0x6d, 0x26, 0x36, 0x3f, -0x09, -0x34, 0x34, -0x5b, -0x1b, -0x0f, 0x71, -0x28, 0x31, 0x15, + 0x04, -0x39, 0x23, -0x3d, 0x18, -0x6a, 0x05, -0x66, 0x07, 0x12, -0x80, -0x1e, -0x15, 0x27, -0x4e, 0x75, + 0x09, -0x7d, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, -0x60, 0x52, 0x3b, -0x2a, -0x4d, 0x29, -0x1d, 0x2f, -0x7c, + 0x53, -0x2f, 0x00, -0x13, 0x20, -0x04, -0x4f, 0x5b, 0x6a, -0x35, -0x42, 0x39, 0x4a, 0x4c, 0x58, -0x31, + -0x30, -0x11, -0x56, -0x05, 0x43, 0x4d, 0x33, -0x7b, 0x45, -0x07, 0x02, 0x7f, 0x50, 0x3c, -0x61, -0x58, + 0x51, -0x5d, 0x40, -0x71, -0x6e, -0x63, 0x38, -0x0b, -0x44, -0x4a, -0x26, 0x21, 0x10, -0x01, -0x0d, -0x2e, + -0x33, 0x0c, 0x13, -0x14, 0x5f, -0x69, 0x44, 0x17, -0x3c, -0x59, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, -0x7f, 0x4f, -0x24, 0x22, 0x2a, -0x70, -0x78, 0x46, -0x12, -0x48, 0x14, -0x22, 0x5e, 0x0b, -0x25, + -0x20, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, -0x3e, -0x2d, -0x54, 0x62, -0x6f, -0x6b, -0x1c, 0x79, + -0x19, -0x38, 0x37, 0x6d, -0x73, -0x2b, 0x4e, -0x57, 0x6c, 0x56, -0x0c, -0x16, 0x65, 0x7a, -0x52, 0x08, + -0x46, 0x78, 0x25, 0x2e, 0x1c, -0x5a, -0x4c, -0x3a, -0x18, -0x23, 0x74, 0x1f, 0x4b, -0x43, -0x75, -0x76, + 0x70, 0x3e, -0x4b, 0x66, 0x48, 0x03, -0x0a, 0x0e, 0x61, 0x35, 0x57, -0x47, -0x7a, -0x3f, 0x1d, -0x62, + -0x1f, -0x08, -0x68, 0x11, 0x69, -0x27, -0x72, -0x6c, -0x65, 0x1e, -0x79, -0x17, -0x32, 0x55, 0x28, -0x21, + -0x74, -0x5f, -0x77, 0x0d, -0x41, -0x1a, 0x42, 0x68, 0x41, -0x67, 0x2d, 0x0f, -0x50, 0x54, -0x45, 0x16 + }; + private static final int NB = 4; + private static final int NK = 4; + private static final int NR = 10; + + private static final byte[] rCon = new byte[] { + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, -0x80, 0x1b, 0x36 + }; + public byte[] key = new byte[4*NK]; + public byte[][] state = new byte[4][NB]; + public byte[][] keySchedule = new byte[NR+1][NB*4]; + + public AES(String stringKey) { + if (stringKey.length() == NK*8) { + this.key = hexStringToBytes(stringKey); + } + } + private static byte[] hexStringToBytes(String key) { + byte[] bytesKey = new byte[NK * 4]; + for (int i = 0; i < 4 * NK; i++) { + bytesKey[i] = (byte) Integer.parseInt(key.substring(2 * i, 2 * (i + 1)), 16); + } + return bytesKey; + } + public void setKey(String stringKey) { + if (stringKey.length() == NK*8) { + this.key = hexStringToBytes(stringKey); + } + } + /** + * returns string of ciphertext + * @param plainText text to encrypt + * @return ciphertext + */ + public String encrypt(String plainText) { + if (plainText.length() != 8 * NB || key.length != 4 * NK) { + return null; + } + byte[] bytePlainText = hexStringToBytes(plainText); + // place plaintext in state array + for (int r = 0; r < 4; r++) { + for (int c = 0; c < NB; c++) { + state[r][c] = bytePlainText[4 * c + r]; + } + } + keyExpansion(); + addRoundKey(0); // round 0 + for (int round = 1; round < NR; round++) { + subBytes(); + shiftRows(); + mixColumns(); + addRoundKey(round); + } + subBytes(); + shiftRows(); + addRoundKey(10); + return stateToOutput(state); + } + /** + * coverts state array to output string + * @param bytes state array + * @return bytes of state array ordered into a string + */ + private String stateToOutput(byte[][] bytes) { + StringBuilder res = new StringBuilder(); + for (int c = 0; c < NB; c++) { + for (int r = 0; r < 4; r++) { + String sB = Integer.toString(bytes[r][c] & 0xff, 16); + res.append(sB.length() == 1 ? '0' + sB : sB); + } + } + return res.toString(); + } + /** + * XORes the state with the appropriate words from the key schedule + * @param round current round to choose which word to use + */ + public void addRoundKey(int round) { + + for (int r = 0; r < 4; r++) { + for (int c = 0; c < NB; c++) { + state[r][c] ^= keySchedule[round][4 * c + r]; + } + } + } + /** + * creates key schedule for the algorithm from encryption key + */ + public void keyExpansion() { + System.arraycopy(key, 0, keySchedule[0], 0, 4*NK); // copy key into first indices of key schedule + for (int i = NK; i < NB * (NR + 1); i++) { + byte[] previousWord = new byte[4], temp; + System.arraycopy(keySchedule[(i - 1) / NK], 4 * ((i - 1) % NK), previousWord, 0, 4); + if (i % NK == 0) { + temp = subWord(rotateWord(previousWord)); + temp[0] ^= rCon[i / NK - 1]; // xor with the rConstant + } else { + temp = previousWord; + } + // copy the new word into the key schedule + for (int j = 0; j < 4; j++) { + keySchedule[i / NK][4 * (i % 4) + j] = (byte) (keySchedule[i / NK - 1][4 * (i % 4) + j] ^ temp[j]); + } + } + } + /** + * passes word through sBox for keyExpansion + * @param word word to sBox + * @return sBoxed word + */ + private static byte[] subWord(byte[] word) { + byte[] subbedWord = new byte[4]; + for (int i = 0; i < 4; i++) { + subbedWord[i] = sBox[word[i] & 0xff]; + } + return subbedWord; + } + /** + * rotates the word by one byte to the left + * @param word word to rotate + * @return rotate word + */ + public byte[] rotateWord(byte[] word) { + byte[] shiftedWord = new byte[4]; + for (int i = 0; i < 4; i++) { + shiftedWord[i] = word[(i + 1) % 4]; + } + return shiftedWord; + } + /** + * applies mixColumns operation on state array + */ + public void mixColumns() { + for (int c = 0; c < NB; c++) { + byte[] tempColumn = new byte[4]; + // first preform operation on temp array so not to overwrite the original needed values + for (int r = 0; r < 4; r++) { + tempColumn[r] = mixColumnsHelper(r, c); + } + + for (int r = 0; r < 4; r++) { + state[r][c] = tempColumn[r]; + } + } + } + /** + * returns XOR operation needed for mixColumns + * @param r row of byte + * @param c column of byte + * @return new value for byte in state array + */ + public byte mixColumnsHelper(int r, int c) { + return (byte) (multiplyBy02(state[r][c]) + ^ multiplyBy03(state[(r + 1) % 4][c]) + ^ state[(r + 2) % 4][c] + ^ state[(r + 3) % 4][c]); + } + + /** + * preforms multiplication by two in GF(2^8) + * @param val value to multiply with + * @return product + */ + public byte multiplyBy02(byte val) { + return (byte) ((val << 1) ^ ((val & 0x80) == 0x00 ? 0x00 : 0x11b)); + } + + public byte multiplyBy03(byte i) { + // 3 * z = 2 * z + 1 * z + return (byte) (multiplyBy02(i) ^ i); + } + + /** + * applies the shiftRows operation on the state array + */ + public void shiftRows() { + for (int r = 1; r < 4; r++) { + byte[] tempRow = new byte[NB]; + System.arraycopy(state[r], 0, tempRow, 0, NB); + for (int c = 0; c < NB; c++) { + state[r][c] = tempRow[(r + c) % NB]; + } + } + } + + /** + * preforms the sBox operation on the state array + */ + public void subBytes() { + for (int r = 0; r < NB; r++) { + for (int c = 0; c < NB; c++) { + state[r][c] = sBox[state[r][c] & 0xff]; + } + } + } + + public static void main(String[] args) { + AES aes = new AES("2b7e151628aed2a6abf7158809cf4f3c"); + System.out.println("Cipher Text: " + aes.encrypt("3243f6a8885a308d313198a2e0370734")); + } +} \ No newline at end of file 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/Armstrong_Funtion.java b/Armstrong_Funtion.java new file mode 100644 index 00000000..07148f6a --- /dev/null +++ b/Armstrong_Funtion.java @@ -0,0 +1,48 @@ +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"); + } + } +} + + + \ No newline at end of file diff --git a/BinarySearch.java b/BinarySearch.java index eeffdf12..dbc1c117 100644 --- a/BinarySearch.java +++ b/BinarySearch.java @@ -45,7 +45,23 @@ public static void main(String[] args) { * @param number * @return index of given number in array or -1 if not found */ - public static int performBinarySearch(int[] input, int number) { +// 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 -1; +// } + public static int performBinarySearch(int[] input, int number) { int low = 0; int high = input.length - 1; 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/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..81e3ef95 100644 --- a/BubbleSort.java +++ b/BubbleSort.java @@ -1,4 +1,5 @@ public class BubbleSortExample { + //worst case of this code is O(n2). static void bubbleSort(int[] arr) { int n = arr.length; int temp = 0; @@ -13,8 +14,32 @@ static void bubbleSort(int[] arr) { } } + - } + } + // 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}; @@ -32,4 +57,4 @@ public static void main(String[] args) { } } -} \ 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/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 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/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/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 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/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/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/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/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/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/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/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;in2) + { + 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/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/GuessTheNumberGame.java b/GuessTheNumberGame.java new file mode 100644 index 00000000..7b5b3bd0 --- /dev/null +++ b/GuessTheNumberGame.java @@ -0,0 +1,34 @@ +import java.util.*; + +class GuessTheNumberGame +{ + public static void main(String[] args) + { + Scanner sc = new Scanner(System.in); + Random rm = new Random(); + + int cc = rm.nextInt(1,100); + int uc,count=0; + System.out.println("Guess the number : "); + + for(;;) + { + uc = sc.nextInt(); + count++; + + if(uc==cc) + { + System.out.println("You guessed the number in "+count+" turns."); + break; + } + else if(uccc) + { + System.out.println("This number is greater than computer's.\nTry again :"); + } + } + } +} \ No newline at end of file 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; i0) + { + 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/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/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/Linear_Search.java b/Linear_Search.java new file mode 100644 index 00000000..9459795d --- /dev/null +++ b/Linear_Search.java @@ -0,0 +1,23 @@ +public class LinearSearch { + + public static final int unorderedLinearSearch(int value, int[] array) { + for (int i = 0; i < array.length; i++) { + int iValue = array[i]; + if (value == iValue) + return i; + } + return Integer.MAX_VALUE; + } + + public static void main(String[] args) { + int[] integers = {1,2,3,4,5,6,7,8,8,8,9,9,9,0}; + //the element that should be found + int shouldBeFound = 9; + + int atIndex = LinearSearch.unorderedLinearSearch(shouldBeFound, integers); + + System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" + , shouldBeFound, integers[atIndex], atIndex, integers.length)); + + } +} 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/MazeRecursion.java b/MazeRecursion.java new file mode 100644 index 00000000..c52a4e6f --- /dev/null +++ b/MazeRecursion.java @@ -0,0 +1,158 @@ +package com.thealgorithms.backtracking; + +public class MazeRecursion { + + public static void mazeRecursion() { + // First create a 2 dimensions array to mimic a maze map + int[][] map = new int[8][7]; + int[][] map2 = new int[8][7]; + + // We use 1 to indicate wall + // Set the ceiling and floor to 1 + for (int i = 0; i < 7; i++) { + map[0][i] = 1; + map[7][i] = 1; + } + + // Then we set the left and right wall to 1 + for (int i = 0; i < 8; i++) { + map[i][0] = 1; + map[i][6] = 1; + } + + // Now we have created a maze with its wall initialized + + // Here we set the obstacle + map[3][1] = 1; + map[3][2] = 1; + + // Print the current map + System.out.println("The condition of the map: "); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // clone another map for setWay2 method + for (int i = 0; i < map.length; i++) { + for (int j = 0; j < map[i].length; j++) { + map2[i][j] = map[i][j]; + } + } + + // By using recursive backtracking to let your ball(target) find its way in the + // maze + // The first parameter is the map + // Second parameter is x coordinate of your target + // Thrid parameter is the y coordinate of your target + setWay(map, 1, 1); + setWay2(map2, 1, 1); + + // Print out the new map1, with the ball footprint + System.out.println("After the ball goes through the map1,show the current map1 condition"); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map[i][j] + " "); + } + System.out.println(); + } + + // Print out the new map2, with the ball footprint + System.out.println("After the ball goes through the map2,show the current map2 condition"); + for (int i = 0; i < 8; i++) { + for (int j = 0; j < 7; j++) { + System.out.print(map2[i][j] + " "); + } + System.out.println(); + } + } + + + + // Using recursive path finding to help the ball find its way in the maze + // Description: + // 1. map (means the maze) + // 2. i, j (means the initial coordinate of the ball in the maze) + // 3. if the ball can reach the end of maze, that is position of map[6][5], + // means the we have found a path for the ball + // 4. Additional Information: 0 in the map[i][j] means the ball has not gone + // through this position, 1 means the wall, 2 means the path is feasible, 3 + // means the ball has gone through the path but this path is dead end + // 5. We will need strategy for the ball to pass through the maze for example: + // Down -> 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/Method_overloading.java b/Method_overloading.java new file mode 100644 index 00000000..acd8aaa6 --- /dev/null +++ b/Method_overloading.java @@ -0,0 +1,80 @@ + // Java Program for Method overloading +// By using Different Types of Arguments + +// Class 1 +// Helper class +class Helper { + + // Method with 2 integer parameters + static int Multiply(int a, int b) + { + + // Returns product of integer numbers + return a * b; + } + + // Method 2 + // With same name but with 2 double parameters + static double Multiply(double a, double b) + { + + // Returns product of double numbers + return a * b; + } +} + +// Class 2 +// Main class +class basic { + + // Main driver method + public static void main(String[] args) + { + + // Calling method by passing + // input as in arguments + System.out.println(Helper.Multiply(2, 4)); + System.out.println(Helper.Multiply(5.5, 6.3)); + } +} + +// Java program for Method Overloading +// by Using Different Numbers of Arguments + +// Class 1 +// Helper class +class abc { + + // Method 1 + // Multiplication of 2 numbers + static int Multiply(int a, int b) + { + + // Return product + return a * b; + } + + // Method 2 + // // Multiplication of 3 numbers + static int Multiply(int a, int b, int c) + { + + // Return product + return a * b * c; + } +} + +// Class 2 +// Main class +class simple { + + // Main driver method + public static void main(String[] args) + { + + // Calling method by passing + // input as in arguments + System.out.println(abc.Multiply(2, 4)); + System.out.println(abc.Multiply(2, 7, 3)); + } +} 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/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/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/PreorderTraversal.java b/PreorderTraversal.java new file mode 100644 index 00000000..08dc5187 --- /dev/null +++ b/PreorderTraversal.java @@ -0,0 +1,55 @@ + +class Node { + int key; + Node left, right; + + public Node(int item) + { + key = item; + left = right = null; + } +} + +class BinaryTree { + + Node root; + + BinaryTree() { + root = null; + } + + + void printInorder(Node node) + { + if (node == null) + return; + + + printInorder(node.left); + + System.out.print(node.key + " "); + + + printInorder(node.right); + } + + + void printInorder() { + printInorder(root); + } + + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + + + System.out.println("\nInorder traversal of binary tree is "); + tree.printInorder(); + } +} diff --git a/Program to Check whether Person is eligible to vote or Not.java b/Program to Check whether Person is eligible to vote or Not.java new file mode 100644 index 00000000..f6d76deb --- /dev/null +++ b/Program to Check whether Person is eligible to vote or Not.java @@ -0,0 +1,20 @@ +import java.util.*; +class Voting +{ + public static void main(String args[]) + { + Scanner sc = new Scanner(System.in); + System.out.println("Enter your Name: "); + String name=sc.nextLine(); + System.out.println("Enter your age: "); + int age=sc.nextInt(); + if((age>=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/QuickSort.java b/QuickSort.java new file mode 100644 index 00000000..a3f4850f --- /dev/null +++ b/QuickSort.java @@ -0,0 +1,89 @@ +// Java implementation of QuickSort +import java.io.*; + +class GFG { + + // A utility function to swap two elements + static void swap(int[] arr, int i, int j) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + /* This function takes last element as pivot, places + the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) + to left of pivot and all greater elements to right + of pivot */ + static int partition(int[] arr, int low, int high) + { + + // pivot + int pivot = arr[high]; + + // Index of smaller element and + // indicates the right position + // of pivot found so far + int i = (low - 1); + + for (int j = low; j <= high - 1; j++) { + + // If current element is smaller + // than the pivot + if (arr[j] < pivot) { + + // Increment index of + // smaller element + i++; + swap(arr, i, j); + } + } + swap(arr, i + 1, high); + return (i + 1); + } + + /* The main function that implements QuickSort + arr[] --> 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/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/Reverse a Number using a while loop.java b/Reverse a Number using a while loop.java new file mode 100644 index 00000000..a4435125 --- /dev/null +++ b/Reverse a Number using a while loop.java @@ -0,0 +1,21 @@ +class Main { + public static void main(String[] args) { + + int num = 1234, reversed = 0; + + System.out.println("Original Number: " + num); + + // run loop until num becomes 0 + while(num != 0) { + + // get last digit from num + int digit = num % 10; + reversed = reversed * 10 + digit; + + // remove the last digit from num + num /= 10; + } + + System.out.println("Reversed Number: " + reversed); + } +} diff --git a/Reverse-words-in-string.java b/Reverse-words-in-string.java new file mode 100644 index 00000000..840625a8 --- /dev/null +++ b/Reverse-words-in-string.java @@ -0,0 +1,18 @@ +class Solution { + public String reverseWords(String s) { + String resp = ""; + List 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/RockPaperScissors.java b/RockPaperScissors.java new file mode 100644 index 00000000..a850b443 --- /dev/null +++ b/RockPaperScissors.java @@ -0,0 +1,65 @@ +import java.util.*; + +class RockPaperScissors +{ + public static void print(int cc) + { + if(cc==1) + { + System.out.println("Computer choice is Rock"); + } + else if(cc==2) + { + System.out.println("Computer choice is Scissors"); + } + else if(cc==3) + { + System.out.println("Computer choice is Paper"); + } + } + + public static boolean check(int uc1) + { + boolean flag; + if(uc1 == 1 || uc1==2 || uc1==3) + { + flag=true; + } + else + { + flag=false; + } + return flag; + } + public static void main(String[] args) + { + System.out.println("Choose :\n1 for Rock\n2 for Scissors\n3 for Paper"); + Random rm = new Random(); + Scanner sc = new Scanner(System.in); + int uc = sc.nextInt(); + boolean flag1 = check(uc); + + if(!flag1) + { + System.out.println("Enter Right Choice"); + } + else + { + int cc = rm.nextInt(1,4); + print(cc); + + if(cc==uc) + { + System.out.println("It's a draw"); + } + else if((cc==2 && uc==1) || (cc==3 && uc==2) || (uc==3 && cc==1)) + { + System.out.println("You won"); + } + else + { + System.out.println("Computer won"); + } + } + } +} \ No newline at end of file diff --git a/Rock_Paper_Scissors.java b/Rock_Paper_Scissors.java new file mode 100644 index 00000000..32cca74c --- /dev/null +++ b/Rock_Paper_Scissors.java @@ -0,0 +1,64 @@ +import java.util.*; + +public class Game +{ + + public static final String ROCK = "ROCK"; + public static final String PAPER = "PAPER"; + public static final String SCISSORS = "SCISSORS"; + + public static void main(String args[]) + { + System.out.println("Enter any one of the following inputs: "); + System.out.println("ROCK"); + System.out.println("PAPER"); + System.out.println("SCISSORS"); + System.out.println(); + + String playerMove = getPlayerMove(); + String computerMove = getComputerMove(); + + + if (playerMove.equals(computerMove)) + System.out.println("Game is Tie !!"); + // if playerMove is ROCK + else if (playerMove.equals(Game.ROCK)) + System.out.println(computerMove.equals(Game.PAPER) ? "Computer Wins": "Player wins"); + // if playerMove is PAPER + else if (playerMove.equals(Game.PAPER)) + System.out.println(computerMove.equals(Game.SCISSORS) ? "Computer Wins": "Player wins"); + // if playerMove is SCISSORS + else + System.out.println(computerMove.equals(Game.ROCK) ? "Computer Wins": "Player wins"); + } + + /* Get Computer's move using Random + class nextInt() method */ + public static String getComputerMove() + { + String computermove; + Random random = new Random(); + int input = random.nextInt(3)+1; + if (input == 1) + computermove = Game.ROCK; + else if(input == 2) + computermove = Game.PAPER; + else + computermove = Game.SCISSORS; + + System.out.println("Computer move is: " + computermove); + System.out.println(); + return computermove; + } + + /* Get Player's move using Scanner + class */ + public static String getPlayerMove() + { + Scanner in = new Scanner(System.in); + String input = in.next(); + String playermove = input.toUpperCase(); + System.out.println("Player move is: "+ playermove); + return playermove; + } +} 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/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/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;is=new ArrayList<>(); + for(int i=0;i<9;i++){ + for(int j=0;j<9;j++){ + if(board[i][j]!='.'){ + char a=board[i][j]; + String s1="r"+i+a; + String s2="c"+j+a; + String s3="b"+(i/3)+"-"+(j/3)+a; + if(s.contains(s1)||s.contains(s2)||s.contains(s3)) + return false; + s.add(s1); + s.add(s2); + s.add(s3); + }} + } + return true; + } +} \ No newline at end of file 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 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/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/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 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/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/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/_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/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/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/binary_search.java b/binary_search.java new file mode 100644 index 00000000..421f93b9 --- /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)/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/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..a688ae98 100644 --- a/bubblesort.java +++ b/bubblesort.java @@ -1,35 +1,50 @@ -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] + " "); - } - - } -} +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); + } +} \ No newline at end of file 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/calculator.java b/calculator.java new file mode 100644 index 00000000..8f81a7bb --- /dev/null +++ b/calculator.java @@ -0,0 +1,56 @@ +import java.util.Scanner; + +class Main { + public static void main(String[] args) { + + char operator; + Double number1, number2, result; + + // create an object of Scanner class + Scanner input = new Scanner(System.in); + + // ask users to enter operator + System.out.println("Choose an operator: +, -, *, or /"); + operator = input.next().charAt(0); + + // ask users to enter numbers + System.out.println("Enter first number"); + number1 = input.nextDouble(); + + System.out.println("Enter second number"); + number2 = input.nextDouble(); + + switch (operator) { + + // performs addition between numbers + case '+': + result = number1 + number2; + System.out.println(number1 + " + " + number2 + " = " + result); + break; + + // performs subtraction between numbers + case '-': + result = number1 - number2; + System.out.println(number1 + " - " + number2 + " = " + result); + break; + + // performs multiplication between numbers + case '*': + result = number1 * number2; + System.out.println(number1 + " * " + number2 + " = " + result); + break; + + // performs division between numbers + case '/': + result = number1 / number2; + System.out.println(number1 + " / " + number2 + " = " + result); + break; + + default: + System.out.println("Invalid operator!"); + break; + } + + input.close(); + } +} \ No newline at end of file diff --git a/ceilingNum.java b/ceilingNum.java new file mode 100644 index 00000000..ca365cc6 --- /dev/null +++ b/ceilingNum.java @@ -0,0 +1,37 @@ +public class CeilingNum { + public static void main(String[] args) { + int[] arr={2,3,5,9,14,16,18}; + int num = 5; + int ans=Ceilingnum(arr,num); + System.out.println(ans); + } + + public static int Ceilingnum(int arr[],int target) + { + if(target>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/countSort.java b/countSort.java new file mode 100644 index 00000000..332a4bb9 --- /dev/null +++ b/countSort.java @@ -0,0 +1,23 @@ +public class countSort { + public static void main(String[] args) { + int[] arr = {5,4,3,3,2,1}; //created array + int k = 5; + int n = arr.length; + int[] countArr = new int[k+1]; + for(int i=1;i<=k;i++) countArr[i] = 0; + + for(int i=0;i +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/fibonacci.java b/fibonacci.java new file mode 100644 index 00000000..0429d398 --- /dev/null +++ b/fibonacci.java @@ -0,0 +1,17 @@ +class FibonacciExample2{ + static int n1=0,n2=1,n3=0; + static void printFibonacci(int count){ + if(count>0){ + n3 = n1 + n2; + n1 = n2; + n2 = n3; + System.out.print(" "+n3); + printFibonacci(count-1); + } + } + public static void main(String args[]){ + int count=10; + System.out.print(n1+" "+n2);//printing 0 and 1 + printFibonacci(count-2);//n-2 because 2 numbers are already printed + } +} \ No newline at end of file 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/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/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/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=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/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/javasubstring.java b/javasubstring.java new file mode 100644 index 00000000..68bac97a --- /dev/null +++ b/javasubstring.java @@ -0,0 +1,17 @@ +package day3; + +import java.util.*; + +class javasubstring { + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.println("Enter any String value = "); + String S = in.nextLine(); + System.out.println("Enter the start point = "); + int start = in.nextInt(); + System.out.println("Enter the end point = "); + int end = in.nextInt(); + System.out.println(S.substring(start, end)); + } +} diff --git a/jobSequencing.java b/jobSequencing.java new file mode 100644 index 00000000..b0b36fdb --- /dev/null +++ b/jobSequencing.java @@ -0,0 +1,130 @@ +// This is Job Sequencing Problem using Greedy Method + +import java.util.*; + +public class jobSequencing +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter the number of Jobs"); + int n=sc.nextInt(); + String a[]=new String[n]; + int b[]=new int[n]; + int c[]=new int[n]; + for(int i=0;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/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/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/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/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/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/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/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;k0){ + r=n%10; //getting remainder + sum=(sum*10)+r; + n=n/10; + } + if(temp==sum) + System.out.println("palindrome number "); + else + System.out.println("not palindrome"); +} +} \ No newline at end of file diff --git a/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/primenumber.java b/primenumber.java new file mode 100644 index 00000000..356b6057 --- /dev/null +++ b/primenumber.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 +} +} \ No newline at end of file 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/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/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/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/reverseLinkedList.py b/reverseLinkedList.py new file mode 100644 index 00000000..3ed5f558 --- /dev/null +++ b/reverseLinkedList.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> 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/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/romanToInt.java b/romanToInt.java new file mode 100644 index 00000000..0ad7d798 --- /dev/null +++ b/romanToInt.java @@ -0,0 +1,51 @@ +import java.util.Scanner; + +class Solution { + public int romanToInt(String s) { + int res = 0; + for (int i = 0; i < s.length(); i++) { + int s1 = value(s.charAt(i)); + if (i + 1 < s.length()) { + int s2 = value(s.charAt(i + 1)); + if (s1 >= 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/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/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/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/snake.java b/snake.java new file mode 100644 index 00000000..f7dfd8fa --- /dev/null +++ b/snake.java @@ -0,0 +1,33 @@ +package com.zetcode; + +import java.awt.EventQueue; +import javax.swing.JFrame; + +public class Snake extends JFrame { + + public Snake() { + + initUI(); + } + + private void initUI() { + + add(new Board()); + + setResizable(false); + pack(); + + setTitle("Snake"); + setLocationRelativeTo(null); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + + + public static void main(String[] args) { + + EventQueue.invokeLater(() -> { + JFrame ex = new Snake(); + ex.setVisible(true); + }); + } +} \ No newline at end of file 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/stringpalindrome.java b/stringpalindrome.java new file mode 100644 index 00000000..e756f966 --- /dev/null +++ b/stringpalindrome.java @@ -0,0 +1,71 @@ +/*package whatever //do not write package name here */ + + + +import java.io.*; + + + +class GFG { + + public static boolean isPalindrome(String str) + + { + + // Initializing an empty string to store the reverse + + // of the original str + + String rev = ""; + + + + // Initializing a new boolean variable for the + + // answer + + boolean ans = false; + + + + for (int i = str.length() - 1; i >= 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/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;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/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/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()