title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Program to find maximum number of boxes we can fit inside another boxes in python
Suppose we have a list of boxes where each row represents the height and width of given boxes. We can put a box in another box if first box is smaller than the second one (when both of its width and height are smaller than the other box), we have to find the maximum number of boxes we can fit into a box. So, if the input is like then the output will be 3, as we can fit the box [6, 6] inside [10, 10] which we can be put into [12, 12] box. To solve this, we will follow these steps − Define a function insert_index() . This will take arr, this_h l := 0 r := size of arr - 1 res := 0 while l <= r, dom := l +(r - l) // 2cur_h := arr[m]if cur_h < this_h is non-zero, thenres := ml := m + 1otherwise,r := m - 1 m := l +(r - l) // 2 cur_h := arr[m] if cur_h < this_h is non-zero, thenres := ml := m + 1 res := m l := m + 1 otherwise,r := m - 1 r := m - 1 return res + 1 From the main method, do the following: sort the matrix based on width, if widths are same sort them based on height n := number of items in matrix heights := a list of size (n + 1) and fill it with inf heights[0] := -inf res := 0 for each box in matrix, do[cur_w, cur_h] := boxindex := insert_index(heights, cur_h)if heights[index] >= cur_h, thenheights[index] := cur_hres := maximum of res and index [cur_w, cur_h] := box index := insert_index(heights, cur_h) if heights[index] >= cur_h, thenheights[index] := cur_h heights[index] := cur_h res := maximum of res and index return res Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, matrix): matrix = sorted(matrix, key=lambda x: (x[0], -x[1])) n = len(matrix) heights = [float("inf")] * (n + 1) heights[0] = float("-inf") res = 0 for box in matrix: cur_w, cur_h = box index = self.insert_index(heights, cur_h) if heights[index] >= cur_h: heights[index] = cur_h res = max(res, index) return res def insert_index(self, arr, this_h): l = 0 r = len(arr) - 1 res = 0 while l <= r: m = l + (r - l) // 2 cur_h = arr[m] if cur_h < this_h: res = m l = m + 1 else: r = m - 1 return res + 1 ob = Solution() matrix = [ [12, 12], [10, 10], [6, 6], [5, 10] ] print(ob.solve(matrix)) matrix = [ [12, 12], [10, 10], [6, 6], [5, 10] ] 3
[ { "code": null, "e": 1368, "s": 1062, "text": "Suppose we have a list of boxes where each row represents the height and width of given boxes. We can put a box in another box if first box is smaller than the second one (when both of its width and height are smaller than the other box), we have to find the maximum number of boxes we can fit into a box." }, { "code": null, "e": 1393, "s": 1368, "text": "So, if the input is like" }, { "code": null, "e": 1504, "s": 1393, "text": "then the output will be 3, as we can fit the box [6, 6] inside [10, 10] which we can be put into [12, 12] box." }, { "code": null, "e": 1548, "s": 1504, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1610, "s": 1548, "text": "Define a function insert_index() . This will take arr, this_h" }, { "code": null, "e": 1617, "s": 1610, "text": "l := 0" }, { "code": null, "e": 1638, "s": 1617, "text": "r := size of arr - 1" }, { "code": null, "e": 1647, "s": 1638, "text": "res := 0" }, { "code": null, "e": 1772, "s": 1647, "text": "while l <= r, dom := l +(r - l) // 2cur_h := arr[m]if cur_h < this_h is non-zero, thenres := ml := m + 1otherwise,r := m - 1" }, { "code": null, "e": 1793, "s": 1772, "text": "m := l +(r - l) // 2" }, { "code": null, "e": 1809, "s": 1793, "text": "cur_h := arr[m]" }, { "code": null, "e": 1863, "s": 1809, "text": "if cur_h < this_h is non-zero, thenres := ml := m + 1" }, { "code": null, "e": 1872, "s": 1863, "text": "res := m" }, { "code": null, "e": 1883, "s": 1872, "text": "l := m + 1" }, { "code": null, "e": 1904, "s": 1883, "text": "otherwise,r := m - 1" }, { "code": null, "e": 1915, "s": 1904, "text": "r := m - 1" }, { "code": null, "e": 1930, "s": 1915, "text": "return res + 1" }, { "code": null, "e": 1970, "s": 1930, "text": "From the main method, do the following:" }, { "code": null, "e": 2047, "s": 1970, "text": "sort the matrix based on width, if widths are same sort them based on height" }, { "code": null, "e": 2078, "s": 2047, "text": "n := number of items in matrix" }, { "code": null, "e": 2133, "s": 2078, "text": "heights := a list of size (n + 1) and fill it with inf" }, { "code": null, "e": 2152, "s": 2133, "text": "heights[0] := -inf" }, { "code": null, "e": 2161, "s": 2152, "text": "res := 0" }, { "code": null, "e": 2332, "s": 2161, "text": "for each box in matrix, do[cur_w, cur_h] := boxindex := insert_index(heights, cur_h)if heights[index] >= cur_h, thenheights[index] := cur_hres := maximum of res and index" }, { "code": null, "e": 2354, "s": 2332, "text": "[cur_w, cur_h] := box" }, { "code": null, "e": 2392, "s": 2354, "text": "index := insert_index(heights, cur_h)" }, { "code": null, "e": 2448, "s": 2392, "text": "if heights[index] >= cur_h, thenheights[index] := cur_h" }, { "code": null, "e": 2472, "s": 2448, "text": "heights[index] := cur_h" }, { "code": null, "e": 2504, "s": 2472, "text": "res := maximum of res and index" }, { "code": null, "e": 2515, "s": 2504, "text": "return res" }, { "code": null, "e": 2585, "s": 2515, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2595, "s": 2585, "text": "Live Demo" }, { "code": null, "e": 3429, "s": 2595, "text": "class Solution:\n def solve(self, matrix):\n matrix = sorted(matrix, key=lambda x: (x[0], -x[1]))\n n = len(matrix)\n\n heights = [float(\"inf\")] * (n + 1)\n heights[0] = float(\"-inf\")\n res = 0\n\n for box in matrix:\n cur_w, cur_h = box\n index = self.insert_index(heights, cur_h)\n\n if heights[index] >= cur_h:\n heights[index] = cur_h\n res = max(res, index)\n return res\n\n def insert_index(self, arr, this_h):\n l = 0\n r = len(arr) - 1\n res = 0\n while l <= r:\n m = l + (r - l) // 2\n cur_h = arr[m]\n if cur_h < this_h:\n res = m\n l = m + 1\n else:\n r = m - 1\n return res + 1\n\nob = Solution()\nmatrix = [\n [12, 12],\n [10, 10],\n [6, 6],\n [5, 10]\n]\nprint(ob.solve(matrix))" }, { "code": null, "e": 3486, "s": 3429, "text": "matrix = [ \n[12, 12], \n[10, 10], \n[6, 6], \n[5, 10] ]" }, { "code": null, "e": 3488, "s": 3486, "text": "3" } ]
JavaScript Array find() function
The find() method of JavaScript is used to return the first elements value in an array, if the condition is passed, otherwise the return value is undefined. The syntax is as follows − array.find(function(val, index, arr),thisValue) Here, function is a function with val, which is the value of the current element. The index is the array index, and arr is the array. The this value parameter is the value to be passed to the function. Live Demo <!DOCTYPE html> <html> <body> <h2>Ranking Points</h2> <p>Get the points (first element) above 400...</p> <button onclick="display()">Result</button> <p id="demo"></p> <script> var pointsArr = [50, 100, 200, 300, 400, 500, 600]; function pointsFunc(points) { return points > 400; } function display() { document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc); } </script> </body> </html> Now, click on the “Result” button − Let us see another example, wherein the result would be undefined − Live Demo <!DOCTYPE html> <html> <body> <h2>Ranking Points</h2> <p>Get the points (first element) above 400...</p> <button onclick="display()">Result</button> <p id="demo"></p> <script> var pointsArr = [50, 100, 200, 300, 400]; function pointsFunc(points) { return points > 400; } function display() { document.getElementById("demo").innerHTML = pointsArr.find(pointsFunc); } </script> </body> </html> Now, click on the “Result” button −
[ { "code": null, "e": 1246, "s": 1062, "text": "The find() method of JavaScript is used to return the first elements value in an array, if the condition is passed, otherwise the return value is undefined. The syntax is as follows −" }, { "code": null, "e": 1294, "s": 1246, "text": "array.find(function(val, index, arr),thisValue)" }, { "code": null, "e": 1496, "s": 1294, "text": "Here, function is a function with val, which is the value of the current element. The index is the array index, and arr is the array. The this value parameter is the value to be passed to the function." }, { "code": null, "e": 1507, "s": 1496, "text": " Live Demo" }, { "code": null, "e": 1975, "s": 1507, "text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Ranking Points</h2>\n <p>Get the points (first element) above 400...</p>\n <button onclick=\"display()\">Result</button>\n <p id=\"demo\"></p>\n <script>\n var pointsArr = [50, 100, 200, 300, 400, 500, 600];\n function pointsFunc(points) {\n return points > 400;\n }\n function display() {\n document.getElementById(\"demo\").innerHTML = pointsArr.find(pointsFunc);\n }\n </script>\n</body>\n</html>" }, { "code": null, "e": 2011, "s": 1975, "text": "Now, click on the “Result” button −" }, { "code": null, "e": 2079, "s": 2011, "text": "Let us see another example, wherein the result would be undefined −" }, { "code": null, "e": 2090, "s": 2079, "text": " Live Demo" }, { "code": null, "e": 2548, "s": 2090, "text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Ranking Points</h2>\n <p>Get the points (first element) above 400...</p>\n <button onclick=\"display()\">Result</button>\n <p id=\"demo\"></p>\n <script>\n var pointsArr = [50, 100, 200, 300, 400];\n function pointsFunc(points) {\n return points > 400;\n }\n function display() {\n document.getElementById(\"demo\").innerHTML = pointsArr.find(pointsFunc);\n }\n </script>\n</body>\n</html>" }, { "code": null, "e": 2584, "s": 2548, "text": "Now, click on the “Result” button −" } ]
Find the minimum number of steps to reach M from N in C++
Suppose we have two integers N and M. We have to find minimum number of steps to reach M from N, by performing given operations − Multiply the number x by 2, so x will be 2*x Subtract one from the number x, so the number will be x – 1 If N = 4 and M = 6, then output will be 2. So if we perform operation number 2 on N, then N becomes 3, then perform operation number one on updated value of N, so it becomes 2 * 3 = 6. So the minimum number of steps will be 2. To solve this problem, we will follow these rules − We can reverse the problem, like we take the number N starting from M, so new two operations will be Divide the number by 2, when it is even,add 1 with the number Divide the number by 2, when it is even, add 1 with the number Now the minimum number of operations will beif N > M, return the difference between them, so number of steps will be adding 1 to M, until it becomes equal to NOtherwise when N < M, keep dividing M by 2, until it becomes less than N. If M is odd, then add 1 to it first, then divide by 2, Once M is less than N, add the difference between them to the count along with the count of above operations. if N > M, return the difference between them, so number of steps will be adding 1 to M, until it becomes equal to N Otherwise when N < M, keep dividing M by 2, until it becomes less than N. If M is odd, then add 1 to it first, then divide by 2, Once M is less than N, add the difference between them to the count along with the count of above operations. Live Demo #include<iostream> using namespace std; int countMinimumSteps(int n, int m) { int count = 0; while(m > n) { if(m % 2 == 1) { m++; count++; } m /= 2; count++; } return count + n - m; } int main() { int n = 4, m = 6; cout << "Minimum number of operations required: " << countMinimumSteps(n, m); } Minimum number of operations required: 2
[ { "code": null, "e": 1192, "s": 1062, "text": "Suppose we have two integers N and M. We have to find minimum number of steps to reach M from N, by performing given operations −" }, { "code": null, "e": 1237, "s": 1192, "text": "Multiply the number x by 2, so x will be 2*x" }, { "code": null, "e": 1297, "s": 1237, "text": "Subtract one from the number x, so the number will be x – 1" }, { "code": null, "e": 1524, "s": 1297, "text": "If N = 4 and M = 6, then output will be 2. So if we perform operation number 2 on N, then N becomes 3, then perform operation number one on updated value of N, so it becomes 2 * 3 = 6. So the minimum number of steps will be 2." }, { "code": null, "e": 1576, "s": 1524, "text": "To solve this problem, we will follow these rules −" }, { "code": null, "e": 1677, "s": 1576, "text": "We can reverse the problem, like we take the number N starting from M, so new two operations will be" }, { "code": null, "e": 1739, "s": 1677, "text": "Divide the number by 2, when it is even,add 1 with the number" }, { "code": null, "e": 1780, "s": 1739, "text": "Divide the number by 2, when it is even," }, { "code": null, "e": 1802, "s": 1780, "text": "add 1 with the number" }, { "code": null, "e": 2200, "s": 1802, "text": "Now the minimum number of operations will beif N > M, return the difference between them, so number of steps will be adding 1 to M, until it becomes equal to NOtherwise when N < M, keep dividing M by 2, until it becomes less than N. If M is odd, then add 1 to it first, then divide by 2, Once M is less than N, add the difference between them to the count along with the count of above operations." }, { "code": null, "e": 2316, "s": 2200, "text": "if N > M, return the difference between them, so number of steps will be adding 1 to M, until it becomes equal to N" }, { "code": null, "e": 2555, "s": 2316, "text": "Otherwise when N < M, keep dividing M by 2, until it becomes less than N. If M is odd, then add 1 to it first, then divide by 2, Once M is less than N, add the difference between them to the count along with the count of above operations." }, { "code": null, "e": 2566, "s": 2555, "text": " Live Demo" }, { "code": null, "e": 2921, "s": 2566, "text": "#include<iostream>\nusing namespace std;\nint countMinimumSteps(int n, int m) {\n int count = 0;\n while(m > n) {\n if(m % 2 == 1) {\n m++;\n count++;\n }\n m /= 2;\n count++;\n }\n return count + n - m;\n}\nint main() {\n int n = 4, m = 6;\n cout << \"Minimum number of operations required: \" << countMinimumSteps(n, m);\n}" }, { "code": null, "e": 2962, "s": 2921, "text": "Minimum number of operations required: 2" } ]
Find all Autobiographical Numbers with given number of digits - GeeksforGeeks
24 Nov, 2021 Given N as the number of digits, the task is to find all the Autobiographical Numbers whose length is equal to N. An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. Examples: Input: N = 4 Output: 1210, 2020Input: N = 5 Output: 21200 Approach: Any number with N-digits lies in the range [10(n-1), 10n-1]. So, each number in this range is iterated and checked if it is an Autobiographical number or not. Convert the number to a stringiterate through each digit and store it in a variable.Then run an inner loop, compare the iterator of the outer loop with each digit of the inner loop and if they are equal then increment the occurrence count of the digit.Then check for equality between occurrence count and the variable in which each digit is stored so that we can know if the current number is autobiographical or not. Convert the number to a string iterate through each digit and store it in a variable. Then run an inner loop, compare the iterator of the outer loop with each digit of the inner loop and if they are equal then increment the occurrence count of the digit. Then check for equality between occurrence count and the variable in which each digit is stored so that we can know if the current number is autobiographical or not. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation to find// Autobiographical numbers with length N #include <bits/stdc++.h>using namespace std; // Function to return if the// number is autobiographical or notbool isAutoBio(int num){ string autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = to_string(num); for (int i = 0; i < autoStr.size(); i++) { // Extracting each character // from each index one by one // and converting into an integer index = autoStr.at(i) - '0'; // Initialise count as 0 cnt = 0; for (j = 0; j < autoStr.size(); j++) { number = autoStr.at(j) - '0'; // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (index != cnt) return false; } return true;} // Function to print autobiographical number// with given number of digitsvoid findAutoBios(int n){ int high, low, i, flag = 0; // Left boundary of interval low = pow(10, n - 1); // Right boundary of interval high = pow(10, n) - 1; for (i = low; i <= high; i++) { if (isAutoBio(i)) { flag = 1; cout << i << ", "; } } // Flag = 0 implies that the number // is not an autobiographical no. if (!flag) cout << "There is no " << "Autobiographical number" << " with " << n << " digits\n";} // Driver Codeint main(){ int N = 0; findAutoBios(N); N = 4; findAutoBios(N); return 0;} // Java implementation to find// Autobiographical numbers with length N import java.util.*;import java.lang.Math; public class autobio { public static boolean isAutoBio(int num) { String autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = Integer.toString(num); for (i = 0; i < autoStr.length(); i++) { // Extracting each character // from each index one by one // and converting into an integer index = Integer.parseInt(autoStr.charAt(i) + ""); // initialize count as 0 cnt = 0; for (j = 0; j < autoStr.length(); j++) { number = Integer.parseInt(autoStr.charAt(j) + ""); // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (cnt != index) return false; } return true; } // Function to print autobiographical number // with given number of digits public static void findAutoBios(double n) { // both the boundaries are taken double, so as // to satisfy Math.pow() function's signature double high, low; int i, flag = 0; // Left boundary of interval low = Math.pow(10.0, n - 1); // Right boundary of interval high = Math.pow(10.0, n) - 1.0; for (i = (int)low; i <= (int)high; i++) if (isAutoBio(i)) { flag = 1; System.out.print(i + ", "); } // Flag = 0 implies that the number // is not an autobiographical no. if (flag == 0) System.out.println("There is no Autobiographical Number" + "with " + (int)n + " digits"); } // Driver Code public static void main(String[] args) { double N = 0; findAutoBios(N); N = 4; findAutoBios(N); }} # Python implementation to find# Autobiographical numbers with length N from math import pow # Function to return if the# number is autobiographical or notdef isAutoBio(num): # Converting the integer # number to string autoStr = str(num) for i in range(0, len(autoStr)): # Extracting each character # from each index one by one # and converting into an integer index = int(autoStr[i]) # Initialize count as 0 cnt = 0 for j in range(0, len(autoStr)): number = int(autoStr[j]) # Check if it is equal to the # index i if true then # increment the count if number == i: # It is an # Autobiographical # number cnt += 1 # Return false if the count and # the index number are not equal if cnt != index: return False return True # Function to print autobiographical number# with given number of digitsdef findAutoBios(n): # Left boundary of interval low = int(pow(10, n-1)) # Right boundary of interval high = int(pow(10, n) - 1) flag = 0 for i in range(low, high + 1): if isAutoBio(i): flag = 1 print(i, end =', ') # Flag = 0 implies that the number # is not an autobiographical no. if flag == 0: print("There is no Autobiographical Number with "+ str(n) + " digits") # Driver Codeif __name__ == "__main__": N = 0 findAutoBios(N) N = 4 findAutoBios(N) // C# implementation to find// Autobiographical numbers with length Nusing System; class autobio { public static bool isAutoBio(int num) { String autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = num.ToString(); for (i = 0; i < autoStr.Length; i++) { // Extracting each character // from each index one by one // and converting into an integer index = Int32.Parse(autoStr[i] + ""); // initialize count as 0 cnt = 0; for (j = 0; j < autoStr.Length; j++) { number = Int32.Parse(autoStr[j] + ""); // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (cnt != index) return false; } return true; } // Function to print autobiographical number // with given number of digits public static void findAutoBios(double n) { // both the boundaries are taken double, so as // to satisfy Math.Pow() function's signature double high, low; int i, flag = 0; // Left boundary of interval low = Math.Pow(10.0, n - 1); // Right boundary of interval high = Math.Pow(10.0, n) - 1.0; for (i = (int)low; i <= (int)high; i++) if (isAutoBio(i)) { flag = 1; Console.Write(i + ", "); } // Flag = 0 implies that the number // is not an autobiographical no. if (flag == 0) Console.WriteLine("There is no Autobiographical Number" + "with " + (int)n + " digits"); } // Driver Code public static void Main(String[] args) { double N = 0; findAutoBios(N); N = 4; findAutoBios(N); }} // This code is contributed by sapnasingh4991 There is no Autobiographical number with 0 digits 1210, 2020 Time Complexity: O(10n – 10n-1) Auxiliary Space: O(1) saikiranjagini sapnasingh4991 souravmahato348 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Operators in C / C++ Euclidean algorithms (Basic and Extended) The Knight's tour problem | Backtracking-1 Efficient program to print all prime factors of a given number Find minimum number of coins that make a given value
[ { "code": null, "e": 24574, "s": 24546, "text": "\n24 Nov, 2021" }, { "code": null, "e": 24690, "s": 24574, "text": "Given N as the number of digits, the task is to find all the Autobiographical Numbers whose length is equal to N. " }, { "code": null, "e": 24920, "s": 24690, "text": "An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. " }, { "code": null, "e": 24932, "s": 24920, "text": "Examples: " }, { "code": null, "e": 24992, "s": 24932, "text": "Input: N = 4 Output: 1210, 2020Input: N = 5 Output: 21200 " }, { "code": null, "e": 25165, "s": 24994, "text": "Approach: Any number with N-digits lies in the range [10(n-1), 10n-1]. So, each number in this range is iterated and checked if it is an Autobiographical number or not. " }, { "code": null, "e": 25583, "s": 25165, "text": "Convert the number to a stringiterate through each digit and store it in a variable.Then run an inner loop, compare the iterator of the outer loop with each digit of the inner loop and if they are equal then increment the occurrence count of the digit.Then check for equality between occurrence count and the variable in which each digit is stored so that we can know if the current number is autobiographical or not." }, { "code": null, "e": 25614, "s": 25583, "text": "Convert the number to a string" }, { "code": null, "e": 25669, "s": 25614, "text": "iterate through each digit and store it in a variable." }, { "code": null, "e": 25838, "s": 25669, "text": "Then run an inner loop, compare the iterator of the outer loop with each digit of the inner loop and if they are equal then increment the occurrence count of the digit." }, { "code": null, "e": 26004, "s": 25838, "text": "Then check for equality between occurrence count and the variable in which each digit is stored so that we can know if the current number is autobiographical or not." }, { "code": null, "e": 26056, "s": 26004, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26060, "s": 26056, "text": "C++" }, { "code": null, "e": 26065, "s": 26060, "text": "Java" }, { "code": null, "e": 26073, "s": 26065, "text": "Python3" }, { "code": null, "e": 26076, "s": 26073, "text": "C#" }, { "code": "// C++ implementation to find// Autobiographical numbers with length N #include <bits/stdc++.h>using namespace std; // Function to return if the// number is autobiographical or notbool isAutoBio(int num){ string autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = to_string(num); for (int i = 0; i < autoStr.size(); i++) { // Extracting each character // from each index one by one // and converting into an integer index = autoStr.at(i) - '0'; // Initialise count as 0 cnt = 0; for (j = 0; j < autoStr.size(); j++) { number = autoStr.at(j) - '0'; // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (index != cnt) return false; } return true;} // Function to print autobiographical number// with given number of digitsvoid findAutoBios(int n){ int high, low, i, flag = 0; // Left boundary of interval low = pow(10, n - 1); // Right boundary of interval high = pow(10, n) - 1; for (i = low; i <= high; i++) { if (isAutoBio(i)) { flag = 1; cout << i << \", \"; } } // Flag = 0 implies that the number // is not an autobiographical no. if (!flag) cout << \"There is no \" << \"Autobiographical number\" << \" with \" << n << \" digits\\n\";} // Driver Codeint main(){ int N = 0; findAutoBios(N); N = 4; findAutoBios(N); return 0;}", "e": 27889, "s": 26076, "text": null }, { "code": "// Java implementation to find// Autobiographical numbers with length N import java.util.*;import java.lang.Math; public class autobio { public static boolean isAutoBio(int num) { String autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = Integer.toString(num); for (i = 0; i < autoStr.length(); i++) { // Extracting each character // from each index one by one // and converting into an integer index = Integer.parseInt(autoStr.charAt(i) + \"\"); // initialize count as 0 cnt = 0; for (j = 0; j < autoStr.length(); j++) { number = Integer.parseInt(autoStr.charAt(j) + \"\"); // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (cnt != index) return false; } return true; } // Function to print autobiographical number // with given number of digits public static void findAutoBios(double n) { // both the boundaries are taken double, so as // to satisfy Math.pow() function's signature double high, low; int i, flag = 0; // Left boundary of interval low = Math.pow(10.0, n - 1); // Right boundary of interval high = Math.pow(10.0, n) - 1.0; for (i = (int)low; i <= (int)high; i++) if (isAutoBio(i)) { flag = 1; System.out.print(i + \", \"); } // Flag = 0 implies that the number // is not an autobiographical no. if (flag == 0) System.out.println(\"There is no Autobiographical Number\" + \"with \" + (int)n + \" digits\"); } // Driver Code public static void main(String[] args) { double N = 0; findAutoBios(N); N = 4; findAutoBios(N); }}", "e": 30130, "s": 27889, "text": null }, { "code": "# Python implementation to find# Autobiographical numbers with length N from math import pow # Function to return if the# number is autobiographical or notdef isAutoBio(num): # Converting the integer # number to string autoStr = str(num) for i in range(0, len(autoStr)): # Extracting each character # from each index one by one # and converting into an integer index = int(autoStr[i]) # Initialize count as 0 cnt = 0 for j in range(0, len(autoStr)): number = int(autoStr[j]) # Check if it is equal to the # index i if true then # increment the count if number == i: # It is an # Autobiographical # number cnt += 1 # Return false if the count and # the index number are not equal if cnt != index: return False return True # Function to print autobiographical number# with given number of digitsdef findAutoBios(n): # Left boundary of interval low = int(pow(10, n-1)) # Right boundary of interval high = int(pow(10, n) - 1) flag = 0 for i in range(low, high + 1): if isAutoBio(i): flag = 1 print(i, end =', ') # Flag = 0 implies that the number # is not an autobiographical no. if flag == 0: print(\"There is no Autobiographical Number with \"+ str(n) + \" digits\") # Driver Codeif __name__ == \"__main__\": N = 0 findAutoBios(N) N = 4 findAutoBios(N)", "e": 31704, "s": 30130, "text": null }, { "code": "// C# implementation to find// Autobiographical numbers with length Nusing System; class autobio { public static bool isAutoBio(int num) { String autoStr; int index, number, i, j, cnt; // Converting the integer // number to string autoStr = num.ToString(); for (i = 0; i < autoStr.Length; i++) { // Extracting each character // from each index one by one // and converting into an integer index = Int32.Parse(autoStr[i] + \"\"); // initialize count as 0 cnt = 0; for (j = 0; j < autoStr.Length; j++) { number = Int32.Parse(autoStr[j] + \"\"); // Check if it is equal to the // index i if true then // increment the count if (number == i) // It is an // Autobiographical // number cnt++; } // Return false if the count and // the index number are not equal if (cnt != index) return false; } return true; } // Function to print autobiographical number // with given number of digits public static void findAutoBios(double n) { // both the boundaries are taken double, so as // to satisfy Math.Pow() function's signature double high, low; int i, flag = 0; // Left boundary of interval low = Math.Pow(10.0, n - 1); // Right boundary of interval high = Math.Pow(10.0, n) - 1.0; for (i = (int)low; i <= (int)high; i++) if (isAutoBio(i)) { flag = 1; Console.Write(i + \", \"); } // Flag = 0 implies that the number // is not an autobiographical no. if (flag == 0) Console.WriteLine(\"There is no Autobiographical Number\" + \"with \" + (int)n + \" digits\"); } // Driver Code public static void Main(String[] args) { double N = 0; findAutoBios(N); N = 4; findAutoBios(N); }} // This code is contributed by sapnasingh4991", "e": 33933, "s": 31704, "text": null }, { "code": null, "e": 33994, "s": 33933, "text": "There is no Autobiographical number with 0 digits\n1210, 2020" }, { "code": null, "e": 34028, "s": 33996, "text": "Time Complexity: O(10n – 10n-1)" }, { "code": null, "e": 34050, "s": 34028, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 34065, "s": 34050, "text": "saikiranjagini" }, { "code": null, "e": 34080, "s": 34065, "text": "sapnasingh4991" }, { "code": null, "e": 34096, "s": 34080, "text": "souravmahato348" }, { "code": null, "e": 34110, "s": 34096, "text": "number-digits" }, { "code": null, "e": 34123, "s": 34110, "text": "Mathematical" }, { "code": null, "e": 34136, "s": 34123, "text": "Mathematical" }, { "code": null, "e": 34234, "s": 34136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34258, "s": 34234, "text": "Merge two sorted arrays" }, { "code": null, "e": 34301, "s": 34258, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34315, "s": 34301, "text": "Prime Numbers" }, { "code": null, "e": 34364, "s": 34315, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 34405, "s": 34364, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34426, "s": 34405, "text": "Operators in C / C++" }, { "code": null, "e": 34468, "s": 34426, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 34511, "s": 34468, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34574, "s": 34511, "text": "Efficient program to print all prime factors of a given number" } ]
MathML - Overview
MathML stands for Mathematical Markup Language and is an XML based application. It is used to describe mathematical and scientific notations. It's 1 and 2 version were created and developed by The Math Working Group which is one of the oldest W3C Working Groups during 1996-2004. MathML version 3 was created during Math Working Group's second activity period (2006-2016)and is an ISO standard. MathML is XML based and have limited number of tags which can be used to mark up a mathematical equation in terms of format and its semantics. MathML intends to capture meaning of syntax as well as formatting of the equation. Considering the fact the mathematical equations are often meaningful to many applications so writing them using MathML handles formatting as well as meaning of an equation. MathML provides low-level format to describing mathematics as a basis taken for machine to machine communication. Various applications like algebra systems, print typesetters can use MathML to encode mathematical notation for high-quality visual display, and mathematical content and scientific software, voice synthesizers can use MathML for semantics. MathML provides two ways to represent a mathematical notation. Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc. Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc. Semantic Way − It uses mark up tags like apply, eq, power etc. Semantic Way − It uses mark up tags like apply, eq, power etc. We are using MathJax library to render MathML syntax so that it can run on all major browsers. It currently supports presentational way only. <math xmlns = "http://www.w3.org/1998/Math/MathML"> <mrow> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <mrow> <mn>4</mn> <mo>⁢</mo> <mi>x</mi> </mrow> <mo>+</mo> <mn>4</mn> </mrow> <mo>=</mo> <mn>0</mn> </mrow> </math> Print Add Notes Bookmark this page
[ { "code": null, "e": 2652, "s": 2257, "text": "MathML stands for Mathematical Markup Language and is an XML based application. It is used to describe mathematical and scientific notations. It's 1 and 2 version were created and developed by The Math Working Group which is one of the oldest W3C Working Groups during 1996-2004. MathML version 3 was created during Math Working Group's second activity period (2006-2016)and is an ISO standard." }, { "code": null, "e": 3165, "s": 2652, "text": "MathML is XML based and have limited number of tags which can be used to mark up a mathematical equation in terms of format and its semantics. MathML intends to capture meaning of syntax as well as formatting of the equation. Considering the fact the mathematical equations are often meaningful to many applications so writing them using MathML handles formatting as well as meaning of an equation. MathML provides low-level format to describing mathematics as a basis taken for machine to machine communication." }, { "code": null, "e": 3405, "s": 3165, "text": "Various applications like algebra systems, print typesetters can use MathML to encode mathematical notation for high-quality visual display, and mathematical content and scientific software, voice synthesizers can use MathML for semantics." }, { "code": null, "e": 3468, "s": 3405, "text": "MathML provides two ways to represent a mathematical notation." }, { "code": null, "e": 3567, "s": 3468, "text": "Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc." }, { "code": null, "e": 3666, "s": 3567, "text": "Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc." }, { "code": null, "e": 3729, "s": 3666, "text": "Semantic Way − It uses mark up tags like apply, eq, power etc." }, { "code": null, "e": 3792, "s": 3729, "text": "Semantic Way − It uses mark up tags like apply, eq, power etc." }, { "code": null, "e": 3934, "s": 3792, "text": "We are using MathJax library to render MathML syntax so that it can run on all major browsers. It currently supports presentational way only." }, { "code": null, "e": 4282, "s": 3934, "text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mrow>\n <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo>\n <mrow>\n <mn>4</mn>\n <mo>⁢</mo>\n <mi>x</mi>\n </mrow>\n <mo>+</mo>\n <mn>4</mn>\n </mrow>\n \n <mo>=</mo>\n <mn>0</mn>\n </mrow>\n</math>" }, { "code": null, "e": 4289, "s": 4282, "text": " Print" }, { "code": null, "e": 4300, "s": 4289, "text": " Add Notes" } ]
How add files to S3 Bucket using Shell Script - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here we will see how to add files to S3 Bucket using Shell Script. Create S3 Bucket Create an IAM user, get Access Key and Secret Key The shell script is the most prominent solution to push the files into S3 bucket if we consider this task as an independent. As part of this tutorial, I am going to push all the files under /opt/s3files directory to s3 bucket. bucket=my-files files_location=/opt/s3files/ now_time=$(date +"%H%M%S") contentType="application/x-compressed-tar" dateValue=`date -R` # your key goes here.. s3Key=AKIAWQEOCFWY224LOMFA # your secrets goes here.. s3Secret=wu78rgdkjrhhdbcoUed+Xm1chCytUTiVeyOUDFJE function pushToS3() { files_path=$1 for file in $files_path* do fname=$(basename $file) logInfo "Start sending $fname to S3" resource="/${bucket}/${now_date}/${fname}_${now_time}" stringToSign="PUT\n\n${contentType}\n${dateValue}\n${resource}" signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${s3Secret} -binary | base64` curl -X PUT -T "${file}" \ -H "Host: ${bucket}.s3.amazonaws.com" \ -H "Date: ${dateValue}" \ -H "Content-Type: ${contentType}" \ -H "Authorization: AWS ${s3Key}:${signature}" \ https://${bucket}.s3.amazonaws.com/${now_date}/${fname}_${now_time} logInfo "$fname has been sent to S3 successfully." done } pushToS3 $files_location Provide execute permissions to the file: $chmod 777 SendToS3.sh $./SendToS3.sh S3 Upload Objects Happy Learning 🙂 Date yyyymmdd format in Shell Script Shell Script How to write logs in a Separate File How to Copy Local Files to AWS EC2 instance Manually ? Java Reflection Get Field Information Modes of Python Program How to add dynamic files to JTree Java 8 walk How to Read all files in a folder Java 8 – Convert java.util.Date to java.time.LocalDate php readfile Example Tutorials How to convert Timestamp to Date in Java Date yyyymmdd format in Shell Script Shell Script How to write logs in a Separate File How to Copy Local Files to AWS EC2 instance Manually ? Java Reflection Get Field Information Modes of Python Program How to add dynamic files to JTree Java 8 walk How to Read all files in a folder Java 8 – Convert java.util.Date to java.time.LocalDate php readfile Example Tutorials How to convert Timestamp to Date in Java Luis Felipe December 20, 2021 at 4:11 am - Reply Hello! I have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again. Luis Felipe December 20, 2021 at 4:11 am - Reply Hello! I have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again. Hello! I have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again. Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 465, "s": 398, "text": "Here we will see how to add files to S3 Bucket using Shell Script." }, { "code": null, "e": 482, "s": 465, "text": "Create S3 Bucket" }, { "code": null, "e": 532, "s": 482, "text": "Create an IAM user, get Access Key and Secret Key" }, { "code": null, "e": 759, "s": 532, "text": "The shell script is the most prominent solution to push the files into S3 bucket if we consider this task as an independent. As part of this tutorial, I am going to push all the files under /opt/s3files directory to s3 bucket." }, { "code": null, "e": 1744, "s": 759, "text": "bucket=my-files\nfiles_location=/opt/s3files/\nnow_time=$(date +\"%H%M%S\")\ncontentType=\"application/x-compressed-tar\"\ndateValue=`date -R`\n# your key goes here..\ns3Key=AKIAWQEOCFWY224LOMFA\n# your secrets goes here..\ns3Secret=wu78rgdkjrhhdbcoUed+Xm1chCytUTiVeyOUDFJE\n\nfunction pushToS3()\n{\n files_path=$1\n for file in $files_path*\n do\n fname=$(basename $file)\n logInfo \"Start sending $fname to S3\"\n resource=\"/${bucket}/${now_date}/${fname}_${now_time}\"\n stringToSign=\"PUT\\n\\n${contentType}\\n${dateValue}\\n${resource}\"\n signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${s3Secret} -binary | base64`\n curl -X PUT -T \"${file}\" \\\n -H \"Host: ${bucket}.s3.amazonaws.com\" \\\n -H \"Date: ${dateValue}\" \\\n -H \"Content-Type: ${contentType}\" \\\n -H \"Authorization: AWS ${s3Key}:${signature}\" \\\n https://${bucket}.s3.amazonaws.com/${now_date}/${fname}_${now_time}\n logInfo \"$fname has been sent to S3 successfully.\"\n done\n}\npushToS3 $files_location" }, { "code": null, "e": 1785, "s": 1744, "text": "Provide execute permissions to the file:" }, { "code": null, "e": 1823, "s": 1785, "text": "$chmod 777 SendToS3.sh\n$./SendToS3.sh" }, { "code": null, "e": 1841, "s": 1823, "text": "S3 Upload Objects" }, { "code": null, "e": 1858, "s": 1841, "text": "Happy Learning 🙂" }, { "code": null, "e": 2271, "s": 1858, "text": "\nDate yyyymmdd format in Shell Script\nShell Script How to write logs in a Separate File\nHow to Copy Local Files to AWS EC2 instance Manually ?\nJava Reflection Get Field Information\nModes of Python Program\nHow to add dynamic files to JTree\nJava 8 walk How to Read all files in a folder\nJava 8 – Convert java.util.Date to java.time.LocalDate\nphp readfile Example Tutorials\nHow to convert Timestamp to Date in Java\n" }, { "code": null, "e": 2308, "s": 2271, "text": "Date yyyymmdd format in Shell Script" }, { "code": null, "e": 2358, "s": 2308, "text": "Shell Script How to write logs in a Separate File" }, { "code": null, "e": 2413, "s": 2358, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 2451, "s": 2413, "text": "Java Reflection Get Field Information" }, { "code": null, "e": 2475, "s": 2451, "text": "Modes of Python Program" }, { "code": null, "e": 2509, "s": 2475, "text": "How to add dynamic files to JTree" }, { "code": null, "e": 2555, "s": 2509, "text": "Java 8 walk How to Read all files in a folder" }, { "code": null, "e": 2610, "s": 2555, "text": "Java 8 – Convert java.util.Date to java.time.LocalDate" }, { "code": null, "e": 2641, "s": 2610, "text": "php readfile Example Tutorials" }, { "code": null, "e": 2682, "s": 2641, "text": "How to convert Timestamp to Date in Java" }, { "code": null, "e": 2948, "s": 2682, "text": "\n\n\n\n\n\nLuis Felipe\nDecember 20, 2021 at 4:11 am - Reply \n\nHello!\nI have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again.\n\n\n\n\n" }, { "code": null, "e": 3212, "s": 2948, "text": "\n\n\n\n\nLuis Felipe\nDecember 20, 2021 at 4:11 am - Reply \n\nHello!\nI have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again.\n\n\n\n" }, { "code": null, "e": 3219, "s": 3212, "text": "Hello!" }, { "code": null, "e": 3416, "s": 3219, "text": "I have a question: does S3 verify if a data already exists in it before upload? I mean, if I already have an archive in S3 and it’s still in the path of upload I don’t want to send it to S3 again." }, { "code": null, "e": 3422, "s": 3420, "text": "Δ" }, { "code": null, "e": 3446, "s": 3422, "text": " Install Java on Mac OS" }, { "code": null, "e": 3474, "s": 3446, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3503, "s": 3474, "text": " Install Minikube on Windows" }, { "code": null, "e": 3538, "s": 3503, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3565, "s": 3538, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3592, "s": 3565, "text": " Install Gradle on Windows" }, { "code": null, "e": 3621, "s": 3592, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3647, "s": 3621, "text": " Install PuTTY on windows" }, { "code": null, "e": 3673, "s": 3647, "text": " Install Mysql on Windows" }, { "code": null, "e": 3709, "s": 3673, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 3743, "s": 3709, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 3769, "s": 3743, "text": " Install Maven on Windows" }, { "code": null, "e": 3794, "s": 3769, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 3828, "s": 3794, "text": " Install Maven on Windows Command" }, { "code": null, "e": 3863, "s": 3828, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 3887, "s": 3863, "text": " Install Ant on Windows" }, { "code": null, "e": 3916, "s": 3887, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3948, "s": 3916, "text": " Install Apache Kafka on Ubuntu" } ]
Math.Round() Method in C#
The Math.Round() method in C# rounds a value to the nearest integer or to the specified number of fractional digits. The following are the methods overloaded by Math.Round() − Math.Round(Double) Math.Round(Double, Int32) Math.Round(Double, Int32, MidpointRounding) Math.Round(Double, MidpointRounding) Math.Round(Decimal) Math.Round(Decimal, Int32) Math.Round(Decimal, Int32, MidpointRounding) Math.Round(Decimal, MidpointRounding) Let us now see an example to implement Math.Round() method i.e. Math.Round(Decimal) − using System; public class Demo { public static void Main(){ Decimal val1 = 78.12m; Decimal val2 = 30.675m; Console.WriteLine("Decimal Value = " + val1); Console.WriteLine("Rounded value = " + Math.Round(val1)); Console.WriteLine("Decimal Value = " + val2); Console.WriteLine("Rounded value = " + Math.Round(val2)); } } This will produce the following output − Decimal Value = 78.12 Rounded value = 78 Decimal Value = 30.675 Rounded value = 31 Let us see another example to implement Math.Round() method i.e. Math.Round(Double) − using System; public class Demo { public static void Main(){ Double val1 = 23.10; Double val2 = 90.98; Console.WriteLine("Double Value = " + val1); Console.WriteLine("Rounded value = " + Math.Round(val1)); Console.WriteLine("Double Value = " + val2); Console.WriteLine("Rounded value = " + Math.Round(val2)); } } This will produce the following output − Double Value = 23.1 Rounded value = 23 Double Value = 90.98 Rounded value = 91
[ { "code": null, "e": 1179, "s": 1062, "text": "The Math.Round() method in C# rounds a value to the nearest integer or to the specified number of fractional digits." }, { "code": null, "e": 1238, "s": 1179, "text": "The following are the methods overloaded by Math.Round() −" }, { "code": null, "e": 1494, "s": 1238, "text": "Math.Round(Double)\nMath.Round(Double, Int32)\nMath.Round(Double, Int32, MidpointRounding)\nMath.Round(Double, MidpointRounding)\nMath.Round(Decimal)\nMath.Round(Decimal, Int32)\nMath.Round(Decimal, Int32, MidpointRounding)\nMath.Round(Decimal, MidpointRounding)" }, { "code": null, "e": 1580, "s": 1494, "text": "Let us now see an example to implement Math.Round() method i.e. Math.Round(Decimal) −" }, { "code": null, "e": 1942, "s": 1580, "text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 78.12m;\n Decimal val2 = 30.675m;\n Console.WriteLine(\"Decimal Value = \" + val1);\n Console.WriteLine(\"Rounded value = \" + Math.Round(val1));\n Console.WriteLine(\"Decimal Value = \" + val2);\n Console.WriteLine(\"Rounded value = \" + Math.Round(val2));\n }\n}" }, { "code": null, "e": 1983, "s": 1942, "text": "This will produce the following output −" }, { "code": null, "e": 2066, "s": 1983, "text": "Decimal Value = 78.12\nRounded value = 78\nDecimal Value = 30.675\nRounded value = 31" }, { "code": null, "e": 2152, "s": 2066, "text": "Let us see another example to implement Math.Round() method i.e. Math.Round(Double) −" }, { "code": null, "e": 2507, "s": 2152, "text": "using System;\npublic class Demo {\n public static void Main(){\n Double val1 = 23.10;\n Double val2 = 90.98;\n Console.WriteLine(\"Double Value = \" + val1);\n Console.WriteLine(\"Rounded value = \" + Math.Round(val1));\n Console.WriteLine(\"Double Value = \" + val2);\n Console.WriteLine(\"Rounded value = \" + Math.Round(val2));\n }\n}" }, { "code": null, "e": 2548, "s": 2507, "text": "This will produce the following output −" }, { "code": null, "e": 2627, "s": 2548, "text": "Double Value = 23.1\nRounded value = 23\nDouble Value = 90.98\nRounded value = 91" } ]
How to use BroadcastReceiver in Android?
This example demonstrates how do I use BroadcastReceiver in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Switch android:id="@+id/wifiSwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Switch wifiSwitch; WifiManager wifiManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiSwitch = findViewById(R.id.wifiSwitch); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { wifiManager.setWifiEnabled(true); wifiSwitch.setText("WiFi is ON"); } else { wifiManager.setWifiEnabled(false); wifiSwitch.setText("WiFi is OFF"); } } }); } @Override protected void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION); registerReceiver(wifiStateReceiver, intentFilter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(wifiStateReceiver); } private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int wifiStateExtra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); switch (wifiStateExtra) { case WifiManager.WIFI_STATE_ENABLED: wifiSwitch.setChecked(true); wifiSwitch.setText("WiFi is ON"); Toast.makeText(MainActivity.this, "Wifi is On", Toast.LENGTH_SHORT).show(); break; case WifiManager.WIFI_STATE_DISABLED: wifiSwitch.setChecked(false); wifiSwitch.setText("WiFi is OFF"); Toast.makeText(MainActivity.this, "Wifi is Off", Toast.LENGTH_SHORT).show(); break; } } }; } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1131, "s": 1062, "text": "This example demonstrates how do I use BroadcastReceiver in android." }, { "code": null, "e": 1260, "s": 1131, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1325, "s": 1260, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1796, "s": 1325, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Switch\n android:id=\"@+id/wifiSwitch\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 1853, "s": 1796, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4271, "s": 1853, "text": "import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.wifi.WifiManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.CompoundButton;\nimport android.widget.Switch;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Switch wifiSwitch;\n WifiManager wifiManager;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n wifiSwitch = findViewById(R.id.wifiSwitch);\n wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);\n wifiSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked) {\n wifiManager.setWifiEnabled(true);\n wifiSwitch.setText(\"WiFi is ON\");\n } else {\n wifiManager.setWifiEnabled(false);\n wifiSwitch.setText(\"WiFi is OFF\");\n }\n }\n });\n }\n @Override\n protected void onStart() {\n super.onStart();\n IntentFilter intentFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);\n registerReceiver(wifiStateReceiver, intentFilter);\n }\n @Override\n protected void onStop() {\n super.onStop();\n unregisterReceiver(wifiStateReceiver);\n }\n private BroadcastReceiver wifiStateReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n int wifiStateExtra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);\n switch (wifiStateExtra) {\n case WifiManager.WIFI_STATE_ENABLED:\n wifiSwitch.setChecked(true);\n wifiSwitch.setText(\"WiFi is ON\");\n Toast.makeText(MainActivity.this, \"Wifi is On\", Toast.LENGTH_SHORT).show();\n break;\n case WifiManager.WIFI_STATE_DISABLED:\n wifiSwitch.setChecked(false);\n wifiSwitch.setText(\"WiFi is OFF\");\n Toast.makeText(MainActivity.this, \"Wifi is Off\", Toast.LENGTH_SHORT).show();\n break;\n }\n }\n };\n}" }, { "code": null, "e": 4326, "s": 4271, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5146, "s": 4326, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\" />\n <uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5493, "s": 5146, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5534, "s": 5493, "text": "Click here to download the project code." } ]
Plotting time-series with Date labels on X-axis in R - GeeksforGeeks
30 Jun, 2021 In this article, we will discuss how to plot time-series with date labels on the x-axis in R Programming Language supportive examples. The plot() method in base R is a generic plotting function. It plots the corresponding coordinates of the x and y axes respectively. The plot can be customized to add the line type, line width in the plot. Syntax: plot(x, y, ...) Parameter : x, y – The coordinates to plot. The input data frame contains col1 as the date character strings and col2 as the corresponding time stamps. Example: R # defining a data framedata_frame <- data.frame( col1 = c("6/7/2021","7/7/2021","8/7/2021", "9/7/2021","10/7/2021"), col2 = c(799355, 805800,701262,531579, 690068)) print ("Original Dataframe")print (data_frame) # describing new column in date classdata_frame$col3 <- as.Date(data_frame$col1, "%m/%d/%Y",) # plotting the dataplot(data_frame$col3, data_frame$col2 , cex = 0.9,type = "l" ,xaxt = "n" ) # Add dates to x-axisaxis(1, data_frame$col3, format(data_frame$col3, "%d-%m-%Y")) Output [1] "Original Dataframe" col1 col2 1 6/7/2021 799355 2 7/7/2021 805800 3 8/7/2021 701262 4 9/7/2021 531579 5 10/7/2021 690068 The ggplot2 library is used to display descriptive complex plots in the R programming language working space window. The ggplot() method is used to plot the data points of the specified data frame and specify the set of plot aesthetics. It is used to create an aesthetic mapping and add a particular geom function mapping. Syntax: ggplot(data = NULL, mapping = aes(c1, c2 )) + geom_line() Parameters : data – The default data set to plot mapping – The aesthetic mapping to use The geom_line() is used to add geoms in the form of lines and points. It is used to plotting time series as well as lines in the plot. Example: R library("ggplot2") # defining a data framedata_frame <- data.frame( col1 = c("1/6/2021","1/7/2021","1/8/2021", "1/9/2021","1/10/2021"), col2 = c(799355, 805800,701262,531579, 690068)) print ("Original Dataframe")print (data_frame) # describing new column in date classdata_frame$col3 <- as.Date(data_frame$col1, "%m/%d/%Y") # plotting the dataggplot( data = data_frame, aes( col3, col2 )) + geom_line() +scale_x_date(date_labels = "%Y-%m-%d") Output [1] "Original Dataframe" col1 col2 1 6/7/2021 799355 2 7/7/2021 805800 3 8/7/2021 701262 4 9/7/2021 531579 5 10/7/2021 690068 Picked R-Charts R-ggplot R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25377, "s": 25242, "text": "In this article, we will discuss how to plot time-series with date labels on the x-axis in R Programming Language supportive examples." }, { "code": null, "e": 25584, "s": 25377, "text": "The plot() method in base R is a generic plotting function. It plots the corresponding coordinates of the x and y axes respectively. The plot can be customized to add the line type, line width in the plot. " }, { "code": null, "e": 25592, "s": 25584, "text": "Syntax:" }, { "code": null, "e": 25608, "s": 25592, "text": "plot(x, y, ...)" }, { "code": null, "e": 25621, "s": 25608, "text": "Parameter : " }, { "code": null, "e": 25654, "s": 25621, "text": "x, y – The coordinates to plot. " }, { "code": null, "e": 25763, "s": 25654, "text": "The input data frame contains col1 as the date character strings and col2 as the corresponding time stamps. " }, { "code": null, "e": 25772, "s": 25763, "text": "Example:" }, { "code": null, "e": 25774, "s": 25772, "text": "R" }, { "code": "# defining a data framedata_frame <- data.frame( col1 = c(\"6/7/2021\",\"7/7/2021\",\"8/7/2021\", \"9/7/2021\",\"10/7/2021\"), col2 = c(799355, 805800,701262,531579, 690068)) print (\"Original Dataframe\")print (data_frame) # describing new column in date classdata_frame$col3 <- as.Date(data_frame$col1, \"%m/%d/%Y\",) # plotting the dataplot(data_frame$col3, data_frame$col2 , cex = 0.9,type = \"l\" ,xaxt = \"n\" ) # Add dates to x-axisaxis(1, data_frame$col3, format(data_frame$col3, \"%d-%m-%Y\"))", "e": 26419, "s": 25774, "text": null }, { "code": null, "e": 26426, "s": 26419, "text": "Output" }, { "code": null, "e": 26560, "s": 26426, "text": "[1] \"Original Dataframe\"\ncol1 col2\n1 6/7/2021 799355\n2 7/7/2021 805800\n3 8/7/2021 701262 \n4 9/7/2021 531579 \n5 10/7/2021 690068" }, { "code": null, "e": 26678, "s": 26560, "text": "The ggplot2 library is used to display descriptive complex plots in the R programming language working space window. " }, { "code": null, "e": 26885, "s": 26678, "text": "The ggplot() method is used to plot the data points of the specified data frame and specify the set of plot aesthetics. It is used to create an aesthetic mapping and add a particular geom function mapping. " }, { "code": null, "e": 26893, "s": 26885, "text": "Syntax:" }, { "code": null, "e": 26951, "s": 26893, "text": "ggplot(data = NULL, mapping = aes(c1, c2 )) + geom_line()" }, { "code": null, "e": 26965, "s": 26951, "text": "Parameters : " }, { "code": null, "e": 27002, "s": 26965, "text": "data – The default data set to plot " }, { "code": null, "e": 27041, "s": 27002, "text": "mapping – The aesthetic mapping to use" }, { "code": null, "e": 27177, "s": 27041, "text": "The geom_line() is used to add geoms in the form of lines and points. It is used to plotting time series as well as lines in the plot. " }, { "code": null, "e": 27186, "s": 27177, "text": "Example:" }, { "code": null, "e": 27188, "s": 27186, "text": "R" }, { "code": "library(\"ggplot2\") # defining a data framedata_frame <- data.frame( col1 = c(\"1/6/2021\",\"1/7/2021\",\"1/8/2021\", \"1/9/2021\",\"1/10/2021\"), col2 = c(799355, 805800,701262,531579, 690068)) print (\"Original Dataframe\")print (data_frame) # describing new column in date classdata_frame$col3 <- as.Date(data_frame$col1, \"%m/%d/%Y\") # plotting the dataggplot( data = data_frame, aes( col3, col2 )) + geom_line() +scale_x_date(date_labels = \"%Y-%m-%d\")", "e": 27728, "s": 27188, "text": null }, { "code": null, "e": 27735, "s": 27728, "text": "Output" }, { "code": null, "e": 27867, "s": 27735, "text": "[1] \"Original Dataframe\"\ncol1 col2\n1 6/7/2021 799355\n2 7/7/2021 805800\n3 8/7/2021 701262\n4 9/7/2021 531579\n5 10/7/2021 690068" }, { "code": null, "e": 27874, "s": 27867, "text": "Picked" }, { "code": null, "e": 27883, "s": 27874, "text": "R-Charts" }, { "code": null, "e": 27892, "s": 27883, "text": "R-ggplot" }, { "code": null, "e": 27901, "s": 27892, "text": "R-Graphs" }, { "code": null, "e": 27909, "s": 27901, "text": "R-plots" }, { "code": null, "e": 27920, "s": 27909, "text": "R Language" }, { "code": null, "e": 28018, "s": 27920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28070, "s": 28018, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28108, "s": 28070, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28143, "s": 28108, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28201, "s": 28143, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28250, "s": 28201, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28287, "s": 28250, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28337, "s": 28287, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28380, "s": 28337, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28406, "s": 28380, "text": "Time Series Analysis in R" } ]
Functional Programming - Function Types
Functions are of two types − Predefined functions User-defined functions In this chapter, we will discuss in detail about functions. These are the functions that are built into Language to perform operations & are stored in the Standard Function Library. For Example − ‘Strcat’ in C++ & ‘concat’ in Haskell are used to append the two strings, ‘strlen’ in C++ & ‘len’ in Python are used to calculate the string length. The following program shows how you can print the length of a string using C++ − #include <iostream> #include <string.h> #include <stdio.h> using namespace std; int main() { char str[20] = "Hello World"; int len; len = strlen(str); cout<<"String length is: "<<len; return 0; } It will produce the following output − String length is: 11 The following program shows how to print the length of a string using Python, which is a functional programming language − str = "Hello World"; print("String length is: ", len(str)) It will produce the following output − ('String length is: ', 11) User-defined functions are defined by the user to perform specific tasks. There are four different patterns to define a function − Functions with no argument and no return value Functions with no argument but a return value Functions with argument but no return value Functions with argument and a return value The following program shows how to define a function with no argument and no return value in C++ − #include <iostream> using namespace std; void function1() { cout <<"Hello World"; } int main() { function1(); return 0; } It will produce the following output − Hello World The following program shows how you can define a similar function (no argument and no return value) in Python − def function1(): print ("Hello World") function1() It will produce the following output − Hello World The following program shows how to define a function with no argument but a return value in C++ − #include <iostream> using namespace std; string function1() { return("Hello World"); } int main() { cout<<function1(); return 0; } It will produce the following output − Hello World The following program shows how you can define a similar function (with no argument but a return value) in Python − def function1(): return "Hello World" res = function1() print(res) It will produce the following output − Hello World The following program shows how to define a function with argument but no return value in C++ − #include <iostream> using namespace std; void function1(int x, int y) { int c; c = x+y; cout<<"Sum is: "<<c; } int main() { function1(4,5); return 0; } It will produce the following output − Sum is: 9 The following program shows how you can define a similar function in Python − def function1(x,y): c = x + y print("Sum is:",c) function1(4,5) It will produce the following output − ('Sum is:', 9) The following program shows how to define a function in C++ with no argument but a return value − #include <iostream> using namespace std; int function1(int x, int y) { int c; c = x + y; return c; } int main() { int res; res = function1(4,5); cout<<"Sum is: "<<res; return 0; } It will produce the following output − Sum is: 9 The following program shows how to define a similar function (with argument and a return value) in Python − def function1(x,y): c = x + y return c res = function1(4,5) print("Sum is ",res) It will produce the following output − ('Sum is ', 9) 32 Lectures 3.5 hours Pavan Lalwani 11 Lectures 1 hours Prof. Paul Cline, Ed.D 72 Lectures 10.5 hours Arun Ammasai 51 Lectures 2 hours Skillbakerystudios 43 Lectures 4 hours Mohammad Nauman 8 Lectures 1 hours Santharam Sivalenka Print Add Notes Bookmark this page
[ { "code": null, "e": 1850, "s": 1821, "text": "Functions are of two types −" }, { "code": null, "e": 1871, "s": 1850, "text": "Predefined functions" }, { "code": null, "e": 1894, "s": 1871, "text": "User-defined functions" }, { "code": null, "e": 1954, "s": 1894, "text": "In this chapter, we will discuss in detail about functions." }, { "code": null, "e": 2076, "s": 1954, "text": "These are the functions that are built into Language to perform operations & are stored in the Standard Function Library." }, { "code": null, "e": 2239, "s": 2076, "text": "For Example − ‘Strcat’ in C++ & ‘concat’ in Haskell are used to append the two strings, ‘strlen’ in C++ & ‘len’ in Python are used to calculate the string length." }, { "code": null, "e": 2320, "s": 2239, "text": "The following program shows how you can print the length of a string using C++ −" }, { "code": null, "e": 2548, "s": 2320, "text": "#include <iostream> \n#include <string.h> \n#include <stdio.h> \nusing namespace std; \n\nint main() { \n char str[20] = \"Hello World\"; \n int len; \n len = strlen(str); \n cout<<\"String length is: \"<<len; \n return 0; \n} " }, { "code": null, "e": 2587, "s": 2548, "text": "It will produce the following output −" }, { "code": null, "e": 2609, "s": 2587, "text": "String length is: 11\n" }, { "code": null, "e": 2732, "s": 2609, "text": "The following program shows how to print the length of a string using Python, which is a functional programming language −" }, { "code": null, "e": 2793, "s": 2732, "text": "str = \"Hello World\"; \nprint(\"String length is: \", len(str)) " }, { "code": null, "e": 2832, "s": 2793, "text": "It will produce the following output −" }, { "code": null, "e": 2860, "s": 2832, "text": "('String length is: ', 11)\n" }, { "code": null, "e": 2991, "s": 2860, "text": "User-defined functions are defined by the user to perform specific tasks. There are four different patterns to define a function −" }, { "code": null, "e": 3038, "s": 2991, "text": "Functions with no argument and no return value" }, { "code": null, "e": 3084, "s": 3038, "text": "Functions with no argument but a return value" }, { "code": null, "e": 3128, "s": 3084, "text": "Functions with argument but no return value" }, { "code": null, "e": 3171, "s": 3128, "text": "Functions with argument and a return value" }, { "code": null, "e": 3270, "s": 3171, "text": "The following program shows how to define a function with no argument and no return value in C++ −" }, { "code": null, "e": 3412, "s": 3270, "text": "#include <iostream> \nusing namespace std; \n\nvoid function1() { \n cout <<\"Hello World\"; \n} \nint main() { \n function1(); \n return 0; \n} " }, { "code": null, "e": 3451, "s": 3412, "text": "It will produce the following output −" }, { "code": null, "e": 3465, "s": 3451, "text": "Hello World \n" }, { "code": null, "e": 3577, "s": 3465, "text": "The following program shows how you can define a similar function (no argument and no return value) in Python −" }, { "code": null, "e": 3642, "s": 3577, "text": "def function1(): \n print (\"Hello World\") \n \nfunction1() " }, { "code": null, "e": 3681, "s": 3642, "text": "It will produce the following output −" }, { "code": null, "e": 3695, "s": 3681, "text": "Hello World \n" }, { "code": null, "e": 3793, "s": 3695, "text": "The following program shows how to define a function with no argument but a return value in C++ −" }, { "code": null, "e": 3943, "s": 3793, "text": "#include <iostream> \nusing namespace std; \nstring function1() { \n return(\"Hello World\"); \n} \n\nint main() { \n cout<<function1(); \n return 0; \n}" }, { "code": null, "e": 3982, "s": 3943, "text": "It will produce the following output −" }, { "code": null, "e": 3996, "s": 3982, "text": "Hello World \n" }, { "code": null, "e": 4112, "s": 3996, "text": "The following program shows how you can define a similar function (with no argument but a return value) in Python −" }, { "code": null, "e": 4186, "s": 4112, "text": "def function1(): \n return \"Hello World\" \nres = function1() \nprint(res) " }, { "code": null, "e": 4225, "s": 4186, "text": "It will produce the following output −" }, { "code": null, "e": 4239, "s": 4225, "text": "Hello World \n" }, { "code": null, "e": 4335, "s": 4239, "text": "The following program shows how to define a function with argument but no return value in C++ −" }, { "code": null, "e": 4518, "s": 4335, "text": "#include <iostream> \nusing namespace std; \nvoid function1(int x, int y) { \n int c; \n c = x+y; \n cout<<\"Sum is: \"<<c; \n} \n\nint main() { \n function1(4,5); \n return 0; \n}" }, { "code": null, "e": 4557, "s": 4518, "text": "It will produce the following output −" }, { "code": null, "e": 4569, "s": 4557, "text": "Sum is: 9 \n" }, { "code": null, "e": 4647, "s": 4569, "text": "The following program shows how you can define a similar function in Python −" }, { "code": null, "e": 4720, "s": 4647, "text": "def function1(x,y): \n c = x + y \n print(\"Sum is:\",c) \nfunction1(4,5)" }, { "code": null, "e": 4759, "s": 4720, "text": "It will produce the following output −" }, { "code": null, "e": 4775, "s": 4759, "text": "('Sum is:', 9)\n" }, { "code": null, "e": 4873, "s": 4775, "text": "The following program shows how to define a function in C++ with no argument but a return value −" }, { "code": null, "e": 5095, "s": 4873, "text": "#include <iostream> \nusing namespace std; \nint function1(int x, int y) { \n int c; \n c = x + y; \n return c; \n} \n\nint main() { \n int res; \n res = function1(4,5); \n cout<<\"Sum is: \"<<res; \n return 0; \n}" }, { "code": null, "e": 5134, "s": 5095, "text": "It will produce the following output −" }, { "code": null, "e": 5146, "s": 5134, "text": "Sum is: 9 \n" }, { "code": null, "e": 5254, "s": 5146, "text": "The following program shows how to define a similar function (with argument and a return value) in Python −" }, { "code": null, "e": 5348, "s": 5254, "text": "def function1(x,y): \n c = x + y \n return c \n\nres = function1(4,5) \nprint(\"Sum is \",res) " }, { "code": null, "e": 5387, "s": 5348, "text": "It will produce the following output −" }, { "code": null, "e": 5403, "s": 5387, "text": "('Sum is ', 9)\n" }, { "code": null, "e": 5438, "s": 5403, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5453, "s": 5438, "text": " Pavan Lalwani" }, { "code": null, "e": 5486, "s": 5453, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 5510, "s": 5486, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 5546, "s": 5510, "text": "\n 72 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5560, "s": 5546, "text": " Arun Ammasai" }, { "code": null, "e": 5593, "s": 5560, "text": "\n 51 Lectures \n 2 hours \n" }, { "code": null, "e": 5613, "s": 5593, "text": " Skillbakerystudios" }, { "code": null, "e": 5646, "s": 5613, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 5663, "s": 5646, "text": " Mohammad Nauman" }, { "code": null, "e": 5695, "s": 5663, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 5716, "s": 5695, "text": " Santharam Sivalenka" }, { "code": null, "e": 5723, "s": 5716, "text": " Print" }, { "code": null, "e": 5734, "s": 5723, "text": " Add Notes" } ]
Filling byte array in Java
The byte array in Java can be filled by using the method java.util.Arrays.fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.util.Arrays.fill() are the array name and the value that is to be stored in the array elements. A program that demonstrates this is given as follows − Live Demo import java.util.Arrays; public class Demo { public static void main(String[] a) { byte arr[] = new byte[] {5, 1, 9, 2, 6}; System.out.print("Byte array elements are: "); for (int num : arr) { System.out.print(num + " "); } Arrays.fill(arr, (byte) 7); System.out.print("\nByte array elements after Arrays.fill() method are: "); for (int num : arr) { System.out.print(num + " "); } } } Byte array elements are: 5 1 9 2 6 Byte array elements after Arrays.fill() method are: 7 7 7 7 7 Now let us understand the above program. First, the elements of the byte array arr are printed. A code snippet which demonstrates this is as follows − byte arr[] = new byte[] {5, 1, 9, 2, 6}; System.out.print("Byte array elements are: "); for (int num : arr) { System.out.print(num + " "); } After this, the Arrays.fill() method is used to assign the byte value 7 to all the elements in the array. Then this array is printed. A code snippet which demonstrates this is as follows − Arrays.fill(arr, (byte) 7); System.out.print("\nByte array elements after Arrays.fill() method are: "); for (int num : arr) { System.out.print(num + " "); }
[ { "code": null, "e": 1348, "s": 1062, "text": "The byte array in Java can be filled by using the method java.util.Arrays.fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.util.Arrays.fill() are the array name and the value that is to be stored in the array elements." }, { "code": null, "e": 1403, "s": 1348, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 1871, "s": 1414, "text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] a) {\n byte arr[] = new byte[] {5, 1, 9, 2, 6};\n System.out.print(\"Byte array elements are: \");\n for (int num : arr) {\n System.out.print(num + \" \");\n }\n Arrays.fill(arr, (byte) 7);\n System.out.print(\"\\nByte array elements after Arrays.fill() method are: \");\n for (int num : arr) {\n System.out.print(num + \" \");\n }\n }\n}" }, { "code": null, "e": 1968, "s": 1871, "text": "Byte array elements are: 5 1 9 2 6\nByte array elements after Arrays.fill() method are: 7 7 7 7 7" }, { "code": null, "e": 2009, "s": 1968, "text": "Now let us understand the above program." }, { "code": null, "e": 2119, "s": 2009, "text": "First, the elements of the byte array arr are printed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2263, "s": 2119, "text": "byte arr[] = new byte[] {5, 1, 9, 2, 6};\nSystem.out.print(\"Byte array elements are: \");\nfor (int num : arr) {\n System.out.print(num + \" \");\n}" }, { "code": null, "e": 2452, "s": 2263, "text": "After this, the Arrays.fill() method is used to assign the byte value 7 to all the elements in the array. Then this array is printed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2612, "s": 2452, "text": "Arrays.fill(arr, (byte) 7);\nSystem.out.print(\"\\nByte array elements after Arrays.fill() method are: \");\nfor (int num : arr) {\n System.out.print(num + \" \");\n}" } ]
Lodash - toString method
_.toString(value) Converts value to a string. An empty string is returned for null and undefined values. The sign of -0 is preserved. value (*) − The value to convert. value (*) − The value to convert. (string) − Returns the converted string. (string) − Returns the converted string. var _ = require('lodash'); console.log(_.toString(-0)); console.log(_.toString([1, 2, 3])); Save the above program in tester.js. Run the following command to execute this program. \>node tester.js -0 1,2,3 Print Add Notes Bookmark this page
[ { "code": null, "e": 1846, "s": 1827, "text": "_.toString(value)\n" }, { "code": null, "e": 1962, "s": 1846, "text": "Converts value to a string. An empty string is returned for null and undefined values. The sign of -0 is preserved." }, { "code": null, "e": 1996, "s": 1962, "text": "value (*) − The value to convert." }, { "code": null, "e": 2030, "s": 1996, "text": "value (*) − The value to convert." }, { "code": null, "e": 2071, "s": 2030, "text": "(string) − Returns the converted string." }, { "code": null, "e": 2112, "s": 2071, "text": "(string) − Returns the converted string." }, { "code": null, "e": 2206, "s": 2112, "text": "var _ = require('lodash');\n \nconsole.log(_.toString(-0));\nconsole.log(_.toString([1, 2, 3]));" }, { "code": null, "e": 2294, "s": 2206, "text": "Save the above program in tester.js. Run the following command to execute this program." }, { "code": null, "e": 2312, "s": 2294, "text": "\\>node tester.js\n" }, { "code": null, "e": 2322, "s": 2312, "text": "-0\n1,2,3\n" }, { "code": null, "e": 2329, "s": 2322, "text": " Print" }, { "code": null, "e": 2340, "s": 2329, "text": " Add Notes" } ]
What is C++ Standard Output Stream (cout)?
std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog). As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in the header <iostream> with external linkage and static duration: it lasts the entire duration of the program. You can use this object to write to the screen. For example, if you want to write "Hello" to the screen, you'd write − Live Demo #include<iostream> int main() { std::cout << "Hello"; return 0; } Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using − $ g++ hello.cpp Run it using − $ ./a.out This will give the output − Hello
[ { "code": null, "e": 1411, "s": 1062, "text": "std::cout is an object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog)." }, { "code": null, "e": 1739, "s": 1411, "text": "As an object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write. The object is declared in the header <iostream> with external linkage and static duration: it lasts the entire duration of the program." }, { "code": null, "e": 1858, "s": 1739, "text": "You can use this object to write to the screen. For example, if you want to write \"Hello\" to the screen, you'd write −" }, { "code": null, "e": 1868, "s": 1858, "text": "Live Demo" }, { "code": null, "e": 1940, "s": 1868, "text": "#include<iostream>\nint main() {\n std::cout << \"Hello\";\n return 0;\n}" }, { "code": null, "e": 2077, "s": 1940, "text": "Then save this program to hello.cpp file. Finally navigate to the saved location of this file in the terminal/cmd and compile it using −" }, { "code": null, "e": 2093, "s": 2077, "text": "$ g++ hello.cpp" }, { "code": null, "e": 2108, "s": 2093, "text": "Run it using −" }, { "code": null, "e": 2118, "s": 2108, "text": "$ ./a.out" }, { "code": null, "e": 2146, "s": 2118, "text": "This will give the output −" }, { "code": null, "e": 2152, "s": 2146, "text": "Hello" } ]
CSS - z-index
The z-index sets the stacking level of an element. auto − The stack level of the element is the same as that of its parent element. auto − The stack level of the element is the same as that of its parent element. integer − The stack level of the element is set to the given value, and it establishes a new stacking context for any descendant elements. integer − The stack level of the element is set to the given value, and it establishes a new stacking context for any descendant elements. All the positioned elements. object.style.zindex = "1"; Following is the example which shows how to create layers in CSS. <html> <head> </head> <body> <div style = "background-color:red; width:300px; height:100px; position:relative; top:10px; left:80px; z-index:2"> </div> <div style = "background-color:yellow; width:300px; height:100px; position:relative; top:-60px; left:35px; z-index:1;"> </div> <div style = "background-color:green; width:300px; height:100px; position:relative; top:-220px; left:120px; z-index:3;"> </div> </body> </html> This will produce following result − 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2677, "s": 2626, "text": "The z-index sets the stacking level of an element." }, { "code": null, "e": 2758, "s": 2677, "text": "auto − The stack level of the element is the same as that of its parent element." }, { "code": null, "e": 2839, "s": 2758, "text": "auto − The stack level of the element is the same as that of its parent element." }, { "code": null, "e": 2978, "s": 2839, "text": "integer − The stack level of the element is set to the given value, and it establishes a new stacking context for any descendant elements." }, { "code": null, "e": 3117, "s": 2978, "text": "integer − The stack level of the element is set to the given value, and it establishes a new stacking context for any descendant elements." }, { "code": null, "e": 3146, "s": 3117, "text": "All the positioned elements." }, { "code": null, "e": 3174, "s": 3146, "text": "object.style.zindex = \"1\";\n" }, { "code": null, "e": 3240, "s": 3174, "text": "Following is the example which shows how to create layers in CSS." }, { "code": null, "e": 3891, "s": 3240, "text": "<html>\n <head>\n </head>\n \n <body>\n <div style = \"background-color:red;\n width:300px;\n height:100px;\n position:relative;\n top:10px;\n left:80px;\n z-index:2\">\n </div>\n \n <div style = \"background-color:yellow;\n width:300px;\n height:100px;\n position:relative;\n top:-60px;\n left:35px;\n z-index:1;\">\n </div>\n \n <div style = \"background-color:green;\n width:300px;\n height:100px;\n position:relative;\n top:-220px;\n left:120px;\n z-index:3;\">\n </div>\n </body>\n</html> " }, { "code": null, "e": 3928, "s": 3891, "text": "This will produce following result −" }, { "code": null, "e": 3963, "s": 3928, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3977, "s": 3963, "text": " Anadi Sharma" }, { "code": null, "e": 4012, "s": 3977, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4029, "s": 4012, "text": " Frahaan Hussain" }, { "code": null, "e": 4064, "s": 4029, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4095, "s": 4064, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4130, "s": 4095, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4161, "s": 4130, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4196, "s": 4161, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4227, "s": 4196, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4260, "s": 4227, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4291, "s": 4260, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4298, "s": 4291, "text": " Print" }, { "code": null, "e": 4309, "s": 4298, "text": " Add Notes" } ]
Python | sympy.apart() method - GeeksforGeeks
25 Jun, 2019 With the help of sympy.apart() method, we can performs a partial fraction decomposition on a rational mathematical expression. Syntax: apart(expression) Parameters:expression – It is a rational mathematical expression. Returns: Returns an expression after the partial decomposition. Example #1:In this example we can see that by using sympy.apart() method, we can get a partial fraction decomposition of a given mathematical expression. # import sympyfrom sympy import * x = symbols('x')expr = (4 * x**3 + 21 * x**2 + 10 * x + 12) / (x**4 + 5 * x**3 + 5 * x**2 + 4 * x) print("Mathematical expression : {}".format(expr)) # Use sympy.apart() methodpd = apart(expr) print("After Partial Decomposition : {}".format(pd)) Output: Mathematical expression : (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x) After Partial Decomposition : (2*x - 1)/(x**2 + x + 1) - 1/(x + 4) + 3/x Example #2: # import sympyfrom sympy import * x = symbols('x')expr = 1/(x + 3)(x + 2) print("Mathematical expression : {}".format(expr)) # Use sympy.factor_list() methodpd = apart(expr) print("After Partial Decomposition : {}".format(pd)) Output: Mathematical expression : 1/((x + 2)*(x + 3)) After Partial Decomposition : -1/(x + 3) + 1/(x + 2) SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n25 Jun, 2019" }, { "code": null, "e": 24028, "s": 23901, "text": "With the help of sympy.apart() method, we can performs a partial fraction decomposition on a rational mathematical expression." }, { "code": null, "e": 24054, "s": 24028, "text": "Syntax: apart(expression)" }, { "code": null, "e": 24120, "s": 24054, "text": "Parameters:expression – It is a rational mathematical expression." }, { "code": null, "e": 24184, "s": 24120, "text": "Returns: Returns an expression after the partial decomposition." }, { "code": null, "e": 24338, "s": 24184, "text": "Example #1:In this example we can see that by using sympy.apart() method, we can get a partial fraction decomposition of a given mathematical expression." }, { "code": "# import sympyfrom sympy import * x = symbols('x')expr = (4 * x**3 + 21 * x**2 + 10 * x + 12) / (x**4 + 5 * x**3 + 5 * x**2 + 4 * x) print(\"Mathematical expression : {}\".format(expr)) # Use sympy.apart() methodpd = apart(expr) print(\"After Partial Decomposition : {}\".format(pd)) ", "e": 24628, "s": 24338, "text": null }, { "code": null, "e": 24636, "s": 24628, "text": "Output:" }, { "code": null, "e": 24798, "s": 24636, "text": "Mathematical expression : (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x)\nAfter Partial Decomposition : (2*x - 1)/(x**2 + x + 1) - 1/(x + 4) + 3/x\n" }, { "code": null, "e": 24810, "s": 24798, "text": "Example #2:" }, { "code": "# import sympyfrom sympy import * x = symbols('x')expr = 1/(x + 3)(x + 2) print(\"Mathematical expression : {}\".format(expr)) # Use sympy.factor_list() methodpd = apart(expr) print(\"After Partial Decomposition : {}\".format(pd)) ", "e": 25048, "s": 24810, "text": null }, { "code": null, "e": 25056, "s": 25048, "text": "Output:" }, { "code": null, "e": 25156, "s": 25056, "text": "Mathematical expression : 1/((x + 2)*(x + 3))\nAfter Partial Decomposition : -1/(x + 3) + 1/(x + 2)\n" }, { "code": null, "e": 25162, "s": 25156, "text": "SymPy" }, { "code": null, "e": 25169, "s": 25162, "text": "Python" }, { "code": null, "e": 25267, "s": 25169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25276, "s": 25267, "text": "Comments" }, { "code": null, "e": 25289, "s": 25276, "text": "Old Comments" }, { "code": null, "e": 25321, "s": 25289, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25377, "s": 25321, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25419, "s": 25377, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25461, "s": 25419, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25497, "s": 25461, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25519, "s": 25497, "text": "Defaultdict in Python" }, { "code": null, "e": 25558, "s": 25519, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25585, "s": 25558, "text": "Python Classes and Objects" }, { "code": null, "e": 25616, "s": 25585, "text": "Python | os.path.join() method" } ]
JavaScript string.slice() Method - GeeksforGeeks
06 Oct, 2021 Below is the example of the string.slice() Method. Example: javascript <script> var A = 'Geeks for Geeks'; b = A.slice(0,5); c = A.slice(6,9); d = A.slice(10); document.write(b +"<br>"); document.write(c +"<br>"); document.write(d +"<br>"); </script> Output: Geeks for Geeks The string.slice() is an inbuilt method in javascript which is used to return a part or slice of the given input string.Syntax: string.slice(startingindex, endingindex) Parameter: This method uses two-parameter startingindex( from which index, the string should be started) and endingindex (before which index, the string should be included).Return Values: It returns a part or a slice of the given input string.JavaScript code to show the working of the string.slice() method: Code #1: javascript <script> // Taking a string as input. var A = 'Ram is going to school'; // Calling of slice() function. b = A.slice(0, 5); // Here starting index is 1 given // and ending index is not given to it so // it takes to the end of the string c = A.slice(1); // Here endingindex is -1 i.e, second last character // of the given string. d = A.slice(3, -1); e = A.slice(6); document.write(b +"<br>"); document.write(c +"<br>"); document.write(d +"<br>"); document.write(e); </script> Output: Ram i am is going to school is going to schoo going to school Code #2: javascript <script> // Taking a string as input. var A = 'Geeks for Geeks'; // Calling of slice() function. // Here starting index is -1 given b = A.slice(-1,5); // Here endingindex is -1 i.e c = A.slice(0,-1); document.write(b +"<br>"); document.write(c +"<br>"); </script> Output: Geeks for Geek Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 4 and above safari 1 and above ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request How to Use the JavaScript Fetch API to Get Data? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24554, "s": 24526, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24607, "s": 24554, "text": "Below is the example of the string.slice() Method. " }, { "code": null, "e": 24618, "s": 24607, "text": "Example: " }, { "code": null, "e": 24629, "s": 24618, "text": "javascript" }, { "code": "<script> var A = 'Geeks for Geeks'; b = A.slice(0,5); c = A.slice(6,9); d = A.slice(10); document.write(b +\"<br>\"); document.write(c +\"<br>\"); document.write(d +\"<br>\"); </script>", "e": 24857, "s": 24629, "text": null }, { "code": null, "e": 24867, "s": 24857, "text": "Output: " }, { "code": null, "e": 24883, "s": 24867, "text": "Geeks\nfor\nGeeks" }, { "code": null, "e": 25013, "s": 24883, "text": "The string.slice() is an inbuilt method in javascript which is used to return a part or slice of the given input string.Syntax: " }, { "code": null, "e": 25054, "s": 25013, "text": "string.slice(startingindex, endingindex)" }, { "code": null, "e": 25374, "s": 25054, "text": "Parameter: This method uses two-parameter startingindex( from which index, the string should be started) and endingindex (before which index, the string should be included).Return Values: It returns a part or a slice of the given input string.JavaScript code to show the working of the string.slice() method: Code #1: " }, { "code": null, "e": 25385, "s": 25374, "text": "javascript" }, { "code": "<script> // Taking a string as input. var A = 'Ram is going to school'; // Calling of slice() function. b = A.slice(0, 5); // Here starting index is 1 given // and ending index is not given to it so // it takes to the end of the string c = A.slice(1); // Here endingindex is -1 i.e, second last character // of the given string. d = A.slice(3, -1); e = A.slice(6); document.write(b +\"<br>\"); document.write(c +\"<br>\"); document.write(d +\"<br>\"); document.write(e); </script>", "e": 25929, "s": 25385, "text": null }, { "code": null, "e": 25939, "s": 25929, "text": "Output: " }, { "code": null, "e": 26001, "s": 25939, "text": "Ram i\nam is going to school\nis going to schoo\ngoing to school" }, { "code": null, "e": 26012, "s": 26001, "text": "Code #2: " }, { "code": null, "e": 26023, "s": 26012, "text": "javascript" }, { "code": "<script> // Taking a string as input. var A = 'Geeks for Geeks'; // Calling of slice() function. // Here starting index is -1 given b = A.slice(-1,5); // Here endingindex is -1 i.e c = A.slice(0,-1); document.write(b +\"<br>\"); document.write(c +\"<br>\"); </script>", "e": 26323, "s": 26023, "text": null }, { "code": null, "e": 26333, "s": 26323, "text": "Output: " }, { "code": null, "e": 26348, "s": 26333, "text": "Geeks for Geek" }, { "code": null, "e": 26369, "s": 26350, "text": "Supported Browser:" }, { "code": null, "e": 26388, "s": 26369, "text": "Chrome 1 and above" }, { "code": null, "e": 26406, "s": 26388, "text": "Edge 12 and above" }, { "code": null, "e": 26426, "s": 26406, "text": "Firefox 1 and above" }, { "code": null, "e": 26456, "s": 26426, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 26474, "s": 26456, "text": "Opera 4 and above" }, { "code": null, "e": 26493, "s": 26474, "text": "safari 1 and above" }, { "code": null, "e": 26505, "s": 26493, "text": "ysachin2314" }, { "code": null, "e": 26524, "s": 26505, "text": "JavaScript-Methods" }, { "code": null, "e": 26542, "s": 26524, "text": "javascript-string" }, { "code": null, "e": 26553, "s": 26542, "text": "JavaScript" }, { "code": null, "e": 26570, "s": 26553, "text": "Web Technologies" }, { "code": null, "e": 26668, "s": 26570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26677, "s": 26668, "text": "Comments" }, { "code": null, "e": 26690, "s": 26677, "text": "Old Comments" }, { "code": null, "e": 26751, "s": 26690, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26796, "s": 26751, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26868, "s": 26796, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26909, "s": 26868, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26958, "s": 26909, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 27014, "s": 26958, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27047, "s": 27014, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27109, "s": 27047, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27152, "s": 27109, "text": "How to fetch data from an API in ReactJS ?" } ]
Convert Column Classes of Data Table in R - GeeksforGeeks
26 May, 2021 The data.table package is used to ease the data manipulation operations such as sub-setting, grouping, and updating operations of the data table in R Programming Language. sapply() method in R programming language is used to apply a function over the specified R object, a data frame, or a matrix. If we specify FUN = “class”, the data type of each of the columns of the data table is returned. Syntax: sapply ( data-table , FUN) The data type of the particular column in R language can be changed to the required class, by explicit conversion. The result has to be stored in a different variable, in order to preserve it. Syntax: data.table [ , col-name := conv-func(col-name) ] In this syntax, conv-func illustrates the explicit conversion function to be applied to the particular column. For instance, it is as.character() for character conversion, as.numeric() for numeric conversion and as.factor() for factor-type variable conversion. Example: R library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print ("Original DataTable")print (data_table) # getting class of columnssapply(data_table , class) # convert column into characterdata_table_mod <- data_table[ , col3 := as.character(col3)] print ("Modified DataTable")print (data_table_mod)sapply(data_table_mod , class) Output [1] "Original DataTable" col1 col2 col3 1: 1 a 5 2: 2 b 8 3: 3 c 7 4: 4 d 6 5: 5 e 9 6: 1 a 10 col1 col2 col3 "integer" "character" "factor" [1] "Modified DataTable" col1 col2 col3 1: 1 a 5 2: 2 b 8 3: 3 c 7 4: 4 d 6 5: 5 e 9 6: 1 a 10 col1 col2 col3 "integer" "character" "character" However, the conversion of character factor to numeric can be simulated only if the particular column is convertible to numerical form. In the following code, when col2 of the data table is converted to integral format using as.numeric(), data is lost and replaced by missing values. Example: R library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print ("Original DataTable")print (data_table) # getting class of columnssapply(data_table , class) # convert column into characterdata_table_mod <- data_table[ , col2 := as.numeric(col2)] print ("Modified DataTable")print (data_table_mod)sapply(data_table_mod , class) Output [1] "Original DataTable" col1 col2 col3 1: 1 a 10 2: 2 b 6 3: 3 c 5 4: 4 d 9 5: 5 e 7 6: 1 a 8 col1 col2 col3 "integer" "character" "factor" [1] "Modified DataTable" col1 col2 col3 1: 1 NA 10 2: 2 NA 6 3: 3 NA 5 4: 4 NA 9 5: 5 NA 7 6: 1 NA 8 col1 col2 col3 "integer" "numeric" "factor" The lapply() method in R language is used to apply a user-defined function over all the components of the supplied data frame or data table object. It is mostly used for nested lists. Syntax: lapply( obj , FUN) Parameter: obj : An object to apply conversion onto FUN: Function applied to each element of the supplied object The following syntax can be used to the similar conversion of the specified columns into the factor type format. This implementation is used to update the columns by reference using`:=`, e.g., DT[ , names(DT) := lapply(.SD, as.factor)], that is, it doesn’t create any copies of your data. Since, factors are categorical variables which can be used to store both integers and characters, there is no loss or ambiguity in data retrieval. Example: R library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print ("Original DataTable")print (data_table) # getting class of columnssapply(data_table , class) # convert column into factor typecols <- c("col1","col2") # Change class of certain columnsdata_table_mod <- data_table[ , (cols) := lapply(.SD, as.factor), .SDcols = cols] print ("Modified DataTable")print (data_table_mod)sapply(data_table_mod , class) Output [1] "Original DataTable" col1 col2 col3 1: 1 a 5 2: 2 b 8 3: 3 c 7 4: 4 d 6 5: 5 e 9 6: 1 a 10 col1 col2 col3 "integer" "character" "factor" [1] "Modified DataTable" col1 col2 col3 1: 1 a 5 2: 2 b 8 3: 3 c 7 4: 4 d 6 5: 5 e 9 6: 1 a 10 col1 col2 col3 "factor" "factor" "factor" Picked R DataTable R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n26 May, 2021" }, { "code": null, "e": 25024, "s": 24851, "text": "The data.table package is used to ease the data manipulation operations such as sub-setting, grouping, and updating operations of the data table in R Programming Language. " }, { "code": null, "e": 25248, "s": 25024, "text": "sapply() method in R programming language is used to apply a function over the specified R object, a data frame, or a matrix. If we specify FUN = “class”, the data type of each of the columns of the data table is returned. " }, { "code": null, "e": 25256, "s": 25248, "text": "Syntax:" }, { "code": null, "e": 25283, "s": 25256, "text": "sapply ( data-table , FUN)" }, { "code": null, "e": 25477, "s": 25283, "text": "The data type of the particular column in R language can be changed to the required class, by explicit conversion. The result has to be stored in a different variable, in order to preserve it. " }, { "code": null, "e": 25485, "s": 25477, "text": "Syntax:" }, { "code": null, "e": 25534, "s": 25485, "text": "data.table [ , col-name := conv-func(col-name) ]" }, { "code": null, "e": 25795, "s": 25534, "text": "In this syntax, conv-func illustrates the explicit conversion function to be applied to the particular column. For instance, it is as.character() for character conversion, as.numeric() for numeric conversion and as.factor() for factor-type variable conversion." }, { "code": null, "e": 25804, "s": 25795, "text": "Example:" }, { "code": null, "e": 25806, "s": 25804, "text": "R" }, { "code": "library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print (\"Original DataTable\")print (data_table) # getting class of columnssapply(data_table , class) # convert column into characterdata_table_mod <- data_table[ , col3 := as.character(col3)] print (\"Modified DataTable\")print (data_table_mod)sapply(data_table_mod , class)", "e": 26264, "s": 25806, "text": null }, { "code": null, "e": 26271, "s": 26264, "text": "Output" }, { "code": null, "e": 26725, "s": 26271, "text": "[1] \"Original DataTable\" \n col1 col2 col3 \n1: 1 a 5 \n2: 2 b 8 \n3: 3 c 7 \n4: 4 d 6 \n5: 5 e 9 \n6: 1 a 10 \ncol1 col2 col3 \n\"integer\" \"character\" \"factor\" \n[1] \"Modified DataTable\" \n col1 col2 col3 \n1: 1 a 5 \n2: 2 b 8\n3: 3 c 7 \n4: 4 d 6 \n5: 5 e 9 \n6: 1 a 10 \ncol1 col2 col3 \n\"integer\" \"character\" \"character\" " }, { "code": null, "e": 27009, "s": 26725, "text": "However, the conversion of character factor to numeric can be simulated only if the particular column is convertible to numerical form. In the following code, when col2 of the data table is converted to integral format using as.numeric(), data is lost and replaced by missing values." }, { "code": null, "e": 27018, "s": 27009, "text": "Example:" }, { "code": null, "e": 27020, "s": 27018, "text": "R" }, { "code": "library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print (\"Original DataTable\")print (data_table) # getting class of columnssapply(data_table , class) # convert column into characterdata_table_mod <- data_table[ , col2 := as.numeric(col2)] print (\"Modified DataTable\")print (data_table_mod)sapply(data_table_mod , class)", "e": 27476, "s": 27020, "text": null }, { "code": null, "e": 27483, "s": 27476, "text": "Output" }, { "code": null, "e": 27935, "s": 27483, "text": "[1] \"Original DataTable\" \n col1 col2 col3 \n1: 1 a 10 \n2: 2 b 6 \n3: 3 c 5 \n4: 4 d 9 \n5: 5 e 7 \n6: 1 a 8 \ncol1 col2 col3 \n\"integer\" \"character\" \"factor\" \n[1] \"Modified DataTable\" \n col1 col2 col3 \n1: 1 NA 10 \n2: 2 NA 6 \n3: 3 NA 5 \n4: 4 NA 9 \n5: 5 NA 7 \n6: 1 NA 8 \ncol1 col2 col3 \n\"integer\" \"numeric\" \"factor\" " }, { "code": null, "e": 28119, "s": 27935, "text": "The lapply() method in R language is used to apply a user-defined function over all the components of the supplied data frame or data table object. It is mostly used for nested lists." }, { "code": null, "e": 28128, "s": 28119, "text": "Syntax: " }, { "code": null, "e": 28147, "s": 28128, "text": "lapply( obj , FUN)" }, { "code": null, "e": 28158, "s": 28147, "text": "Parameter:" }, { "code": null, "e": 28199, "s": 28158, "text": "obj : An object to apply conversion onto" }, { "code": null, "e": 28260, "s": 28199, "text": "FUN: Function applied to each element of the supplied object" }, { "code": null, "e": 28697, "s": 28260, "text": "The following syntax can be used to the similar conversion of the specified columns into the factor type format. This implementation is used to update the columns by reference using`:=`, e.g., DT[ , names(DT) := lapply(.SD, as.factor)], that is, it doesn’t create any copies of your data. Since, factors are categorical variables which can be used to store both integers and characters, there is no loss or ambiguity in data retrieval. " }, { "code": null, "e": 28706, "s": 28697, "text": "Example:" }, { "code": null, "e": 28708, "s": 28706, "text": "R" }, { "code": "library(data.table) # creating a data framedata_table <- data.table(col1 = c(1:5), col2 = letters[1:5], col3 = factor(sample(5:10))) print (\"Original DataTable\")print (data_table) # getting class of columnssapply(data_table , class) # convert column into factor typecols <- c(\"col1\",\"col2\") # Change class of certain columnsdata_table_mod <- data_table[ , (cols) := lapply(.SD, as.factor), .SDcols = cols] print (\"Modified DataTable\")print (data_table_mod)sapply(data_table_mod , class)", "e": 29329, "s": 28708, "text": null }, { "code": null, "e": 29336, "s": 29329, "text": "Output" }, { "code": null, "e": 29765, "s": 29336, "text": "[1] \"Original DataTable\"\n col1 col2 col3\n1: 1 a 5\n2: 2 b 8\n3: 3 c 7\n4: 4 d 6\n5: 5 e 9\n6: 1 a 10\ncol1 col2 col3 \n\"integer\" \"character\" \"factor\" \n[1] \"Modified DataTable\"\n col1 col2 col3\n1: 1 a 5\n2: 2 b 8\n3: 3 c 7\n4: 4 d 6\n5: 5 e 9\n6: 1 a 10\ncol1 col2 col3 \n\"factor\" \"factor\" \"factor\"" }, { "code": null, "e": 29772, "s": 29765, "text": "Picked" }, { "code": null, "e": 29784, "s": 29772, "text": "R DataTable" }, { "code": null, "e": 29795, "s": 29784, "text": "R Language" }, { "code": null, "e": 29806, "s": 29795, "text": "R Programs" }, { "code": null, "e": 29904, "s": 29806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29913, "s": 29904, "text": "Comments" }, { "code": null, "e": 29926, "s": 29913, "text": "Old Comments" }, { "code": null, "e": 29978, "s": 29926, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30016, "s": 29978, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30051, "s": 30016, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30109, "s": 30051, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30158, "s": 30109, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30216, "s": 30158, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30265, "s": 30216, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30308, "s": 30265, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30358, "s": 30308, "text": "How to filter R dataframe by multiple conditions?" } ]
Math.DivRem() Method in C#
The Math.DivRem() method in C# is used to divide and calculate the quotient of two numbers and also returns the remainder in an output parameter. public static int DivRem (int dividend, int divisor, out int remainder); public static long DivRem (long dividend, long divisor, long remainder); Let us now see an example to implement Math.DivRem() method − using System; public class Demo { public static void Main(){ int dividend = 30; int divisor = 7; int remainder; int quotient = Math.DivRem(dividend, divisor, out remainder); Console.WriteLine("Quotient = "+quotient); Console.WriteLine("Remainder = "+remainder); } } This will produce the following output − Quotient = 4 Remainder = 2 Let us see another example to implement Math.DivRem() method − using System; public class Demo { public static void Main(){ long dividend = 767676765765765; long divisor = 7; long remainder; long quotient = Math.DivRem(dividend, divisor, out remainder); Console.WriteLine("Quotient = "+quotient); Console.WriteLine("Remainder = "+remainder); } } This will produce the following output − Quotient = 109668109395109 Remainder = 2
[ { "code": null, "e": 1208, "s": 1062, "text": "The Math.DivRem() method in C# is used to divide and calculate the quotient of two numbers and also returns the remainder in an output parameter." }, { "code": null, "e": 1354, "s": 1208, "text": "public static int DivRem (int dividend, int divisor, out int remainder);\npublic static long DivRem (long dividend, long divisor, long remainder);" }, { "code": null, "e": 1416, "s": 1354, "text": "Let us now see an example to implement Math.DivRem() method −" }, { "code": null, "e": 1724, "s": 1416, "text": "using System;\npublic class Demo {\n public static void Main(){\n int dividend = 30;\n int divisor = 7;\n int remainder;\n int quotient = Math.DivRem(dividend, divisor, out remainder);\n Console.WriteLine(\"Quotient = \"+quotient);\n Console.WriteLine(\"Remainder = \"+remainder);\n }\n}" }, { "code": null, "e": 1765, "s": 1724, "text": "This will produce the following output −" }, { "code": null, "e": 1792, "s": 1765, "text": "Quotient = 4\nRemainder = 2" }, { "code": null, "e": 1855, "s": 1792, "text": "Let us see another example to implement Math.DivRem() method −" }, { "code": null, "e": 2180, "s": 1855, "text": "using System;\npublic class Demo {\n public static void Main(){\n long dividend = 767676765765765;\n long divisor = 7;\n long remainder;\n long quotient = Math.DivRem(dividend, divisor, out remainder);\n Console.WriteLine(\"Quotient = \"+quotient);\n Console.WriteLine(\"Remainder = \"+remainder);\n }\n}" }, { "code": null, "e": 2221, "s": 2180, "text": "This will produce the following output −" }, { "code": null, "e": 2262, "s": 2221, "text": "Quotient = 109668109395109\nRemainder = 2" } ]
numpy.swapaxes
This function interchanges the two axes of an array. For NumPy versions after 1.10, a view of the swapped array is returned. The function takes the following parameters. numpy.swapaxes(arr, axis1, axis2) Where, arr Input array whose axes are to be swapped axis1 An int corresponding to the first axis axis2 An int corresponding to the second axis # It creates a 3 dimensional ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print 'The original array:' print a print '\n' # now swap numbers between axis 0 (along depth) and axis 2 (along width) print 'The array after applying the swapaxes function:' print np.swapaxes(a, 2, 0) Its output would be as follows − The original array: [[[0 1] [2 3]] [[4 5] [6 7]]] The array after applying the swapaxes function: [[[0 4] [2 6]] [[1 5] [3 7]]] 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2413, "s": 2243, "text": "This function interchanges the two axes of an array. For NumPy versions after 1.10, a view of the swapped array is returned. The function takes the following parameters." }, { "code": null, "e": 2448, "s": 2413, "text": "numpy.swapaxes(arr, axis1, axis2)\n" }, { "code": null, "e": 2455, "s": 2448, "text": "Where," }, { "code": null, "e": 2459, "s": 2455, "text": "arr" }, { "code": null, "e": 2500, "s": 2459, "text": "Input array whose axes are to be swapped" }, { "code": null, "e": 2506, "s": 2500, "text": "axis1" }, { "code": null, "e": 2545, "s": 2506, "text": "An int corresponding to the first axis" }, { "code": null, "e": 2551, "s": 2545, "text": "axis2" }, { "code": null, "e": 2591, "s": 2551, "text": "An int corresponding to the second axis" }, { "code": null, "e": 2893, "s": 2591, "text": "# It creates a 3 dimensional ndarray \nimport numpy as np \na = np.arange(8).reshape(2,2,2) \n\nprint 'The original array:' \nprint a \nprint '\\n' \n# now swap numbers between axis 0 (along depth) and axis 2 (along width) \n\nprint 'The array after applying the swapaxes function:' \nprint np.swapaxes(a, 2, 0)" }, { "code": null, "e": 2926, "s": 2893, "text": "Its output would be as follows −" }, { "code": null, "e": 3067, "s": 2926, "text": "The original array:\n[[[0 1]\n [2 3]]\n\n [[4 5]\n [6 7]]]\n\nThe array after applying the swapaxes function:\n[[[0 4]\n [2 6]]\n \n [[1 5]\n [3 7]]]\n" }, { "code": null, "e": 3100, "s": 3067, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3117, "s": 3100, "text": " Abhilash Nelson" }, { "code": null, "e": 3150, "s": 3117, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 3185, "s": 3150, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3218, "s": 3185, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 3253, "s": 3218, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3288, "s": 3253, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3300, "s": 3288, "text": " Akbar Khan" }, { "code": null, "e": 3333, "s": 3300, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3348, "s": 3333, "text": " Pruthviraja L" }, { "code": null, "e": 3381, "s": 3348, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3388, "s": 3381, "text": " Anmol" }, { "code": null, "e": 3395, "s": 3388, "text": " Print" }, { "code": null, "e": 3406, "s": 3395, "text": " Add Notes" } ]
Matplotlib - PyLab module
PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib. PyLab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and NumPy (for Mathematics and working with arrays) in a single name space. Although many examples use PyLab, it is no longer recommended. Plotting curves is done with the plot command. It takes a pair of same-length arrays (or sequences) − from numpy import * from pylab import * x = linspace(-3, 3, 30) y = x**2 plot(x, y) show() The above line of code generates the following output − To plot symbols rather than lines, provide an additional string argument. Now, consider executing the following code − from pylab import * x = linspace(-3, 3, 30) y = x**2 plot(x, y, 'r.') show() It plots the red dots as shown below − Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the plot. from pylab import * plot(x, sin(x)) plot(x, cos(x), 'r-') plot(x, -sin(x), 'g--') show() The above line of code generates the following output − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2742, "s": 2516, "text": "PyLab is a procedural interface to the Matplotlib object-oriented plotting library. Matplotlib is the whole package; matplotlib.pyplot is a module in Matplotlib; and PyLab is a module that gets installed alongside Matplotlib." }, { "code": null, "e": 2962, "s": 2742, "text": "PyLab is a convenience module that bulk imports matplotlib.pyplot (for plotting) and NumPy (for Mathematics and working with arrays) in a single name space. Although many examples use PyLab, it is no longer recommended." }, { "code": null, "e": 3064, "s": 2962, "text": "Plotting curves is done with the plot command. It takes a pair of same-length arrays (or sequences) −" }, { "code": null, "e": 3155, "s": 3064, "text": "from numpy import *\nfrom pylab import *\nx = linspace(-3, 3, 30)\ny = x**2\nplot(x, y)\nshow()" }, { "code": null, "e": 3211, "s": 3155, "text": "The above line of code generates the following output −" }, { "code": null, "e": 3285, "s": 3211, "text": "To plot symbols rather than lines, provide an additional string argument." }, { "code": null, "e": 3330, "s": 3285, "text": "Now, consider executing the following code −" }, { "code": null, "e": 3407, "s": 3330, "text": "from pylab import *\nx = linspace(-3, 3, 30)\ny = x**2\nplot(x, y, 'r.')\nshow()" }, { "code": null, "e": 3446, "s": 3407, "text": "It plots the red dots as shown below −" }, { "code": null, "e": 3535, "s": 3446, "text": "Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the plot." }, { "code": null, "e": 3624, "s": 3535, "text": "from pylab import *\nplot(x, sin(x))\nplot(x, cos(x), 'r-')\nplot(x, -sin(x), 'g--')\nshow()" }, { "code": null, "e": 3680, "s": 3624, "text": "The above line of code generates the following output −" }, { "code": null, "e": 3713, "s": 3680, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3730, "s": 3713, "text": " Abhilash Nelson" }, { "code": null, "e": 3763, "s": 3730, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3798, "s": 3763, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3832, "s": 3798, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3867, "s": 3832, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3900, "s": 3867, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 3910, "s": 3900, "text": " Aipython" }, { "code": null, "e": 3945, "s": 3910, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3957, "s": 3945, "text": " Akbar Khan" }, { "code": null, "e": 3990, "s": 3957, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3997, "s": 3990, "text": " Anmol" }, { "code": null, "e": 4004, "s": 3997, "text": " Print" }, { "code": null, "e": 4015, "s": 4004, "text": " Add Notes" } ]
Java Applet | How to display a Digital Clock
14 Dec, 2021 In this article, we shall be animating the applet window with a 1-second delay. The idea is to display the system time of every instance. Approach: Here 6 seven-segment displays are created using the Java Applet library to print the system time in HH:MM:SS format. Each segment of the seven-segment display, numbered as follows can be lit in different combinations to represent the numbers 0-9. We have 6 seven-segment display for displaying the time in HH:MM:SS pattern. Each segment numbered as the following can be lit in different combinations to represent the numbers 0-9. We can assume every single segment as 1 bit so (0-9) 10 number can make 10 different combinations. e.g. if we want to display 0 we should lit-up the segments 0, 1, 2, 3, 4, 5. So this combination will make the number (2^0 | 2^1 | 2^2 | 2^3 | 2^4 | 2^5) = 63. Below is the implementation of the above approach: Java // Java program to illustrate// digital clock using Applets import java.applet.Applet;import java.awt.*;import java.util.*; public class digitalClock extends Applet { @Override public void init() { // Applet window size this.setSize(new Dimension(800, 400)); setBackground(Color.white); new Thread() { @Override public void run() { while (true) { repaint(); delayAnimation(); } } }.start(); } // Animating the applet private void delayAnimation() { try { // Animation delay is 1000 milliseconds Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Function that receive segment combination value // for each digit, position of the display public void display(int val, int pos, Graphics g) { // lit-up the i-th segment // 0-th segment if ((val & 1) != 0) g.fillRect(pos, 150, 5, 50); // 1-st segment if ((val & 2) != 0) g.fillRect(pos, 145, 50, 5); // 2-nd segment if ((val & 4) != 0) g.fillRect(pos + 45, 150, 5, 50); // 3-rd segment if ((val & 8) != 0) g.fillRect(pos + 45, 200, 5, 50); // 4-th segment if ((val & 16) != 0) g.fillRect(pos, 250, 50, 5); // 5-th segment if ((val & 32) != 0) g.fillRect(pos, 200, 5, 50); // 6-th segment if ((val & 64) != 0) g.fillRect(pos + 5, 200, 40, 5); } // Paint the applet @Override public void paint(Graphics g) { // Combination values of different digits int[] digits = new int[] { 63, 12, 118, 94, 77, 91, 123, 14, 127, 95 }; // Get the system time Calendar time = Calendar.getInstance(); int hour = time.get(Calendar.HOUR_OF_DAY); int minute = time.get(Calendar.MINUTE); int second = time.get(Calendar.SECOND); // Deciding AM/PM int am = 1; if (hour > 12) { hour -= 12; am = 0; } // Display hour // tens digit display(digits[hour / 10], 150, g); // units digit display(digits[hour % 10], 225, g); // Display minute // tens digit display(digits[minute / 10], 325, g); // units digit display(digits[minute % 10], 400, g); // Display second // tens digit display(digits[second / 10], 500, g); // units digit display(digits[second % 10], 575, g); // Display AM/PM if (am == 1) g.drawString("am", 650, 250); else g.drawString("pm", 650, 250); // Display ratio signs g.fillRect(300, 175, 5, 5); g.fillRect(300, 225, 5, 5); g.fillRect(475, 175, 5, 5); g.fillRect(475, 225, 5, 5); }} Output: simmytarika5 java-applet Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Dec, 2021" }, { "code": null, "e": 166, "s": 28, "text": "In this article, we shall be animating the applet window with a 1-second delay. The idea is to display the system time of every instance." }, { "code": null, "e": 423, "s": 166, "text": "Approach: Here 6 seven-segment displays are created using the Java Applet library to print the system time in HH:MM:SS format. Each segment of the seven-segment display, numbered as follows can be lit in different combinations to represent the numbers 0-9." }, { "code": null, "e": 606, "s": 423, "text": "We have 6 seven-segment display for displaying the time in HH:MM:SS pattern. Each segment numbered as the following can be lit in different combinations to represent the numbers 0-9." }, { "code": null, "e": 866, "s": 606, "text": "We can assume every single segment as 1 bit so (0-9) 10 number can make 10 different combinations. e.g. if we want to display 0 we should lit-up the segments 0, 1, 2, 3, 4, 5. So this combination will make the number (2^0 | 2^1 | 2^2 | 2^3 | 2^4 | 2^5) = 63. " }, { "code": null, "e": 917, "s": 866, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 922, "s": 917, "text": "Java" }, { "code": "// Java program to illustrate// digital clock using Applets import java.applet.Applet;import java.awt.*;import java.util.*; public class digitalClock extends Applet { @Override public void init() { // Applet window size this.setSize(new Dimension(800, 400)); setBackground(Color.white); new Thread() { @Override public void run() { while (true) { repaint(); delayAnimation(); } } }.start(); } // Animating the applet private void delayAnimation() { try { // Animation delay is 1000 milliseconds Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // Function that receive segment combination value // for each digit, position of the display public void display(int val, int pos, Graphics g) { // lit-up the i-th segment // 0-th segment if ((val & 1) != 0) g.fillRect(pos, 150, 5, 50); // 1-st segment if ((val & 2) != 0) g.fillRect(pos, 145, 50, 5); // 2-nd segment if ((val & 4) != 0) g.fillRect(pos + 45, 150, 5, 50); // 3-rd segment if ((val & 8) != 0) g.fillRect(pos + 45, 200, 5, 50); // 4-th segment if ((val & 16) != 0) g.fillRect(pos, 250, 50, 5); // 5-th segment if ((val & 32) != 0) g.fillRect(pos, 200, 5, 50); // 6-th segment if ((val & 64) != 0) g.fillRect(pos + 5, 200, 40, 5); } // Paint the applet @Override public void paint(Graphics g) { // Combination values of different digits int[] digits = new int[] { 63, 12, 118, 94, 77, 91, 123, 14, 127, 95 }; // Get the system time Calendar time = Calendar.getInstance(); int hour = time.get(Calendar.HOUR_OF_DAY); int minute = time.get(Calendar.MINUTE); int second = time.get(Calendar.SECOND); // Deciding AM/PM int am = 1; if (hour > 12) { hour -= 12; am = 0; } // Display hour // tens digit display(digits[hour / 10], 150, g); // units digit display(digits[hour % 10], 225, g); // Display minute // tens digit display(digits[minute / 10], 325, g); // units digit display(digits[minute % 10], 400, g); // Display second // tens digit display(digits[second / 10], 500, g); // units digit display(digits[second % 10], 575, g); // Display AM/PM if (am == 1) g.drawString(\"am\", 650, 250); else g.drawString(\"pm\", 650, 250); // Display ratio signs g.fillRect(300, 175, 5, 5); g.fillRect(300, 225, 5, 5); g.fillRect(475, 175, 5, 5); g.fillRect(475, 225, 5, 5); }}", "e": 4062, "s": 922, "text": null }, { "code": null, "e": 4071, "s": 4062, "text": "Output: " }, { "code": null, "e": 4084, "s": 4071, "text": "simmytarika5" }, { "code": null, "e": 4096, "s": 4084, "text": "java-applet" }, { "code": null, "e": 4101, "s": 4096, "text": "Java" }, { "code": null, "e": 4115, "s": 4101, "text": "Java Programs" }, { "code": null, "e": 4120, "s": 4115, "text": "Java" } ]
Python – Remove Duplicate Dictionaries characterized by Key
01 Aug, 2020 Given a list of dictionaries, remove all the dictionaries which are duplicate with respect to K key. Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 10}, {“Gfg” : 2, “is” : 16, “best” : 10}], K = “best”Output : [{“Gfg” : 6, “is” : 9, “best” : 10}]Explanation : All keys have 10 value, only 1st record is retained. Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}], K = “best”Output : [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}]Explanation : All values of “best” are unique, hence no removal of dictionaries. Method : Using loop This is brute way in which this task can be performed. In this, we iterate for each dictionary and memoize the Key, if similar key’s same value occur, then that dictionary is avoided in resultant list of dictionaries. Python3 # Python3 code to demonstrate working of # Remove Duplicate Dictionaries characterized by Key# Using loop # initializing liststest_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 2, "is" : 16, "best" : 10}, {"Gfg" : 12, "is" : 1, "best" : 8}, {"Gfg" : 22, "is" : 6, "best" : 8}] # printing original listprint("The original list : " + str(test_list)) # initializing Key K = "best" memo = set()res = []for sub in test_list: # testing for already present value if sub[K] not in memo: res.append(sub) # adding in memo if new value memo.add(sub[K]) # printing result print("The filtered list : " + str(res)) The original list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 2, ‘is’: 16, ‘best’: 10}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}, {‘Gfg’: 22, ‘is’: 6, ‘best’: 8}]The filtered list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 129, "s": 28, "text": "Given a list of dictionaries, remove all the dictionaries which are duplicate with respect to K key." }, { "code": null, "e": 383, "s": 129, "text": "Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 10}, {“Gfg” : 2, “is” : 16, “best” : 10}], K = “best”Output : [{“Gfg” : 6, “is” : 9, “best” : 10}]Explanation : All keys have 10 value, only 1st record is retained." }, { "code": null, "e": 725, "s": 383, "text": "Input : test_list = [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}], K = “best”Output : [{“Gfg” : 6, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 12}, {“Gfg” : 2, “is” : 16, “best” : 15}]Explanation : All values of “best” are unique, hence no removal of dictionaries." }, { "code": null, "e": 746, "s": 725, "text": "Method : Using loop " }, { "code": null, "e": 964, "s": 746, "text": "This is brute way in which this task can be performed. In this, we iterate for each dictionary and memoize the Key, if similar key’s same value occur, then that dictionary is avoided in resultant list of dictionaries." }, { "code": null, "e": 972, "s": 964, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Remove Duplicate Dictionaries characterized by Key# Using loop # initializing liststest_list = [{\"Gfg\" : 6, \"is\" : 9, \"best\" : 10}, {\"Gfg\" : 8, \"is\" : 11, \"best\" : 19}, {\"Gfg\" : 2, \"is\" : 16, \"best\" : 10}, {\"Gfg\" : 12, \"is\" : 1, \"best\" : 8}, {\"Gfg\" : 22, \"is\" : 6, \"best\" : 8}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing Key K = \"best\" memo = set()res = []for sub in test_list: # testing for already present value if sub[K] not in memo: res.append(sub) # adding in memo if new value memo.add(sub[K]) # printing result print(\"The filtered list : \" + str(res))", "e": 1718, "s": 972, "text": null }, { "code": null, "e": 2026, "s": 1718, "text": "The original list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 2, ‘is’: 16, ‘best’: 10}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}, {‘Gfg’: 22, ‘is’: 6, ‘best’: 8}]The filtered list : [{‘Gfg’: 6, ‘is’: 9, ‘best’: 10}, {‘Gfg’: 8, ‘is’: 11, ‘best’: 19}, {‘Gfg’: 12, ‘is’: 1, ‘best’: 8}]" }, { "code": null, "e": 2053, "s": 2026, "text": "Python dictionary-programs" }, { "code": null, "e": 2060, "s": 2053, "text": "Python" }, { "code": null, "e": 2076, "s": 2060, "text": "Python Programs" }, { "code": null, "e": 2174, "s": 2076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2206, "s": 2174, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2233, "s": 2206, "text": "Python Classes and Objects" }, { "code": null, "e": 2254, "s": 2233, "text": "Python OOPs Concepts" }, { "code": null, "e": 2277, "s": 2254, "text": "Introduction To PYTHON" }, { "code": null, "e": 2333, "s": 2277, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2355, "s": 2333, "text": "Defaultdict in Python" }, { "code": null, "e": 2394, "s": 2355, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2432, "s": 2394, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2469, "s": 2432, "text": "Python Program for Fibonacci numbers" } ]
Vue.js | v-text directive
25 Jun, 2020 The v-text directive is a Vue.js directive used to update a element’s textContent with our data. It is just a nice alternative to Mustache syntax. First, we will create a div element with id as app and let’s apply the v-text directive to this element with data as a message. Now we will create this message by initializing a Vue instance the data attribute containing our message. Syntax: v-text="data" Parameters: This directive accepts a single parameter which is the data.Example: This example uses VueJS to update the text of a element with v-text. HTML <!DOCTYPE html><html> <head> <title> VueJS | v-text directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script> </script></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-text directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div v-text="message" id="app"> </div> </div> <script> var app = new Vue({ el: '#app', data: { message: 'Hello this is GeeksforGeeks.' } }) </script></body> </html> Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2020" }, { "code": null, "e": 409, "s": 28, "text": "The v-text directive is a Vue.js directive used to update a element’s textContent with our data. It is just a nice alternative to Mustache syntax. First, we will create a div element with id as app and let’s apply the v-text directive to this element with data as a message. Now we will create this message by initializing a Vue instance the data attribute containing our message." }, { "code": null, "e": 418, "s": 409, "text": "Syntax: " }, { "code": null, "e": 433, "s": 418, "text": "v-text=\"data\"\n" }, { "code": null, "e": 584, "s": 433, "text": "Parameters: This directive accepts a single parameter which is the data.Example: This example uses VueJS to update the text of a element with v-text. " }, { "code": null, "e": 589, "s": 584, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS | v-text directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script> </script></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-text directive </b> </div> <div id=\"canvas\" style=\"border:1px solid #000000; width: 600px;height: 200px;\"> <div v-text=\"message\" id=\"app\"> </div> </div> <script> var app = new Vue({ el: '#app', data: { message: 'Hello this is GeeksforGeeks.' } }) </script></body> </html> ", "e": 1379, "s": 589, "text": null }, { "code": null, "e": 1388, "s": 1379, "text": "Output: " }, { "code": null, "e": 1395, "s": 1388, "text": "Vue.JS" }, { "code": null, "e": 1406, "s": 1395, "text": "JavaScript" }, { "code": null, "e": 1423, "s": 1406, "text": "Web Technologies" }, { "code": null, "e": 1521, "s": 1423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1582, "s": 1521, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1654, "s": 1582, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1694, "s": 1654, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1736, "s": 1694, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1777, "s": 1736, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1810, "s": 1777, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1872, "s": 1810, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1933, "s": 1872, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1983, "s": 1933, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find all combinations that add upto given number
31 Mar, 2021 Given a positive number, find out all combinations of positive numbers that adds upto that number. The program should print only combinations, not permutations. For example, for input 3, either 1, 2 or 2, 1 should be printed.Examples : Input: N = 3 Output: 1 1 1 1 2 3 Input: N = 5 Output: 1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 1 4 2 3 5 We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. We use an array to store combinations and we recursively fill the array and recurse with reduced number. The invariant used in the solution is that each combination will always be stored in increasing order of elements involved. That way we can avoid printing permutations.Below is implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to find out all combinations of// positive numbers that add upto given number#include <iostream>using namespace std; /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */void findCombinationsUtil(int arr[], int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) cout << arr[i] << " "; cout << endl; return; } // Find the previous number stored in arr[] // It helps in maintaining increasing order int prev = (index == 0)? 1 : arr[index-1]; // note loop starts from previous number // i.e. at array location index - 1 for (int k = prev; k <= num ; k++) { // next element of array is k arr[index] = k; // call recursively with reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out all combinations of positive numbers that add upto given number. It uses findCombinationsUtil() */void findCombinations(int n){ // array to store the combinations // It can contain max n elements int arr[n]; //find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codeint main(){ int n = 5; findCombinations(n); return 0;} // Java program to find out// all combinations of positive// numbers that add upto given// numberimport java.io.*; class GFG{ /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */static void findCombinationsUtil(int arr[], int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) System.out.print (arr[i] + " "); System.out.println(); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order int prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (int k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){ // array to store the combinations // It can contain max n elements int arr[] = new int [n]; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codepublic static void main (String[] args){ int n = 5; findCombinations(n);}} // This code is contributed// by akt_mit # Python3 program to find out all# combinations of positive# numbers that add upto given number # arr - array to store the combination# index - next location in array# num - given number# reducedNum - reduced numberdef findCombinationsUtil(arr, index, num, reducedNum): # Base condition if (reducedNum < 0): return # If combination is # found, print it if (reducedNum == 0): for i in range(index): print(arr[i], end = " ") print("") return # Find the previous number stored in arr[]. # It helps in maintaining increasing order prev = 1 if(index == 0) else arr[index - 1] # note loop starts from previous # number i.e. at array location # index - 1 for k in range(prev, num + 1): # next element of array is k arr[index] = k # call recursively with # reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k) # Function to find out all# combinations of positive numbers# that add upto given number.# It uses findCombinationsUtil()def findCombinations(n): # array to store the combinations # It can contain max n elements arr = [0] * n # find all combinations findCombinationsUtil(arr, 0, n, n) # Driver coden = 5;findCombinations(n); # This code is contributed by mits // C# program to find out all// combinations of positive numbers// that add upto given numberusing System; class GFG{ /* arr - array to store thecombinationindex - next location in arraynum - given numberreducedNum - reduced number */static void findCombinationsUtil(int []arr, int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) Console.Write (arr[i] + " "); Console.WriteLine(); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order int prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (int k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){ // array to store the combinations // It can contain max n elements int []arr = new int [n]; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codestatic public void Main (){ int n = 5; findCombinations(n);}} // This code is contributed// by akt_mit <?php// PHP program to find out all// combinations of positive// numbers that add upto given number /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */function findCombinationsUtil($arr, $index, $num, $reducedNum){ // Base condition if ($reducedNum < 0) return; // If combination is // found, print it if ($reducedNum == 0) { for ($i = 0; $i < $index; $i++) echo $arr[$i] , " "; echo "\n"; return; } // Find the previous number // stored in arr[] It helps // in maintaining increasing order $prev = ($index == 0) ? 1 : $arr[$index - 1]; // note loop starts from previous // number i.e. at array location // index - 1 for ($k = $prev; $k <= $num ; $k++) { // next element of array is k $arr[$index] = $k; // call recursively with // reduced number findCombinationsUtil($arr, $index + 1, $num, $reducedNum - $k); }} /* Function to find out allcombinations of positive numbersthat add upto given number.It uses findCombinationsUtil() */function findCombinations($n){ // array to store the combinations // It can contain max n elements $arr = array(); //find all combinations findCombinationsUtil($arr, 0, $n, $n);} // Driver code$n = 5;findCombinations($n); // This code is contributed by ajit?> <script> // Javascript program to find out// all combinations of positive// numbers that add upto given// number /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */function findCombinationsUtil(arr, index, num, reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (let i = 0; i < index; i++) document.write (arr[i] + " "); document.write("<br/>"); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order let prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (let k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */function findCombinations(n){ // array to store the combinations // It can contain max n elements let arr = []; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver Code let n = 5; findCombinations(n); </script> Output : 1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 1 4 2 3 5 Exercise : Modify above solution to consider only distinct elements in a combination.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t Mithun Kumar sksyp souravghosh0416 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Find minimum number of coins that make a given value Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Mar, 2021" }, { "code": null, "e": 289, "s": 52, "text": "Given a positive number, find out all combinations of positive numbers that adds upto that number. The program should print only combinations, not permutations. For example, for input 3, either 1, 2 or 2, 1 should be printed.Examples : " }, { "code": null, "e": 385, "s": 289, "text": "Input: N = 3\nOutput:\n1 1 1\n1 2\n3\n\nInput: N = 5\nOutput:\n1 1 1 1 1\n1 1 1 2\n1 1 3\n1 2 2\n1 4\n2 3\n5 " }, { "code": null, "e": 809, "s": 385, "text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. We use an array to store combinations and we recursively fill the array and recurse with reduced number. The invariant used in the solution is that each combination will always be stored in increasing order of elements involved. That way we can avoid printing permutations.Below is implementation of above idea : " }, { "code": null, "e": 813, "s": 809, "text": "C++" }, { "code": null, "e": 818, "s": 813, "text": "Java" }, { "code": null, "e": 826, "s": 818, "text": "Python3" }, { "code": null, "e": 829, "s": 826, "text": "C#" }, { "code": null, "e": 833, "s": 829, "text": "PHP" }, { "code": null, "e": 844, "s": 833, "text": "Javascript" }, { "code": "// C++ program to find out all combinations of// positive numbers that add upto given number#include <iostream>using namespace std; /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */void findCombinationsUtil(int arr[], int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) cout << arr[i] << \" \"; cout << endl; return; } // Find the previous number stored in arr[] // It helps in maintaining increasing order int prev = (index == 0)? 1 : arr[index-1]; // note loop starts from previous number // i.e. at array location index - 1 for (int k = prev; k <= num ; k++) { // next element of array is k arr[index] = k; // call recursively with reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out all combinations of positive numbers that add upto given number. It uses findCombinationsUtil() */void findCombinations(int n){ // array to store the combinations // It can contain max n elements int arr[n]; //find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codeint main(){ int n = 5; findCombinations(n); return 0;}", "e": 2318, "s": 844, "text": null }, { "code": "// Java program to find out// all combinations of positive// numbers that add upto given// numberimport java.io.*; class GFG{ /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */static void findCombinationsUtil(int arr[], int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) System.out.print (arr[i] + \" \"); System.out.println(); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order int prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (int k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){ // array to store the combinations // It can contain max n elements int arr[] = new int [n]; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codepublic static void main (String[] args){ int n = 5; findCombinations(n);}} // This code is contributed// by akt_mit", "e": 3977, "s": 2318, "text": null }, { "code": "# Python3 program to find out all# combinations of positive# numbers that add upto given number # arr - array to store the combination# index - next location in array# num - given number# reducedNum - reduced numberdef findCombinationsUtil(arr, index, num, reducedNum): # Base condition if (reducedNum < 0): return # If combination is # found, print it if (reducedNum == 0): for i in range(index): print(arr[i], end = \" \") print(\"\") return # Find the previous number stored in arr[]. # It helps in maintaining increasing order prev = 1 if(index == 0) else arr[index - 1] # note loop starts from previous # number i.e. at array location # index - 1 for k in range(prev, num + 1): # next element of array is k arr[index] = k # call recursively with # reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k) # Function to find out all# combinations of positive numbers# that add upto given number.# It uses findCombinationsUtil()def findCombinations(n): # array to store the combinations # It can contain max n elements arr = [0] * n # find all combinations findCombinationsUtil(arr, 0, n, n) # Driver coden = 5;findCombinations(n); # This code is contributed by mits", "e": 5366, "s": 3977, "text": null }, { "code": "// C# program to find out all// combinations of positive numbers// that add upto given numberusing System; class GFG{ /* arr - array to store thecombinationindex - next location in arraynum - given numberreducedNum - reduced number */static void findCombinationsUtil(int []arr, int index, int num, int reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (int i = 0; i < index; i++) Console.Write (arr[i] + \" \"); Console.WriteLine(); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order int prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (int k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){ // array to store the combinations // It can contain max n elements int []arr = new int [n]; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver codestatic public void Main (){ int n = 5; findCombinations(n);}} // This code is contributed// by akt_mit", "e": 6977, "s": 5366, "text": null }, { "code": "<?php// PHP program to find out all// combinations of positive// numbers that add upto given number /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */function findCombinationsUtil($arr, $index, $num, $reducedNum){ // Base condition if ($reducedNum < 0) return; // If combination is // found, print it if ($reducedNum == 0) { for ($i = 0; $i < $index; $i++) echo $arr[$i] , \" \"; echo \"\\n\"; return; } // Find the previous number // stored in arr[] It helps // in maintaining increasing order $prev = ($index == 0) ? 1 : $arr[$index - 1]; // note loop starts from previous // number i.e. at array location // index - 1 for ($k = $prev; $k <= $num ; $k++) { // next element of array is k $arr[$index] = $k; // call recursively with // reduced number findCombinationsUtil($arr, $index + 1, $num, $reducedNum - $k); }} /* Function to find out allcombinations of positive numbersthat add upto given number.It uses findCombinationsUtil() */function findCombinations($n){ // array to store the combinations // It can contain max n elements $arr = array(); //find all combinations findCombinationsUtil($arr, 0, $n, $n);} // Driver code$n = 5;findCombinations($n); // This code is contributed by ajit?>", "e": 8450, "s": 6977, "text": null }, { "code": "<script> // Javascript program to find out// all combinations of positive// numbers that add upto given// number /* arr - array to store the combination index - next location in array num - given number reducedNum - reduced number */function findCombinationsUtil(arr, index, num, reducedNum){ // Base condition if (reducedNum < 0) return; // If combination is // found, print it if (reducedNum == 0) { for (let i = 0; i < index; i++) document.write (arr[i] + \" \"); document.write(\"<br/>\"); return; } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order let prev = (index == 0) ? 1 : arr[index - 1]; // note loop starts from // previous number i.e. at // array location index - 1 for (let k = prev; k <= num ; k++) { // next element of // array is k arr[index] = k; // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k); }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */function findCombinations(n){ // array to store the combinations // It can contain max n elements let arr = []; // find all combinations findCombinationsUtil(arr, 0, n, n);} // Driver Code let n = 5; findCombinations(n); </script>", "e": 10019, "s": 8450, "text": null }, { "code": null, "e": 10029, "s": 10019, "text": "Output : " }, { "code": null, "e": 10076, "s": 10029, "text": "1 1 1 1 1 \n1 1 1 2 \n1 1 3 \n1 2 2 \n1 4 \n2 3 \n5 " }, { "code": null, "e": 10550, "s": 10076, "text": "Exercise : Modify above solution to consider only distinct elements in a combination.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10556, "s": 10550, "text": "jit_t" }, { "code": null, "e": 10569, "s": 10556, "text": "Mithun Kumar" }, { "code": null, "e": 10575, "s": 10569, "text": "sksyp" }, { "code": null, "e": 10591, "s": 10575, "text": "souravghosh0416" }, { "code": null, "e": 10604, "s": 10591, "text": "Mathematical" }, { "code": null, "e": 10617, "s": 10604, "text": "Mathematical" }, { "code": null, "e": 10715, "s": 10617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10739, "s": 10715, "text": "Merge two sorted arrays" }, { "code": null, "e": 10760, "s": 10739, "text": "Operators in C / C++" }, { "code": null, "e": 10774, "s": 10760, "text": "Prime Numbers" }, { "code": null, "e": 10811, "s": 10774, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10854, "s": 10811, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 10886, "s": 10854, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 10939, "s": 10886, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 10966, "s": 10939, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 11009, "s": 10966, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Convert a Roman Number to Decimal using Hashmap in Java
30 Mar, 2022 Given a Roman numeral, the task is to find the corresponding decimal value. Note: Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M. Examples: Input: “III” Output: 3 Input: “MDCCLX” Output: 1760 Approach: Loop through each character in the string containing the Roman numerals.Compare the value of the current roman symbol with the value of the roman symbol to its right. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total. Loop through each character in the string containing the Roman numerals. Compare the value of the current roman symbol with the value of the roman symbol to its right. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total. Below is the implementation of the above approach: Java // Java Program to Convert a Roman// Number to Decimal using Hashmapimport java.io.*;import java.util.Scanner;import java.util.HashMap;class solution { int romanToInt(String s) { // Create a empty hash map. HashMap<Character, Integer> map = new HashMap<>(); // Putting value in hash map. map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); // Creating integer variable to store result. int result = 0; // initialize loop to iterate in string. for (int i = 0; i < s.length(); i++) { // Checking that current element // is not smaller then previous if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) { result += map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1)); } else { result += map.get(s.charAt(i)); } } // Returning the integer value of Roman number. return result; }}public class GFG { public static void main(String[] args) { String s; // Scanner sc = new Scanner(System.in); // s = sc.nextLine(); solution gfg = new solution(); System.out.println(gfg.romanToInt("MDCCLX")); }} Output: 1760 Time Complexity: O(N) Auxiliary Space: O(1) rohitsingh07052 Java-HashMap Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Mar, 2022" }, { "code": null, "e": 128, "s": 52, "text": "Given a Roman numeral, the task is to find the corresponding decimal value." }, { "code": null, "e": 218, "s": 128, "text": "Note: Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M." }, { "code": null, "e": 228, "s": 218, "text": "Examples:" }, { "code": null, "e": 241, "s": 228, "text": "Input: “III”" }, { "code": null, "e": 251, "s": 241, "text": "Output: 3" }, { "code": null, "e": 267, "s": 251, "text": "Input: “MDCCLX”" }, { "code": null, "e": 280, "s": 267, "text": "Output: 1760" }, { "code": null, "e": 290, "s": 280, "text": "Approach:" }, { "code": null, "e": 716, "s": 290, "text": "Loop through each character in the string containing the Roman numerals.Compare the value of the current roman symbol with the value of the roman symbol to its right. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total." }, { "code": null, "e": 789, "s": 716, "text": "Loop through each character in the string containing the Roman numerals." }, { "code": null, "e": 1143, "s": 789, "text": "Compare the value of the current roman symbol with the value of the roman symbol to its right. If the current value is greater than or equal to the value of the symbol to the right, add the current symbol’s value to the total. If the current value is smaller than the value of the symbol to the right, subtract the current symbol’s value from the total." }, { "code": null, "e": 1194, "s": 1143, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1199, "s": 1194, "text": "Java" }, { "code": "// Java Program to Convert a Roman// Number to Decimal using Hashmapimport java.io.*;import java.util.Scanner;import java.util.HashMap;class solution { int romanToInt(String s) { // Create a empty hash map. HashMap<Character, Integer> map = new HashMap<>(); // Putting value in hash map. map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); // Creating integer variable to store result. int result = 0; // initialize loop to iterate in string. for (int i = 0; i < s.length(); i++) { // Checking that current element // is not smaller then previous if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) { result += map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1)); } else { result += map.get(s.charAt(i)); } } // Returning the integer value of Roman number. return result; }}public class GFG { public static void main(String[] args) { String s; // Scanner sc = new Scanner(System.in); // s = sc.nextLine(); solution gfg = new solution(); System.out.println(gfg.romanToInt(\"MDCCLX\")); }}", "e": 2613, "s": 1199, "text": null }, { "code": null, "e": 2621, "s": 2613, "text": "Output:" }, { "code": null, "e": 2626, "s": 2621, "text": "1760" }, { "code": null, "e": 2648, "s": 2626, "text": "Time Complexity: O(N)" }, { "code": null, "e": 2670, "s": 2648, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2686, "s": 2670, "text": "rohitsingh07052" }, { "code": null, "e": 2699, "s": 2686, "text": "Java-HashMap" }, { "code": null, "e": 2704, "s": 2699, "text": "Java" }, { "code": null, "e": 2718, "s": 2704, "text": "Java Programs" }, { "code": null, "e": 2723, "s": 2718, "text": "Java" }, { "code": null, "e": 2821, "s": 2723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2836, "s": 2821, "text": "Stream In Java" }, { "code": null, "e": 2857, "s": 2836, "text": "Introduction to Java" }, { "code": null, "e": 2878, "s": 2857, "text": "Constructors in Java" }, { "code": null, "e": 2897, "s": 2878, "text": "Exceptions in Java" }, { "code": null, "e": 2914, "s": 2897, "text": "Generics in Java" }, { "code": null, "e": 2940, "s": 2914, "text": "Java Programming Examples" }, { "code": null, "e": 2974, "s": 2940, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3021, "s": 2974, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3059, "s": 3021, "text": "Factory method design pattern in Java" } ]
Python | Visualizing image in different color spaces
06 Jun, 2018 OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc. Let’s discuss different ways to visualize images where we will represent images in different formats like grayscale, RGB scale, Hot_map, edge map, Spectral map, etc. RGB image is represented by linear combination of 3 different channels which are R(Red), G(Green) and B(Blue). Pixel intensities in this color space are represented by values ranging from 0 to 255 for single channel. Thus, number of possibilities for one color represented by a pixel is 16 million approximately [255 x 255 x 255 ]. # Python program to read image as RGB # Importing cv2 and matplotlib moduleimport cv2import matplotlib.pyplot as plt # reads image as RGBimg = cv2.imread('g4g.png') # shows the imageplt.imshow(img) Output : Grayscale image contains only single channel. Pixel intensities in this color space is represented by values ranging from 0 to 255. Thus, number of possibilities for one color represented by a pixel is 256. # Python program to read image as GrayScale # Importing cv2 moduleimport cv2 # Reads image as gray scaleimg = cv2.imread('g4g.png', 0) # We can alternatively convert# image by using cv2colorimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() Output : Y represents Luminance or Luma component, Cb and Cr are Chroma components. Cb represents the blue-difference (difference of blue component and Luma Component). Cr represents the red-difference (difference of red component and Luma Component). # Python program to read image# as YCrCb color space # Import cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Convert to YCrCb color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() Output : H : Hue represents dominant wavelength.S : Saturation represents shades of color.V : Value represents Intensity. # Python program to read image# as HSV color space # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Converts to HSV color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() Output : L – Represents Lightness.A – Color component ranging from Green to Magenta.B – Color component ranging from Blue to Yellow. # Python program to read image# as LAB color space # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Converts to LAB color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() Output : Edge map can be obtained by various filters like laplacian, sobel, etc. Here, we use Laplacian to generate edge map. # Python program to read image# as EdgeMap # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') laplacian = cv2.Laplacian(img, cv2.CV_64F)cv2.imshow('EdgeMap', laplacian) cv2.waitKey(0) cv2.destroyAllWindows() Output : In Heat map representation, individual values contained in a matrix are represented as colors. # Python program to visualize # Heat map of image # Importing matplotlib and cv2import matplotlib.pyplot as pltimport cv2 # reads the imageimg = cv2.imread('g4g.png') # plot heat map imageplt.imshow(img, cmap ='hot') Output : Spectral Image map obtains the spectrum for each pixel in the image of a scene. # Python program to visualize # Spectral map of image # Importing matplotlib and cv2import matplotlib.pyplot as pltimport cv2 img = cv2.imread('g4g.png')plt.imshow(img, cmap ='nipy_spectral') Output : Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2018" }, { "code": null, "e": 421, "s": 52, "text": "OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc." }, { "code": null, "e": 587, "s": 421, "text": "Let’s discuss different ways to visualize images where we will represent images in different formats like grayscale, RGB scale, Hot_map, edge map, Spectral map, etc." }, { "code": null, "e": 919, "s": 587, "text": "RGB image is represented by linear combination of 3 different channels which are R(Red), G(Green) and B(Blue). Pixel intensities in this color space are represented by values ranging from 0 to 255 for single channel. Thus, number of possibilities for one color represented by a pixel is 16 million approximately [255 x 255 x 255 ]." }, { "code": "# Python program to read image as RGB # Importing cv2 and matplotlib moduleimport cv2import matplotlib.pyplot as plt # reads image as RGBimg = cv2.imread('g4g.png') # shows the imageplt.imshow(img)", "e": 1120, "s": 919, "text": null }, { "code": null, "e": 1129, "s": 1120, "text": "Output :" }, { "code": null, "e": 1336, "s": 1129, "text": "Grayscale image contains only single channel. Pixel intensities in this color space is represented by values ranging from 0 to 255. Thus, number of possibilities for one color represented by a pixel is 256." }, { "code": "# Python program to read image as GrayScale # Importing cv2 moduleimport cv2 # Reads image as gray scaleimg = cv2.imread('g4g.png', 0) # We can alternatively convert# image by using cv2colorimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()", "e": 1666, "s": 1336, "text": null }, { "code": null, "e": 1675, "s": 1666, "text": "Output :" }, { "code": null, "e": 1918, "s": 1675, "text": "Y represents Luminance or Luma component, Cb and Cr are Chroma components. Cb represents the blue-difference (difference of blue component and Luma Component). Cr represents the red-difference (difference of red component and Luma Component)." }, { "code": "# Python program to read image# as YCrCb color space # Import cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Convert to YCrCb color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()", "e": 2216, "s": 1918, "text": null }, { "code": null, "e": 2225, "s": 2216, "text": "Output :" }, { "code": null, "e": 2338, "s": 2225, "text": "H : Hue represents dominant wavelength.S : Saturation represents shades of color.V : Value represents Intensity." }, { "code": "# Python program to read image# as HSV color space # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Converts to HSV color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()", "e": 2634, "s": 2338, "text": null }, { "code": null, "e": 2643, "s": 2634, "text": "Output :" }, { "code": null, "e": 2767, "s": 2643, "text": "L – Represents Lightness.A – Color component ranging from Green to Magenta.B – Color component ranging from Blue to Yellow." }, { "code": "# Python program to read image# as LAB color space # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') # Converts to LAB color spaceimg = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # Shows the imagecv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()", "e": 3063, "s": 2767, "text": null }, { "code": null, "e": 3072, "s": 3063, "text": "Output :" }, { "code": null, "e": 3189, "s": 3072, "text": "Edge map can be obtained by various filters like laplacian, sobel, etc. Here, we use Laplacian to generate edge map." }, { "code": "# Python program to read image# as EdgeMap # Importing cv2 moduleimport cv2 # Reads the imageimg = cv2.imread('g4g.png') laplacian = cv2.Laplacian(img, cv2.CV_64F)cv2.imshow('EdgeMap', laplacian) cv2.waitKey(0) cv2.destroyAllWindows()", "e": 3439, "s": 3189, "text": null }, { "code": null, "e": 3448, "s": 3439, "text": "Output :" }, { "code": null, "e": 3543, "s": 3448, "text": "In Heat map representation, individual values contained in a matrix are represented as colors." }, { "code": "# Python program to visualize # Heat map of image # Importing matplotlib and cv2import matplotlib.pyplot as pltimport cv2 # reads the imageimg = cv2.imread('g4g.png') # plot heat map imageplt.imshow(img, cmap ='hot') ", "e": 3764, "s": 3543, "text": null }, { "code": null, "e": 3773, "s": 3764, "text": "Output :" }, { "code": null, "e": 3853, "s": 3773, "text": "Spectral Image map obtains the spectrum for each pixel in the image of a scene." }, { "code": "# Python program to visualize # Spectral map of image # Importing matplotlib and cv2import matplotlib.pyplot as pltimport cv2 img = cv2.imread('g4g.png')plt.imshow(img, cmap ='nipy_spectral') ", "e": 4048, "s": 3853, "text": null }, { "code": null, "e": 4057, "s": 4048, "text": "Output :" }, { "code": null, "e": 4074, "s": 4057, "text": "Image-Processing" }, { "code": null, "e": 4081, "s": 4074, "text": "OpenCV" }, { "code": null, "e": 4088, "s": 4081, "text": "Python" }, { "code": null, "e": 4186, "s": 4088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4204, "s": 4186, "text": "Python Dictionary" }, { "code": null, "e": 4246, "s": 4204, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4268, "s": 4246, "text": "Enumerate() in Python" }, { "code": null, "e": 4294, "s": 4268, "text": "Python String | replace()" }, { "code": null, "e": 4326, "s": 4294, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4355, "s": 4326, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4382, "s": 4355, "text": "Python Classes and Objects" }, { "code": null, "e": 4403, "s": 4382, "text": "Python OOPs Concepts" }, { "code": null, "e": 4439, "s": 4403, "text": "Convert integer to string in Python" } ]
Requests - File Upload
In this chapter, we will upload a file using request and read the contents of the file uploaded. We can do it using the files param as shown in the example below. We will use the http://httpbin.org/post to upload the file. import requests myurl = 'https://httpbin.org/post' files = {'file': open('test.txt', 'rb')} getdata = requests.post(myurl, files=files) print(getdata.text) File upload test using Requests E:\prequests>python makeRequest.py { "args": {}, "data": "", "files": { "file": "File upload test using Requests" }, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "175", "Content-Type": "multipart/form-data; boundary=28aee3a9d15a3571fb80d4d2a94bfd33", "Host": "httpbin.org", "User-Agent": "python-requests/2.22.0" }, "json": null, "origin": "117.223.63.135, 117.223.63.135", "url": "https://httpbin.org/post" } It is also possible to send the contents of the file as shown below− import requests myurl = 'https://httpbin.org/post' files = {'file': ('test1.txt', 'Welcome to TutorialsPoint')} getdata = requests.post(myurl, files=files) print(getdata.text) E:\prequests>python makeRequest.py { "args": {}, "data": "", "files": { "file": "Welcome to TutorialsPoint" }, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "170", "Content-Type": "multipart/form-data; boundary=f2837238286fe40e32080aa7e172be4f", "Host": "httpbin.org", "User-Agent": "python-requests/2.22.0" }, "json": null, "origin": "117.223.63.135, 117.223.63.135",
[ { "code": null, "e": 2485, "s": 2322, "text": "In this chapter, we will upload a file using request and read the contents of the file uploaded. We can do it using the files param as shown in the example below." }, { "code": null, "e": 2545, "s": 2485, "text": "We will use the http://httpbin.org/post to upload the file." }, { "code": null, "e": 2703, "s": 2545, "text": "import requests\nmyurl = 'https://httpbin.org/post'\nfiles = {'file': open('test.txt', 'rb')}\ngetdata = requests.post(myurl, files=files)\nprint(getdata.text) " }, { "code": null, "e": 2736, "s": 2703, "text": "File upload test using Requests\n" }, { "code": null, "e": 3277, "s": 2736, "text": "E:\\prequests>python makeRequest.py\n{\n \"args\": {},\n \"data\": \"\",\n \"files\": {\n \"file\": \"File upload test using Requests\"\n },\n \"form\": {},\n \"headers\": {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Content-Length\": \"175\",\n \"Content-Type\": \"multipart/form-data; \n boundary=28aee3a9d15a3571fb80d4d2a94bfd33\",\n \"Host\": \"httpbin.org\",\n \"User-Agent\": \"python-requests/2.22.0\"\n },\n \"json\": null,\n \"origin\": \"117.223.63.135, 117.223.63.135\",\n \"url\": \"https://httpbin.org/post\"\n}\n" }, { "code": null, "e": 3346, "s": 3277, "text": "It is also possible to send the contents of the file as shown below−" }, { "code": null, "e": 3522, "s": 3346, "text": "import requests\nmyurl = 'https://httpbin.org/post'\nfiles = {'file': ('test1.txt', 'Welcome to TutorialsPoint')}\ngetdata = requests.post(myurl, files=files)\nprint(getdata.text)" } ]
C program to display month by month calendar for a given year
22 Apr, 2020 Prerequisite: Find day of the week for a given dateGiven a year N, the task is to print the calendar for every month of the given year. Implementation: // C program to print the month by month// calendar for the given year #include <stdio.h> // Function that returns the index of the// day for date DD/MM/YYYYint dayNumber(int day, int month, int year){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; year -= month < 3; return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;} // Function that returns the name of the// month for the given month Number// January - 0, February - 1 and so onchar* getMonthName(int monthNumber){ char* month; switch (monthNumber) { case 0: month = "January"; break; case 1: month = "February"; break; case 2: month = "March"; break; case 3: month = "April"; break; case 4: month = "May"; break; case 5: month = "June"; break; case 6: month = "July"; break; case 7: month = "August"; break; case 8: month = "September"; break; case 9: month = "October"; break; case 10: month = "November"; break; case 11: month = "December"; break; } return month;} // Function to return the number of days// in a monthint numberOfDays(int monthNumber, int year){ // January if (monthNumber == 0) return (31); // February if (monthNumber == 1) { // If the year is leap then Feb // has 29 days if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return (29); else return (28); } // March if (monthNumber == 2) return (31); // April if (monthNumber == 3) return (30); // May if (monthNumber == 4) return (31); // June if (monthNumber == 5) return (30); // July if (monthNumber == 6) return (31); // August if (monthNumber == 7) return (31); // September if (monthNumber == 8) return (30); // October if (monthNumber == 9) return (31); // November if (monthNumber == 10) return (30); // December if (monthNumber == 11) return (31);} // Function to print the calendar of// the given yearvoid printCalendar(int year){ printf(" Calendar - %d\n\n", year); int days; // Index of the day from 0 to 6 int current = dayNumber(1, 1, year); // i for Iterate through months // j for Iterate through days // of the month - i for (int i = 0; i < 12; i++) { days = numberOfDays(i, year); // Print the current month name printf("\n ------------%s-------------\n", getMonthName(i)); // Print the columns printf(" Sun Mon Tue Wed Thu Fri Sat\n"); // Print appropriate spaces int k; for (k = 0; k < current; k++) printf(" "); for (int j = 1; j <= days; j++) { printf("%5d", j); if (++k > 6) { k = 0; printf("\n"); } } if (k) printf("\n"); current = k; } return;} // Driver Codeint main(){ int year = 2016; // Function Call printCalendar(year); return 0;} Calendar - 2016 ------------January------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------February------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ------------March------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------April------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------May------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------June------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------July------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------August------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------September------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------October------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------November------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------December------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Calendars C Language C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Different Methods to Reverse a String in C++ Left Shift and Right Shift Operators in C/C++ Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2020" }, { "code": null, "e": 188, "s": 52, "text": "Prerequisite: Find day of the week for a given dateGiven a year N, the task is to print the calendar for every month of the given year." }, { "code": null, "e": 204, "s": 188, "text": "Implementation:" }, { "code": "// C program to print the month by month// calendar for the given year #include <stdio.h> // Function that returns the index of the// day for date DD/MM/YYYYint dayNumber(int day, int month, int year){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; year -= month < 3; return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;} // Function that returns the name of the// month for the given month Number// January - 0, February - 1 and so onchar* getMonthName(int monthNumber){ char* month; switch (monthNumber) { case 0: month = \"January\"; break; case 1: month = \"February\"; break; case 2: month = \"March\"; break; case 3: month = \"April\"; break; case 4: month = \"May\"; break; case 5: month = \"June\"; break; case 6: month = \"July\"; break; case 7: month = \"August\"; break; case 8: month = \"September\"; break; case 9: month = \"October\"; break; case 10: month = \"November\"; break; case 11: month = \"December\"; break; } return month;} // Function to return the number of days// in a monthint numberOfDays(int monthNumber, int year){ // January if (monthNumber == 0) return (31); // February if (monthNumber == 1) { // If the year is leap then Feb // has 29 days if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return (29); else return (28); } // March if (monthNumber == 2) return (31); // April if (monthNumber == 3) return (30); // May if (monthNumber == 4) return (31); // June if (monthNumber == 5) return (30); // July if (monthNumber == 6) return (31); // August if (monthNumber == 7) return (31); // September if (monthNumber == 8) return (30); // October if (monthNumber == 9) return (31); // November if (monthNumber == 10) return (30); // December if (monthNumber == 11) return (31);} // Function to print the calendar of// the given yearvoid printCalendar(int year){ printf(\" Calendar - %d\\n\\n\", year); int days; // Index of the day from 0 to 6 int current = dayNumber(1, 1, year); // i for Iterate through months // j for Iterate through days // of the month - i for (int i = 0; i < 12; i++) { days = numberOfDays(i, year); // Print the current month name printf(\"\\n ------------%s-------------\\n\", getMonthName(i)); // Print the columns printf(\" Sun Mon Tue Wed Thu Fri Sat\\n\"); // Print appropriate spaces int k; for (k = 0; k < current; k++) printf(\" \"); for (int j = 1; j <= days; j++) { printf(\"%5d\", j); if (++k > 6) { k = 0; printf(\"\\n\"); } } if (k) printf(\"\\n\"); current = k; } return;} // Driver Codeint main(){ int year = 2016; // Function Call printCalendar(year); return 0;}", "e": 3550, "s": 204, "text": null }, { "code": null, "e": 6493, "s": 3550, "text": "Calendar - 2016\n\n\n ------------January-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n 31\n\n ------------February-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20\n 21 22 23 24 25 26 27\n 28 29\n\n ------------March-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n 13 14 15 16 17 18 19\n 20 21 22 23 24 25 26\n 27 28 29 30 31\n\n ------------April-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n\n ------------May-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6 7\n 8 9 10 11 12 13 14\n 15 16 17 18 19 20 21\n 22 23 24 25 26 27 28\n 29 30 31\n\n ------------June-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4\n 5 6 7 8 9 10 11\n 12 13 14 15 16 17 18\n 19 20 21 22 23 24 25\n 26 27 28 29 30\n\n ------------July-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n 31\n\n ------------August-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20\n 21 22 23 24 25 26 27\n 28 29 30 31\n\n ------------September-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30\n\n ------------October-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1\n 2 3 4 5 6 7 8\n 9 10 11 12 13 14 15\n 16 17 18 19 20 21 22\n 23 24 25 26 27 28 29\n 30 31\n\n ------------November-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n 13 14 15 16 17 18 19\n 20 21 22 23 24 25 26\n 27 28 29 30\n\n ------------December-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30 31\n" }, { "code": null, "e": 6503, "s": 6493, "text": "Calendars" }, { "code": null, "e": 6514, "s": 6503, "text": "C Language" }, { "code": null, "e": 6525, "s": 6514, "text": "C Programs" }, { "code": null, "e": 6544, "s": 6525, "text": "School Programming" }, { "code": null, "e": 6642, "s": 6544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6659, "s": 6642, "text": "Substring in C++" }, { "code": null, "e": 6681, "s": 6659, "text": "Function Pointer in C" }, { "code": null, "e": 6716, "s": 6681, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 6761, "s": 6716, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 6807, "s": 6761, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 6820, "s": 6807, "text": "Strings in C" }, { "code": null, "e": 6861, "s": 6820, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6890, "s": 6861, "text": "Basics of File Handling in C" }, { "code": null, "e": 6928, "s": 6890, "text": "UDP Server-Client implementation in C" } ]
Problem of initialization in C++
18 Apr, 2022 In this article, we will discuss the problem of initialization in C++, the data members of a class have private scope by default, so they are not accessible outside the class directly. Therefore, when objects are created, the members of the object cannot be initialized directly and this problem of not being able to initialize data members is known as the problem of initialization. Example: In the below example, a class is created with two data members. These data members have no explicitly defined scope thus they are private by default. The private data members cannot be initialized later using the object of the class. Here, if the data members are initialized using the object of the class, then it will show an error. C++ // C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class declaring the data membersclass Student { int marks; int rollno;}; // Driver Codeint main(){ Student s1; // Member variables marks and // rollno cannot be initialized // outside the class directly s1.marks = 70; s1.rollno = 2; cout << "Student Roll No: "; cout << s1.rollno; cout << "Student Marks: "; cout << s1.marks; return 0;} Output: Explanation: Now as in the above code it can be seen that private data members cannot be initialized directly outside the class. To solve the above problem of Initialization, the concept of constructors is used. They are a special member functions that are automatically called when an object of that class is created. Also, their name is the same as the class name. The constructors should be used to initialize member variables of the class because member variables cannot be declared or defined in a single statement. Therefore, constructors are used in initializing data members of a class when an object is created. Below is the C++ program to illustrate the above concept: C++ // C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class to declare the// data membersclass Student { int marks = 95; int rollno = 1234; // Wrong way}; // Driver Codeint main(){ Student s1; cout << s1.rollno; cout << s1.marks; return 0;} Output: Explanation: The above method is wrong and does not make the object an actual object because the values stored are garbage due to the private context of the class Student. The object just physically appears. To make the object behave as an actual object which can store values, constructors come into play. Example: In the below example, a constructor is created in the class that will initialize variables with the value. C++ // C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class student with// student detailsclass Student { int marks; int rollno; // Constructor of // the classpublic: Student() { marks = 95; rollno = 1234; cout << "Student marks: " << marks << endl << "Student roll no: " << rollno; }}; // Driver Codeint main(){ Student s1; // Printed Student Details return 0;} Student marks: 95 Student roll no: 1234 jayanth_mkv varshagumber28 Constructors CPP-Basics C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2022" }, { "code": null, "e": 412, "s": 28, "text": "In this article, we will discuss the problem of initialization in C++, the data members of a class have private scope by default, so they are not accessible outside the class directly. Therefore, when objects are created, the members of the object cannot be initialized directly and this problem of not being able to initialize data members is known as the problem of initialization." }, { "code": null, "e": 757, "s": 412, "text": "Example: In the below example, a class is created with two data members. These data members have no explicitly defined scope thus they are private by default. The private data members cannot be initialized later using the object of the class. Here, if the data members are initialized using the object of the class, then it will show an error." }, { "code": null, "e": 761, "s": 757, "text": "C++" }, { "code": "// C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class declaring the data membersclass Student { int marks; int rollno;}; // Driver Codeint main(){ Student s1; // Member variables marks and // rollno cannot be initialized // outside the class directly s1.marks = 70; s1.rollno = 2; cout << \"Student Roll No: \"; cout << s1.rollno; cout << \"Student Marks: \"; cout << s1.marks; return 0;}", "e": 1233, "s": 761, "text": null }, { "code": null, "e": 1242, "s": 1233, "text": " Output:" }, { "code": null, "e": 1375, "s": 1246, "text": "Explanation: Now as in the above code it can be seen that private data members cannot be initialized directly outside the class." }, { "code": null, "e": 1613, "s": 1375, "text": "To solve the above problem of Initialization, the concept of constructors is used. They are a special member functions that are automatically called when an object of that class is created. Also, their name is the same as the class name." }, { "code": null, "e": 1867, "s": 1613, "text": "The constructors should be used to initialize member variables of the class because member variables cannot be declared or defined in a single statement. Therefore, constructors are used in initializing data members of a class when an object is created." }, { "code": null, "e": 1926, "s": 1867, "text": "Below is the C++ program to illustrate the above concept: " }, { "code": null, "e": 1930, "s": 1926, "text": "C++" }, { "code": "// C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class to declare the// data membersclass Student { int marks = 95; int rollno = 1234; // Wrong way}; // Driver Codeint main(){ Student s1; cout << s1.rollno; cout << s1.marks; return 0;}", "e": 2233, "s": 1930, "text": null }, { "code": null, "e": 2242, "s": 2233, "text": " Output:" }, { "code": null, "e": 2553, "s": 2246, "text": "Explanation: The above method is wrong and does not make the object an actual object because the values stored are garbage due to the private context of the class Student. The object just physically appears. To make the object behave as an actual object which can store values, constructors come into play." }, { "code": null, "e": 2670, "s": 2553, "text": "Example: In the below example, a constructor is created in the class that will initialize variables with the value. " }, { "code": null, "e": 2674, "s": 2670, "text": "C++" }, { "code": "// C++ program to demonstrate the// above approach#include <iostream>using namespace std; // Class student with// student detailsclass Student { int marks; int rollno; // Constructor of // the classpublic: Student() { marks = 95; rollno = 1234; cout << \"Student marks: \" << marks << endl << \"Student roll no: \" << rollno; }}; // Driver Codeint main(){ Student s1; // Printed Student Details return 0;}", "e": 3140, "s": 2674, "text": null }, { "code": null, "e": 3180, "s": 3140, "text": "Student marks: 95\nStudent roll no: 1234" }, { "code": null, "e": 3192, "s": 3180, "text": "jayanth_mkv" }, { "code": null, "e": 3207, "s": 3192, "text": "varshagumber28" }, { "code": null, "e": 3220, "s": 3207, "text": "Constructors" }, { "code": null, "e": 3231, "s": 3220, "text": "CPP-Basics" }, { "code": null, "e": 3235, "s": 3231, "text": "C++" }, { "code": null, "e": 3248, "s": 3235, "text": "C++ Programs" }, { "code": null, "e": 3252, "s": 3248, "text": "CPP" }, { "code": null, "e": 3350, "s": 3252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3374, "s": 3350, "text": "Sorting a vector in C++" }, { "code": null, "e": 3394, "s": 3374, "text": "Polymorphism in C++" }, { "code": null, "e": 3438, "s": 3394, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3471, "s": 3438, "text": "Friend class and function in C++" }, { "code": null, "e": 3496, "s": 3471, "text": "std::string class in C++" }, { "code": null, "e": 3531, "s": 3496, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 3565, "s": 3531, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 3609, "s": 3565, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 3668, "s": 3609, "text": "How to return multiple values from a function in C or C++?" } ]
Subset Sum Problem | Practice | GeeksforGeeks
Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Example 1: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 9 Output: 1 Explanation: Here there exists a subset with sum = 9, 4+3+2 = 9. Example 2: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 30 Output: 0 Explanation: There is no subset with sum 30. Your Task: You don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise. The driver code itself prints 1, if returned value is true and prints 0 if returned value is false. Expected Time Complexity: O(sum*N) Expected Auxiliary Space: O(sum*N) Constraints: 1 <= N <= 100 1<= arr[i] <= 100 1<= sum <= 105 0 pythonize1 day ago def recur(dp, arr, S, si): if S==0: dp[S][si]=1; return 1 if dp[S][si] != -1: return dp[S][si] ans = 0 if S >= arr[si]: ans = recur(dp, arr, S-arr[si], si+1) if ans == 0: ans = recur(dp, arr, S, si+1) dp[S][si] = ans return ans class Solution: def isSubsetSum (self, N, arr, S): dp = [ [-1] * N + [0] for _ in range(S+1) ] ans = recur( dp, arr, S, 0 ) return ans +1 sharmaadarsh8593 days ago //using top down approach class Solution{ public: bool isSubsetSum(vector<int>arr, int sum){ // code here int t[arr.size()+2][sum+2]; for(int i=0;i<=arr.size();i++){ for(int j=0;j<=sum;j++){ if(j==0){ t[i][j]=1; } else if(i==0) t[i][j]=0; } } for(int i=1;i<=arr.size();i++){ for(int j=1;j<=sum;j++){ if(arr[i-1]<=j){ // t[i][j]=7; t[i][j]=t[i-1][j-arr[i-1]]+t[i-1][j]; } else if(arr[i-1]>j){ t[i][j]=t[i-1][j]; } } } return t[arr.size()][sum]; }}; +1 shakeher3 days ago //recursion class Solution{ private: bool solve(vector<int>arr, int sum,int idx){ if(sum == 0) return true; if(idx == 0) return (arr[idx] == sum); bool taken = false; if(sum>=arr[idx]) taken = solve(arr,sum-arr[idx],idx-1); bool notTaken = solve(arr,sum,idx-1); return taken || notTaken; } public: bool isSubsetSum(vector<int>arr, int sum){ return solve(arr,sum,arr.size()-1); } }; //memoization class Solution{ private: bool solve(vector<int>arr, int sum,int idx,vector<vector<int>> &dp){ if(sum == 0) return true; if(idx == 0) return (arr[idx] == sum); if(dp[idx][sum]!=-1) return dp[idx][sum]; bool taken = false; if(sum>=arr[idx]) taken = solve(arr,sum-arr[idx],idx-1,dp); bool notTaken = solve(arr,sum,idx-1,dp); return dp[idx][sum] = taken || notTaken; } public: bool isSubsetSum(vector<int>arr, int sum){ int n = arr.size(); int m = sum+1; vector<vector<int>> dp(n,vector<int>(m,-1)); return solve(arr,sum,arr.size()-1,dp); } }; //tabulation class Solution{ public: bool isSubsetSum(vector<int>arr, int target){ int n = (int)arr.size()+1; int m = target+1; vector<vector<bool>> dp(n,vector<bool>(m,false)); for(int i=0;i<n;i++){ dp[i][0] = true; } for(int i=1;i<m;i++){ dp[0][i] = false; } for(int idx=1;idx<n;idx++){ for(int sum=1;sum<m;sum++){ dp[idx][sum] = (arr[idx-1]<=sum)?(dp[idx-1][sum-arr[idx-1]] || dp[idx-1][sum]):(dp[idx-1][sum]); } } return dp[n-1][m-1]; } }; +1 khimanidhaval3 days ago int solve(vector<int>arr, int sum, int n, vector<vector<int>>&dp) { if(n==0) { if(sum==0) { return 1; } return 0; } if(sum==0) { return 1; } if(dp[n][sum]!=-1) { return dp[n][sum]; } bool ra=0; bool la; if(sum>=arr[n-1]) { la=solve(arr, sum-arr[n-1],n-1,dp) || solve(arr,sum,n-1,dp); dp[n][sum]=la; } else{ ra=solve(arr,sum,n-1,dp); dp[n][sum]=ra; } return (la||ra); } bool isSubsetSum(vector<int>arr, int sum){ // code here vector<vector<int>>dp(arr.size()+1, vector<int>(sum+1,-1)); return solve(arr,sum,arr.size(),dp); } 0 thiruvazhidhinesh3 days ago JAVA SOLUTION: class Solution{ static Boolean isSubsetSum(int N, int arr[], int sum){ int[][] dp=new int[N+1][sum+1]; Arrays.sort(arr); for(int i=1;i<sum+1;i++){ dp[0][i]=0; } for(int i=0;i<N+1;i++){ dp[i][0]=0; } for(int i=1;i<N+1;i++){ for(int j=1;j<sum+1;j++){ if(j<arr[i-1]){ dp[i][j]=dp[i-1][j]; } else{ dp[i][j]=Math.max(dp[i-1][j],arr[i-1]+dp[i-1][j-arr[i-1]]); } } } if(dp[N][sum]==sum) return true; return false; }} 0 anonymous15074 days ago int n = arr.size(); int dp[n+1][sum+1]; //initialisation for(int i =0;i<n+1;i++) { for(int j =0;j<sum+1;j++) { if(i==0) dp[i][j]= false; if(j==0) dp[i][j] = true; } } for(int i=1;i<n+1;i++) { for(int j =1;j<sum+1;j++) { if(arr[i-1]<=j) dp[i][j]=dp[i-1][j-arr[i-1]] || dp[i-1][j]; else dp[i][j]=dp[i-1][j]; } } return dp[n][sum]; } 0 kadamavp4 days ago Why does this fail for few testcases? // { Driver Code Starts //Initial template for C++ #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution{ public: bool helper(vector<int>arr, int n ,int sum){ bool t[n+1][sum+1]; //INITIAILIZATION for(int i =0; i<n+1; i++){ for(int j = 0; j<sum+1; j++){ if( i==0 ){ t[i][j] = false; } if(j == 0){ t[i][j] = true; } } } for(int i=1; i<n+1; i++){ for(int j = 1; j<sum+1; j++){ if(arr[i-1] <= j){ t[i][j] = (t[i-1][j-arr[i-1]] || t[i-1][j]); } else{ t[i][j] = t[i-1][j]; } } } return t[n][sum]; } bool isSubsetSum(vector<int>arr, int sum){ // code here int n = arr.size()-1; return helper(arr,n,sum); } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int N, sum; cin >> N; vector<int> arr(N); for(int i = 0; i < N; i++){ cin >> arr[i]; } cin >> sum; Solution ob; cout << ob.isSubsetSum(arr, sum) << endl; } return 0; } // } Driver Code Ends +1 nikhilchakravarthy094 days ago class Solution{ public: bool isSubsetSum(vector<int>arr, int sum){ // code here int n=arr.size(); vector<vector<bool>> dp(n,vector<bool>(sum+1,0)); for(int i=0;i<n;i++) dp[i][0] = true; dp[0][arr[0]] = true; for(int i=1;i<n;i++){ for(int target=1;target<=sum;target++){ bool notake = dp[i-1][target]; bool take = false; if(target >= arr[i]){ take = dp[i-1][target-arr[i]]; } dp[i][target] = (take | notake); } } return dp[n-1][sum]; } }; 0 sumanthbolle3125 days ago bool isSubsetSum(vector<int>arr, int sum){ sort(arr.begin(),arr.end()); int n =arr.size(); int temp = arr[0]; for(int i=1;sum>arr[i];i++) { if(arr[i] == sum || temp == sum) return 1; else if(temp < sum) temp += arr[i]; } return temp == sum; // code here } Code does pass 32 test cases out of 34, any ideas to improve it? 0 armaanbgp5 days ago Working: vector<vector<int>> dp(arr.size(),vector<int>(sum+1,-1)); Not Working: vector<vector<bool>> dp(arr.size(),vector<bool>(sum+1,-1)); We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 374, "s": 238, "text": "Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. " }, { "code": null, "e": 386, "s": 374, "text": "\nExample 1:" }, { "code": null, "e": 513, "s": 386, "text": "Input:\nN = 6\narr[] = {3, 34, 4, 12, 5, 2}\nsum = 9\nOutput: 1 \nExplanation: Here there exists a subset with\nsum = 9, 4+3+2 = 9.\n" }, { "code": null, "e": 524, "s": 513, "text": "Example 2:" }, { "code": null, "e": 631, "s": 524, "text": "Input:\nN = 6\narr[] = {3, 34, 4, 12, 5, 2}\nsum = 30\nOutput: 0 \nExplanation: There is no subset with sum 30." }, { "code": null, "e": 1018, "s": 631, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise.\nThe driver code itself prints 1, if returned value is true and prints 0 if returned value is false.\n " }, { "code": null, "e": 1090, "s": 1018, "text": "Expected Time Complexity: O(sum*N)\nExpected Auxiliary Space: O(sum*N)\n " }, { "code": null, "e": 1150, "s": 1090, "text": "Constraints:\n1 <= N <= 100\n1<= arr[i] <= 100\n1<= sum <= 105" }, { "code": null, "e": 1152, "s": 1150, "text": "0" }, { "code": null, "e": 1171, "s": 1152, "text": "pythonize1 day ago" }, { "code": null, "e": 1429, "s": 1171, "text": "def recur(dp, arr, S, si): if S==0: dp[S][si]=1; return 1 if dp[S][si] != -1: return dp[S][si] ans = 0 if S >= arr[si]: ans = recur(dp, arr, S-arr[si], si+1) if ans == 0: ans = recur(dp, arr, S, si+1) dp[S][si] = ans return ans" }, { "code": null, "e": 1584, "s": 1429, "text": "class Solution: def isSubsetSum (self, N, arr, S): dp = [ [-1] * N + [0] for _ in range(S+1) ] ans = recur( dp, arr, S, 0 ) return ans" }, { "code": null, "e": 1587, "s": 1584, "text": "+1" }, { "code": null, "e": 1613, "s": 1587, "text": "sharmaadarsh8593 days ago" }, { "code": null, "e": 2366, "s": 1613, "text": "//using top down approach class Solution{ public: bool isSubsetSum(vector<int>arr, int sum){ // code here int t[arr.size()+2][sum+2]; for(int i=0;i<=arr.size();i++){ for(int j=0;j<=sum;j++){ if(j==0){ t[i][j]=1; } else if(i==0) t[i][j]=0; } } for(int i=1;i<=arr.size();i++){ for(int j=1;j<=sum;j++){ if(arr[i-1]<=j){ // t[i][j]=7; t[i][j]=t[i-1][j-arr[i-1]]+t[i-1][j]; } else if(arr[i-1]>j){ t[i][j]=t[i-1][j]; } } } return t[arr.size()][sum]; }};" }, { "code": null, "e": 2369, "s": 2366, "text": "+1" }, { "code": null, "e": 2388, "s": 2369, "text": "shakeher3 days ago" }, { "code": null, "e": 4196, "s": 2388, "text": "//recursion\nclass Solution{\nprivate:\nbool solve(vector<int>arr, int sum,int idx){\n \n if(sum == 0)\n return true;\n \n if(idx == 0)\n return (arr[idx] == sum);\n \n bool taken = false;\n if(sum>=arr[idx])\n taken = solve(arr,sum-arr[idx],idx-1);\n \n bool notTaken = solve(arr,sum,idx-1);\n return taken || notTaken;\n \n}\npublic:\n bool isSubsetSum(vector<int>arr, int sum){\n \n return solve(arr,sum,arr.size()-1);\n }\n};\n\n//memoization\nclass Solution{\nprivate:\nbool solve(vector<int>arr, int sum,int idx,vector<vector<int>> &dp){\n \n if(sum == 0)\n return true;\n \n if(idx == 0)\n return (arr[idx] == sum);\n \n if(dp[idx][sum]!=-1)\n return dp[idx][sum];\n \n bool taken = false;\n if(sum>=arr[idx])\n taken = solve(arr,sum-arr[idx],idx-1,dp);\n \n bool notTaken = solve(arr,sum,idx-1,dp);\n return dp[idx][sum] = taken || notTaken;\n \n}\npublic:\n bool isSubsetSum(vector<int>arr, int sum){\n int n = arr.size();\n int m = sum+1;\n vector<vector<int>> dp(n,vector<int>(m,-1));\n return solve(arr,sum,arr.size()-1,dp);\n }\n};\n\n//tabulation\nclass Solution{ \npublic:\n bool isSubsetSum(vector<int>arr, int target){\n int n = (int)arr.size()+1;\n int m = target+1;\n vector<vector<bool>> dp(n,vector<bool>(m,false));\n \n for(int i=0;i<n;i++){\n dp[i][0] = true;\n }\n for(int i=1;i<m;i++){\n dp[0][i] = false;\n }\n \n for(int idx=1;idx<n;idx++){\n for(int sum=1;sum<m;sum++){\n dp[idx][sum] = (arr[idx-1]<=sum)?(dp[idx-1][sum-arr[idx-1]] || dp[idx-1][sum]):(dp[idx-1][sum]);\n }\n }\n \n return dp[n-1][m-1];\n }\n};" }, { "code": null, "e": 4199, "s": 4196, "text": "+1" }, { "code": null, "e": 4223, "s": 4199, "text": "khimanidhaval3 days ago" }, { "code": null, "e": 4813, "s": 4223, "text": "int solve(vector<int>arr, int sum, int n, vector<vector<int>>&dp) { if(n==0) { if(sum==0) { return 1; } return 0; } if(sum==0) { return 1; } if(dp[n][sum]!=-1) { return dp[n][sum]; } bool ra=0; bool la; if(sum>=arr[n-1]) { la=solve(arr, sum-arr[n-1],n-1,dp) || solve(arr,sum,n-1,dp); dp[n][sum]=la; } else{ ra=solve(arr,sum,n-1,dp); dp[n][sum]=ra; } return (la||ra); }" }, { "code": null, "e": 4991, "s": 4813, "text": " bool isSubsetSum(vector<int>arr, int sum){ // code here vector<vector<int>>dp(arr.size()+1, vector<int>(sum+1,-1)); return solve(arr,sum,arr.size(),dp); }" }, { "code": null, "e": 4993, "s": 4991, "text": "0" }, { "code": null, "e": 5021, "s": 4993, "text": "thiruvazhidhinesh3 days ago" }, { "code": null, "e": 5036, "s": 5021, "text": "JAVA SOLUTION:" }, { "code": null, "e": 5642, "s": 5036, "text": "class Solution{ static Boolean isSubsetSum(int N, int arr[], int sum){ int[][] dp=new int[N+1][sum+1]; Arrays.sort(arr); for(int i=1;i<sum+1;i++){ dp[0][i]=0; } for(int i=0;i<N+1;i++){ dp[i][0]=0; } for(int i=1;i<N+1;i++){ for(int j=1;j<sum+1;j++){ if(j<arr[i-1]){ dp[i][j]=dp[i-1][j]; } else{ dp[i][j]=Math.max(dp[i-1][j],arr[i-1]+dp[i-1][j-arr[i-1]]); } } } if(dp[N][sum]==sum) return true; return false; }}" }, { "code": null, "e": 5644, "s": 5642, "text": "0" }, { "code": null, "e": 5668, "s": 5644, "text": "anonymous15074 days ago" }, { "code": null, "e": 6252, "s": 5668, "text": "int n = arr.size(); int dp[n+1][sum+1]; //initialisation for(int i =0;i<n+1;i++) { for(int j =0;j<sum+1;j++) { if(i==0) dp[i][j]= false; if(j==0) dp[i][j] = true; } } for(int i=1;i<n+1;i++) { for(int j =1;j<sum+1;j++) { if(arr[i-1]<=j) dp[i][j]=dp[i-1][j-arr[i-1]] || dp[i-1][j]; else dp[i][j]=dp[i-1][j]; } } return dp[n][sum]; }" }, { "code": null, "e": 6254, "s": 6252, "text": "0" }, { "code": null, "e": 6273, "s": 6254, "text": "kadamavp4 days ago" }, { "code": null, "e": 6311, "s": 6273, "text": "Why does this fail for few testcases?" }, { "code": null, "e": 7789, "s": 6311, "text": "// { Driver Code Starts\n//Initial template for C++\n\n#include<bits/stdc++.h> \nusing namespace std; \n\n // } Driver Code Ends\n//User function template for C++\n\nclass Solution{ \npublic:\n bool helper(vector<int>arr, int n ,int sum){\n \n \n bool t[n+1][sum+1];\n \n \n //INITIAILIZATION\n for(int i =0; i<n+1; i++){\n for(int j = 0; j<sum+1; j++){\n if( i==0 ){\n t[i][j] = false;\n }\n if(j == 0){\n t[i][j] = true;\n }\n }\n }\n \n for(int i=1; i<n+1; i++){\n for(int j = 1; j<sum+1; j++){\n if(arr[i-1] <= j){\n t[i][j] = (t[i-1][j-arr[i-1]] || t[i-1][j]);\n }\n else{\n t[i][j] = t[i-1][j];\n }\n \n }\n }\n \n return t[n][sum];\n }\n bool isSubsetSum(vector<int>arr, int sum){\n // code here \n int n = arr.size()-1;\n return helper(arr,n,sum);\n \n }\n};\n\n// { Driver Code Starts.\nint main() \n{ \n int t;\n cin>>t;\n while(t--)\n {\n int N, sum;\n cin >> N;\n vector<int> arr(N);\n for(int i = 0; i < N; i++){\n cin >> arr[i];\n }\n cin >> sum;\n \n Solution ob;\n cout << ob.isSubsetSum(arr, sum) << endl;\n }\n return 0; \n} \n // } Driver Code Ends" }, { "code": null, "e": 7792, "s": 7789, "text": "+1" }, { "code": null, "e": 7823, "s": 7792, "text": "nikhilchakravarthy094 days ago" }, { "code": null, "e": 8473, "s": 7823, "text": "class Solution{ \npublic:\n bool isSubsetSum(vector<int>arr, int sum){\n // code here \n int n=arr.size();\n vector<vector<bool>> dp(n,vector<bool>(sum+1,0));\n for(int i=0;i<n;i++)\n dp[i][0] = true;\n dp[0][arr[0]] = true;\n for(int i=1;i<n;i++){\n for(int target=1;target<=sum;target++){\n bool notake = dp[i-1][target];\n bool take = false;\n if(target >= arr[i]){\n take = dp[i-1][target-arr[i]];\n }\n dp[i][target] = (take | notake);\n }\n }\n return dp[n-1][sum];\n }\n};" }, { "code": null, "e": 8475, "s": 8473, "text": "0" }, { "code": null, "e": 8501, "s": 8475, "text": "sumanthbolle3125 days ago" }, { "code": null, "e": 8887, "s": 8501, "text": "bool isSubsetSum(vector<int>arr, int sum){\n sort(arr.begin(),arr.end());\n int n =arr.size();\n int temp = arr[0];\n for(int i=1;sum>arr[i];i++)\n {\n if(arr[i] == sum || temp == sum)\n return 1;\n else if(temp < sum)\n temp += arr[i];\n }\n return temp == sum;\n // code here \n \n }" }, { "code": null, "e": 8954, "s": 8889, "text": "Code does pass 32 test cases out of 34, any ideas to improve it?" }, { "code": null, "e": 8956, "s": 8954, "text": "0" }, { "code": null, "e": 8976, "s": 8956, "text": "armaanbgp5 days ago" }, { "code": null, "e": 8985, "s": 8976, "text": "Working:" }, { "code": null, "e": 9043, "s": 8985, "text": "vector<vector<int>> dp(arr.size(),vector<int>(sum+1,-1));" }, { "code": null, "e": 9056, "s": 9043, "text": "Not Working:" }, { "code": null, "e": 9116, "s": 9056, "text": "vector<vector<bool>> dp(arr.size(),vector<bool>(sum+1,-1));" }, { "code": null, "e": 9262, "s": 9116, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9298, "s": 9262, "text": " Login to access your submissions. " }, { "code": null, "e": 9308, "s": 9298, "text": "\nProblem\n" }, { "code": null, "e": 9318, "s": 9308, "text": "\nContest\n" }, { "code": null, "e": 9381, "s": 9318, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9566, "s": 9381, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9850, "s": 9566, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 9996, "s": 9850, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 10073, "s": 9996, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 10114, "s": 10073, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 10142, "s": 10114, "text": "Disable browser extensions." }, { "code": null, "e": 10213, "s": 10142, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 10400, "s": 10213, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Trigonometric Functions of Sum and Difference of Two Angles
20 Dec, 2021 Trigonometry is a branch of mathematics, which deal with the angles, lengths, and heights of triangles and their relationships. It had played an important role to calculate complex functions or large distances which were not possible to calculate without trigonometry. While solving problems with trigonometry, we came across many situations where we have to calculate the trigonometric solutions for the sum of angles or differences of angles. E.g. Here, Which is a tangent trigonometric ratio, with an angle opposite to BC. tan(θ+Φ) = If θ = 30° and Φ = 45°. We know the trigonometric angles of 45° and 30°, but we don’t know the trigonometric angle of (45° + 30° = 75°). So, to simplify these types of problems. We will get to learn trigonometric formulae or identities of sum and differences of two angles which will make things easier. Before moving further first we will see the signs of the trigonometric functions in the four quadrants. These signs play an important role in trigonometry. Now we are going to find the trigonometric identities. As we know that sin(-x) = – sin x cos(-x) = cos x Because only cos and sec are positive in the fourth quadrant. So, now we prove some results regarding sum and difference of angles: Let’s consider a unit circle (having radius as 1) with centre at the origin. Let x be the ∠DOA and y be the ∠AOB. Then (x + y) is the ∠DOB. Also let (– y) be the ∠DOC. Therefore, the coordinates of A, B, C and D are A = (cos x, sin x) B = [cos (x + y), sin (x + y)] C = [cos (– y), sin (– y)] D = (1, 0). As, ∠AOB = ∠COD Adding, ∠BOC both side, we get ∠AOB + ∠BOC = ∠COD + ∠BOC ∠AOC = ∠BOD In △ AOC and △ BOD OA = OB (radius of circle) ∠AOC = ∠BOD (Proved earlier) OC = OD (radius of circle) △ AOC ≅ △ BOD by SAS congruency. By using distance formula, for AC2 = [cos x – cos (– y)]2 + [sin x – sin(–y]2 AC2 = 2 – 2 (cos x cos y – sin x sin y) ................(i) And, now Similarly, using distance formula, we get BD2 = [1 – cos (x + y)]2 + [0 – sin (x + y)]2 BD2 = 2 – 2 cos (x + y) ................(ii) As, △ AOC ≅ △ BOD AC = BD, So AC2 = BD2 From eq(i) and eq(ii), we get 2 – 2 (cos x cos y – sin x sin y) = 2 – 2 cos (x + y) So, cos (x + y) = cos x cos y – sin x sin y Take y = -y, we get cos (x + (-y)) = cos x cos (-y) – sin x sin (-y) cos (x – y) = cos x cos y + sin x sin y Now, taking cos (-(x + y)) = cos ((-x) – y) (cos (-θ) = sin θ) sin (x – y) = sin x cos y – cos x sin y take y = -y, we get sin (x – (-y)) = sin x cos (-y) – cos x sin (-y) sin (x + y) = sin x cos y + cos x sin y The derived formulae for trigonometric ratios of compound angles are as follows: sin (A + B) = sin A cos B + cos A sin B ....................(1) sin (A – B) = sin A cos B – cos A sin B ....................(2) cos (A + B) = cos A cos B – sin A sin B ....................(3) cos (A – B) = cos A cos B + sin A sin B ....................(4) By using these formulae, we can obtain some important and mostly used form: (1) Take, A = In eq(1) and (3), we get sin (+B) = cos B cos (+B) = – sin A (2) Take, A = π In eq(1), (2), (3) and (4) we get sin (π + B) = – sin B sin (π – B) = sin B cos (π ± B) = – cos B (3) Take, A = 2π In eq(2) and (4) we get sin (2π – B) = – sin B cos (2π – B) = cos B Similarly for cot A, tan A, sec A, and cosec A (4) Here, A, B, and (A + B) is not an odd multiple of π/2, so, cosA, cosB and cos(A + B) are non-zero tan(A + B) = sin(A + B)/cos(A + B) From eq(1) and (3), we get tan(A + B) = sin A cos B + cos A sin B/cos A cos B – sin A sin B Now divide the numerator and denominator by cos A cos B we get tan(A + B) = (5) As we know that So, on putting B = -B, we get (6) Here, A, B, and (A + B) is not a multiple of π, so, sinA, sinB and sin(A + B) are non-zero cot(A + B) = cos(A + B)/sin(A + B) From eq(1) and (3), we get cot(A + B) = cos A cos B – sin A sin B/sin A cos B + cos A sin B Now divide the numerator and denominator by sin A sin B we get cot(A + B) = (7) As we know that So, on putting B = -B, we get Here, we will establish two sets of transformation formulae: Factorization and Defactorization formulae. In trigonometry, defactorisation means converting a product into a sum or difference. The defactorization formulae are: (1) 2 sin A cos B = sin (A + B) + sin (A – B) Proof: As we know that sin (A + B) = sin A cos B + cos A sin B ...........................(1) sin (A – B) = sin A cos B – cos A sin B ...........................(2) By adding eq(1) and (2), we get 2 sin A cos B = sin (A + B) + sin (A – B) (2) 2 cos A sin B = sin (A + B) – sin (A – B) Proof: As we know that sin (A + B) = sin A cos B + cos A sin B ...........................(1) sin (A – B) = sin A cos B – cos A sin B ...........................(2) By subtracting eq(2) from (1), we get 2 cos A sin B = sin (A + B) – sin (A – B) (3) 2 cos A cos B = cos (A + B) + cos (A – B) Proof: As we know that cos (A + B) = cos A cos B – sin A sin B ...........................(1) cos (A – B) = cos A cos B + sin A sin B ...........................(2) By adding eq(1) and (2), we get 2 cos A cos B = cos (A + B) + cos (A – B) (4) 2 sin A sin B = cos (A – B) – cos (A + B) Proof: cos (A + B) = cos A cos B – sin A sin B ...........................(1) cos (A – B) = cos A cos B + sin A sin B ...........................(2) By subtracting eq(3) from (4), we get 2 sin A sin B = cos (A – B) – cos (A + B) Example 1. Convert each of the following products into the sum or difference. (i) 2 sin 40° cos 30° (ii) 2 sin 75° sin 15° (iii) cos 75° cos 15° Solution: (i) Given: A = 40° and B = 30° Now put all these values in the formula, 2 sin A cos B = sin (A + B) + sin (A – B) We get 2 sin 40° cos 30° = sin (40 + 30) + sin (40 – 30) = sin (70°) + sin (10°) (ii) Given: A = 75° and B = 15° Now put all these values in the formula, 2 sin A sin B = cos (A – B) – cos (A + B) We get 2 sin 75° sin 15° = cos (75-15) – cos (75+15) = cos (60°) – cos (90°) (iii) Given: A = 75° and B = 15° Now put all these values in the formula, 2 cos A cos B = cos (A + B) + cos (A – B) We get cos 75° cos 15° = 1/2(cos (75+15) + cos (75-15)) = 1/2 (cos (90°) + cos (60°)) Example 2. Solve for Solution: Using the formula 2 cos A cos B = cos (A + B) + cos (A – B) = = = Hence, = 0 In trigonometry, factorisation means converting sum or difference into the product. The factorisation formulae are: (1) sin (C) + sin (D) = 2 sin cos Proof: We have 2 sin A cos B = sin (A + B) + sin (A – B) ...........................(1) So now, we are taking A + B = C and A – B = D Then, A = and B = Now put all these values in eq(1), we get 2 sin () cos () = sin (C) + sin (D) Or sin (C) + sin (D) = 2 sin () cos () (2) sin (C) – sin (D) = 2 cos sin Proof: We have 2 cos A sin B = sin (A + B) – sin (A – B) ...........................(1) So now, we are taking A + B = C and A – B = D Then, A = and B = Now put all these values in eq(1), we get 2 cos () sin () = sin (C) – sin (D) Or sin (C) – sin (D) = 2 cos () sin () (3) cos (C) + cos (D) = 2 cos cos Proof: We have 2 cos A cos B = cos (A + B) + cos (A – B) ...........................(1) So now, we are taking A + B = C and A – B = D Then, A = and B = Now put all these values in eq(1), we get 2 cos () cos () = cos (C) + cos (D) Or cos (C) + cos (D) = 2 cos () cos () (4) cos (C) – cos (D) = 2 sin sin Proof: We have 2 sin A sin B = cos (A – B) – cos (A + B) ...........................(1) So now, we are taking A + B = C and A – B = D Then, A = and B = Now put all these values in eq(1), we get 2 sin () sin () = cos (C) – cos (D) Or cos (C) – cos (D) = 2 sin () sin () Explain 1. Express each of the following as a product (i) sin 40° + sin 20° (ii) sin 60° – sin 20° (iii) cos 40° + cos 80° Solution: (i) Given: C = 40° and D = 20° Now put all these values in the formula, sin (C) + sin (D) = 2 sin cos We get sin 40° + sin 20° = 2 sin cos = 2 sin cos = 2 sin 30° cos 10° (ii) Given: C = 60° and D = 20° Now put all these values in the formula, sin (C) – sin (D) = 2 cos sin We get sin 60° – sin 20° = 2 cos sin = 2 cos sin = 2 cos 40° sin 20° (iii) Given: C = 80° and D = 40° Now put all these values in the formula, cos (C) + cos (D) = 2 cos cos We get cos 40° + cos 80° = 2 cos cos = 2 cos cos = 2 cos 60° cos 20° Example 2. Prove that: 1 + cos 2x + cos 4x + cos 6x = 4 cos x cos 2x cos 3x Solution: Lets take LHS 1 + cos 2x + cos 4x + cos 6x Here, cos 0x = 1 So, (cos 0x + cos 2x) + (cos 4x + cos 6x) Using formula cos (C) + cos (D) = 2 cos cos We get (2 cos cos ) + (2 cos cos ) (2 cos x cos x) + (2 cos 5x cos x) Taking 2 cos x common, we have 2 cos x (cos x + cos 5x) Again using the formula cos (C) + cos (D) = 2 cos cos We get 2 cos x (2 cos cos ) 2 cos x (2 cos 3x cos 2x) 4 cos x cos 2x cos 3x LHS = RHS Hence proved The trigonometric ratios of an angle in a right triangle define the relationship between the angle and the length of its sides. sin 2x or cos 2x, etc. are also, one such trigonometrical formula, also known as double angle formula, as it has a double angle in it. (1) sin 2A = 2 sin A cos A Proof: As we know that sin (A + B) = sin A cos B + cos A sin B ....................(1) Now taking B = A, in eq(1), we get sin (A + A) = sin A cos A + cos A sin A sin 2A = 2 sin A cos A (2) cos 2A = cos2 A – sin2 A Proof: As we know that cos (A + B) = cos A cos B – sin A sin B ....................(1) Now taking B = A, in eq(1), we get cos (A + A) = cos A cos A + sin A sin A cos 2A = cos2 A – sin2 A (3) cos 2A = 2cos2 A – 1 Proof: As we know that cos 2A = cos2 A – sin2 A ....................(1) We also know that sin2 A + cos2 A = 1 So, sin2 A = 1 – cos2 A Now put the value of sin2 A in eq(1), we get cos 2A = cos2 A – (1 – cos2 A) cos 2A = cos2 A – 1 + cos2 A cos 2A = 2cos2 A – 1 (4) cos 2A = 1 – 2sin2 A Proof: As we know that cos 2A = 2cos2 A – 1 ....................(1) We also know that sin2 A + cos2 A = 1 So, cos2 A = 1 – sin2 A Now put the value of sin2 A in eq(1), we get cos 2A = 2(1 – sin2 A) – 1 cos 2A = 2 – 2sin2 A) – 1 cos 2A = 1 – 2sin2 A (5) cos 2A = Proof: As we know that cos 2A = cos2 A – sin2 A So, now dividing, by sin2 A + cos2 A = 1, we get cos 2A = Again dividing the numerator and denominator by cos2 A, we get cos 2A = cos 2A = (6) sin 2A = Proof: As we know that sin (A + B) = sin A cos B + cos A sin B ....................(1) Now taking B = A, in eq(1), we get sin (A + A) = sin A cos A + cos A sin A sin 2A = 2 sin A cos A As we also know that sin2 A + cos2 A = 1 So, now dividing, by sin2 A + cos2 A = 1, we get sin 2A = Now, on dividing the numerator and denominator by cos2 A, we get sin 2A = (7) tan 2A = Proof: As we know that ....................(1) Now taking B = A, in eq(1), we get tan(A + A) = tan 2A = Example: Prove that (i) = tan θ (ii) = cot θ (iii) cos 4x = 1 – 8 sin2x cos2x Solution: (i) sin 2θ = 2 sin θ cos θ ...........(from identity 1) and, 1 + cos 2θ = 2cos2θ ...........(from identity 3) = = tan θ Hence Proved (ii) sin 2θ = 2 sin θ cos θ ...........(from identity 1) and, 1 – cos 2θ = 2sin2θ ...........(from identity 4) = = cot θ Hence Proved (iii) cos 4x = cos 2(2x) = 1 – 2sin2(2x) (using 16) = 1 – 2(sin(2x))2 = 1 – 2(2 sin x cos x)2 (using identity 1) = 1 – 2(4 sin2 x cos2 x) cos 4x = 1 – 8 sin2 x cos2 x Hence Proved The trigonometric ratios of an angle in a right triangle define the relationship between the angle and the length of its sides. sin 3x or cos 3x, etc. are also, one such trigonometrical formula, also known as triple angle formula, as it has a triple angle in it. (1) sin 3A = 3sin A – 4 sin3A Proof: Let’s take LHS sin 3A = sin(2A + A) Using identity sin (A + B) = sin A cos B + cos A sin B We get sin 3A = sin 2A cos A + cos 2A sin A = 2sin A cos A cos A + (1 – 2 sin2A)sin A = 2sin A(1 – sin2A) + sin A – 2 sin3A = 2sin A – 2sin3A + sin A – 2 sin3A sin 3A = 3sin A – 4 sin3A (2) cos 3A = 4 cos3A – 3cos A Proof: Let’s take LHS sin 3A = sin(2A + A) Using identity cos (A + B) = cos A cos B – sin A sin B We get cos 3A = cos 2A cos A – sin 2A sin A = (2cos2A – 1)cos A – 2sin A cos A sin A = (2cos2A – 1)cos A – 2cos A(1 – cos2A) = 2cos3A – cos A – 2cos A + 2cos3A) cos 3A = 4 cos3A – 3cos A (3) tan 3A = Proof: Let’s take LHS tan 3A = tan(2A + A) Using identity We get tan 3A = = = = Example 1. Solve 2sin3xsinx. Solution: We have 2sin3xsinx We also write as y = y1 . y2 ....(1) Here, y1 = 2sin3x y2 = sinx So let’s solve y1 = 2sin3x Using identity sin 3A = 3sin A – 4 sin3A We get y1 = 2(sin x – 4 sin3x) = 2sin x – 8 sin3x Now put these values in eq(1), we get y = (2sin x – 8 sin3x)(sinx) = 2sin2 x – 8 sin4x Example 2. Solve 2tan3xtanx. Solution: We have 2tan3xtanx We also write as y = y1 . y2 ....(1) Here, y1 = 2tan3x y2 = tanx So let’s solve y1 = 2tan3x Using identity tan 3A = We get y1 = 2() = Now put these values in eq(1), we get y = ()(tanx) = simmytarika5 Picked Trigonometry & Height and Distances Class 11 School Learning School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Dec, 2021" }, { "code": null, "e": 502, "s": 52, "text": "Trigonometry is a branch of mathematics, which deal with the angles, lengths, and heights of triangles and their relationships. It had played an important role to calculate complex functions or large distances which were not possible to calculate without trigonometry. While solving problems with trigonometry, we came across many situations where we have to calculate the trigonometric solutions for the sum of angles or differences of angles. E.g." }, { "code": null, "e": 509, "s": 502, "text": "Here, " }, { "code": null, "e": 579, "s": 509, "text": "Which is a tangent trigonometric ratio, with an angle opposite to BC." }, { "code": null, "e": 591, "s": 579, "text": "tan(θ+Φ) = " }, { "code": null, "e": 895, "s": 591, "text": "If θ = 30° and Φ = 45°. We know the trigonometric angles of 45° and 30°, but we don’t know the trigonometric angle of (45° + 30° = 75°). So, to simplify these types of problems. We will get to learn trigonometric formulae or identities of sum and differences of two angles which will make things easier." }, { "code": null, "e": 1052, "s": 895, "text": "Before moving further first we will see the signs of the trigonometric functions in the four quadrants. These signs play an important role in trigonometry. " }, { "code": null, "e": 1123, "s": 1052, "text": "Now we are going to find the trigonometric identities. As we know that" }, { "code": null, "e": 1141, "s": 1123, "text": "sin(-x) = – sin x" }, { "code": null, "e": 1157, "s": 1141, "text": "cos(-x) = cos x" }, { "code": null, "e": 1289, "s": 1157, "text": "Because only cos and sec are positive in the fourth quadrant. So, now we prove some results regarding sum and difference of angles:" }, { "code": null, "e": 1458, "s": 1289, "text": "Let’s consider a unit circle (having radius as 1) with centre at the origin. Let x be the ∠DOA and y be the ∠AOB. Then (x + y) is the ∠DOB. Also let (– y) be the ∠DOC. " }, { "code": null, "e": 1506, "s": 1458, "text": "Therefore, the coordinates of A, B, C and D are" }, { "code": null, "e": 1525, "s": 1506, "text": "A = (cos x, sin x)" }, { "code": null, "e": 1556, "s": 1525, "text": "B = [cos (x + y), sin (x + y)]" }, { "code": null, "e": 1584, "s": 1556, "text": "C = [cos (– y), sin (– y)] " }, { "code": null, "e": 1596, "s": 1584, "text": "D = (1, 0)." }, { "code": null, "e": 1612, "s": 1596, "text": "As, ∠AOB = ∠COD" }, { "code": null, "e": 1643, "s": 1612, "text": "Adding, ∠BOC both side, we get" }, { "code": null, "e": 1669, "s": 1643, "text": "∠AOB + ∠BOC = ∠COD + ∠BOC" }, { "code": null, "e": 1681, "s": 1669, "text": "∠AOC = ∠BOD" }, { "code": null, "e": 1700, "s": 1681, "text": "In △ AOC and △ BOD" }, { "code": null, "e": 1727, "s": 1700, "text": "OA = OB (radius of circle)" }, { "code": null, "e": 1756, "s": 1727, "text": "∠AOC = ∠BOD (Proved earlier)" }, { "code": null, "e": 1783, "s": 1756, "text": "OC = OD (radius of circle)" }, { "code": null, "e": 1816, "s": 1783, "text": "△ AOC ≅ △ BOD by SAS congruency." }, { "code": null, "e": 1847, "s": 1816, "text": "By using distance formula, for" }, { "code": null, "e": 1894, "s": 1847, "text": "AC2 = [cos x – cos (– y)]2 + [sin x – sin(–y]2" }, { "code": null, "e": 1954, "s": 1894, "text": "AC2 = 2 – 2 (cos x cos y – sin x sin y) ................(i)" }, { "code": null, "e": 1963, "s": 1954, "text": "And, now" }, { "code": null, "e": 2005, "s": 1963, "text": "Similarly, using distance formula, we get" }, { "code": null, "e": 2051, "s": 2005, "text": "BD2 = [1 – cos (x + y)]2 + [0 – sin (x + y)]2" }, { "code": null, "e": 2096, "s": 2051, "text": "BD2 = 2 – 2 cos (x + y) ................(ii)" }, { "code": null, "e": 2114, "s": 2096, "text": "As, △ AOC ≅ △ BOD" }, { "code": null, "e": 2136, "s": 2114, "text": "AC = BD, So AC2 = BD2" }, { "code": null, "e": 2166, "s": 2136, "text": "From eq(i) and eq(ii), we get" }, { "code": null, "e": 2220, "s": 2166, "text": "2 – 2 (cos x cos y – sin x sin y) = 2 – 2 cos (x + y)" }, { "code": null, "e": 2225, "s": 2220, "text": "So, " }, { "code": null, "e": 2265, "s": 2225, "text": "cos (x + y) = cos x cos y – sin x sin y" }, { "code": null, "e": 2285, "s": 2265, "text": "Take y = -y, we get" }, { "code": null, "e": 2334, "s": 2285, "text": "cos (x + (-y)) = cos x cos (-y) – sin x sin (-y)" }, { "code": null, "e": 2374, "s": 2334, "text": "cos (x – y) = cos x cos y + sin x sin y" }, { "code": null, "e": 2387, "s": 2374, "text": "Now, taking " }, { "code": null, "e": 2438, "s": 2387, "text": "cos (-(x + y)) = cos ((-x) – y) (cos (-θ) = sin θ)" }, { "code": null, "e": 2478, "s": 2438, "text": "sin (x – y) = sin x cos y – cos x sin y" }, { "code": null, "e": 2498, "s": 2478, "text": "take y = -y, we get" }, { "code": null, "e": 2547, "s": 2498, "text": "sin (x – (-y)) = sin x cos (-y) – cos x sin (-y)" }, { "code": null, "e": 2587, "s": 2547, "text": "sin (x + y) = sin x cos y + cos x sin y" }, { "code": null, "e": 2668, "s": 2587, "text": "The derived formulae for trigonometric ratios of compound angles are as follows:" }, { "code": null, "e": 2736, "s": 2668, "text": "sin (A + B) = sin A cos B + cos A sin B ....................(1)" }, { "code": null, "e": 2806, "s": 2736, "text": "sin (A – B) = sin A cos B – cos A sin B ....................(2)" }, { "code": null, "e": 2874, "s": 2806, "text": "cos (A + B) = cos A cos B – sin A sin B ....................(3)" }, { "code": null, "e": 2942, "s": 2874, "text": "cos (A – B) = cos A cos B + sin A sin B ....................(4)" }, { "code": null, "e": 3018, "s": 2942, "text": "By using these formulae, we can obtain some important and mostly used form:" }, { "code": null, "e": 3033, "s": 3018, "text": "(1) Take, A = " }, { "code": null, "e": 3058, "s": 3033, "text": "In eq(1) and (3), we get" }, { "code": null, "e": 3075, "s": 3058, "text": "sin (+B) = cos B" }, { "code": null, "e": 3094, "s": 3075, "text": "cos (+B) = – sin A" }, { "code": null, "e": 3110, "s": 3094, "text": "(2) Take, A = π" }, { "code": null, "e": 3144, "s": 3110, "text": "In eq(1), (2), (3) and (4) we get" }, { "code": null, "e": 3166, "s": 3144, "text": "sin (π + B) = – sin B" }, { "code": null, "e": 3186, "s": 3166, "text": "sin (π – B) = sin B" }, { "code": null, "e": 3208, "s": 3186, "text": "cos (π ± B) = – cos B" }, { "code": null, "e": 3225, "s": 3208, "text": "(3) Take, A = 2π" }, { "code": null, "e": 3249, "s": 3225, "text": "In eq(2) and (4) we get" }, { "code": null, "e": 3272, "s": 3249, "text": "sin (2π – B) = – sin B" }, { "code": null, "e": 3293, "s": 3272, "text": "cos (2π – B) = cos B" }, { "code": null, "e": 3340, "s": 3293, "text": "Similarly for cot A, tan A, sec A, and cosec A" }, { "code": null, "e": 3345, "s": 3340, "text": "(4) " }, { "code": null, "e": 3443, "s": 3345, "text": "Here, A, B, and (A + B) is not an odd multiple of π/2, so, cosA, cosB and cos(A + B) are non-zero" }, { "code": null, "e": 3478, "s": 3443, "text": "tan(A + B) = sin(A + B)/cos(A + B)" }, { "code": null, "e": 3505, "s": 3478, "text": "From eq(1) and (3), we get" }, { "code": null, "e": 3570, "s": 3505, "text": "tan(A + B) = sin A cos B + cos A sin B/cos A cos B – sin A sin B" }, { "code": null, "e": 3633, "s": 3570, "text": "Now divide the numerator and denominator by cos A cos B we get" }, { "code": null, "e": 3647, "s": 3633, "text": "tan(A + B) = " }, { "code": null, "e": 3652, "s": 3647, "text": "(5) " }, { "code": null, "e": 3669, "s": 3652, "text": "As we know that " }, { "code": null, "e": 3699, "s": 3669, "text": "So, on putting B = -B, we get" }, { "code": null, "e": 3704, "s": 3699, "text": "(6) " }, { "code": null, "e": 3795, "s": 3704, "text": "Here, A, B, and (A + B) is not a multiple of π, so, sinA, sinB and sin(A + B) are non-zero" }, { "code": null, "e": 3830, "s": 3795, "text": "cot(A + B) = cos(A + B)/sin(A + B)" }, { "code": null, "e": 3857, "s": 3830, "text": "From eq(1) and (3), we get" }, { "code": null, "e": 3922, "s": 3857, "text": "cot(A + B) = cos A cos B – sin A sin B/sin A cos B + cos A sin B" }, { "code": null, "e": 3985, "s": 3922, "text": "Now divide the numerator and denominator by sin A sin B we get" }, { "code": null, "e": 3999, "s": 3985, "text": "cot(A + B) = " }, { "code": null, "e": 4004, "s": 3999, "text": "(7) " }, { "code": null, "e": 4021, "s": 4004, "text": "As we know that " }, { "code": null, "e": 4051, "s": 4021, "text": "So, on putting B = -B, we get" }, { "code": null, "e": 4157, "s": 4051, "text": "Here, we will establish two sets of transformation formulae: Factorization and Defactorization formulae. " }, { "code": null, "e": 4277, "s": 4157, "text": "In trigonometry, defactorisation means converting a product into a sum or difference. The defactorization formulae are:" }, { "code": null, "e": 4323, "s": 4277, "text": "(1) 2 sin A cos B = sin (A + B) + sin (A – B)" }, { "code": null, "e": 4330, "s": 4323, "text": "Proof:" }, { "code": null, "e": 4347, "s": 4330, "text": "As we know that " }, { "code": null, "e": 4422, "s": 4347, "text": "sin (A + B) = sin A cos B + cos A sin B ...........................(1)" }, { "code": null, "e": 4498, "s": 4422, "text": "sin (A – B) = sin A cos B – cos A sin B ...........................(2)" }, { "code": null, "e": 4530, "s": 4498, "text": "By adding eq(1) and (2), we get" }, { "code": null, "e": 4572, "s": 4530, "text": "2 sin A cos B = sin (A + B) + sin (A – B)" }, { "code": null, "e": 4618, "s": 4572, "text": "(2) 2 cos A sin B = sin (A + B) – sin (A – B)" }, { "code": null, "e": 4625, "s": 4618, "text": "Proof:" }, { "code": null, "e": 4642, "s": 4625, "text": "As we know that " }, { "code": null, "e": 4717, "s": 4642, "text": "sin (A + B) = sin A cos B + cos A sin B ...........................(1)" }, { "code": null, "e": 4793, "s": 4717, "text": "sin (A – B) = sin A cos B – cos A sin B ...........................(2)" }, { "code": null, "e": 4831, "s": 4793, "text": "By subtracting eq(2) from (1), we get" }, { "code": null, "e": 4873, "s": 4831, "text": "2 cos A sin B = sin (A + B) – sin (A – B)" }, { "code": null, "e": 4919, "s": 4873, "text": "(3) 2 cos A cos B = cos (A + B) + cos (A – B)" }, { "code": null, "e": 4926, "s": 4919, "text": "Proof:" }, { "code": null, "e": 4943, "s": 4926, "text": "As we know that " }, { "code": null, "e": 5018, "s": 4943, "text": "cos (A + B) = cos A cos B – sin A sin B ...........................(1)" }, { "code": null, "e": 5093, "s": 5018, "text": "cos (A – B) = cos A cos B + sin A sin B ...........................(2)" }, { "code": null, "e": 5125, "s": 5093, "text": "By adding eq(1) and (2), we get" }, { "code": null, "e": 5167, "s": 5125, "text": "2 cos A cos B = cos (A + B) + cos (A – B)" }, { "code": null, "e": 5214, "s": 5167, "text": "(4) 2 sin A sin B = cos (A – B) – cos (A + B) " }, { "code": null, "e": 5221, "s": 5214, "text": "Proof:" }, { "code": null, "e": 5296, "s": 5221, "text": "cos (A + B) = cos A cos B – sin A sin B ...........................(1)" }, { "code": null, "e": 5371, "s": 5296, "text": "cos (A – B) = cos A cos B + sin A sin B ...........................(2)" }, { "code": null, "e": 5409, "s": 5371, "text": "By subtracting eq(3) from (4), we get" }, { "code": null, "e": 5453, "s": 5409, "text": "2 sin A sin B = cos (A – B) – cos (A + B) " }, { "code": null, "e": 5531, "s": 5453, "text": "Example 1. Convert each of the following products into the sum or difference." }, { "code": null, "e": 5553, "s": 5531, "text": "(i) 2 sin 40° cos 30°" }, { "code": null, "e": 5576, "s": 5553, "text": "(ii) 2 sin 75° sin 15°" }, { "code": null, "e": 5598, "s": 5576, "text": "(iii) cos 75° cos 15°" }, { "code": null, "e": 5608, "s": 5598, "text": "Solution:" }, { "code": null, "e": 5639, "s": 5608, "text": "(i) Given: A = 40° and B = 30°" }, { "code": null, "e": 5681, "s": 5639, "text": "Now put all these values in the formula, " }, { "code": null, "e": 5723, "s": 5681, "text": "2 sin A cos B = sin (A + B) + sin (A – B)" }, { "code": null, "e": 5730, "s": 5723, "text": "We get" }, { "code": null, "e": 5781, "s": 5730, "text": "2 sin 40° cos 30° = sin (40 + 30) + sin (40 – 30) " }, { "code": null, "e": 5806, "s": 5781, "text": "= sin (70°) + sin (10°) " }, { "code": null, "e": 5838, "s": 5806, "text": "(ii) Given: A = 75° and B = 15°" }, { "code": null, "e": 5880, "s": 5838, "text": "Now put all these values in the formula, " }, { "code": null, "e": 5922, "s": 5880, "text": "2 sin A sin B = cos (A – B) – cos (A + B)" }, { "code": null, "e": 5929, "s": 5922, "text": "We get" }, { "code": null, "e": 5975, "s": 5929, "text": "2 sin 75° sin 15° = cos (75-15) – cos (75+15)" }, { "code": null, "e": 5999, "s": 5975, "text": "= cos (60°) – cos (90°)" }, { "code": null, "e": 6032, "s": 5999, "text": "(iii) Given: A = 75° and B = 15°" }, { "code": null, "e": 6074, "s": 6032, "text": "Now put all these values in the formula, " }, { "code": null, "e": 6116, "s": 6074, "text": "2 cos A cos B = cos (A + B) + cos (A – B)" }, { "code": null, "e": 6123, "s": 6116, "text": "We get" }, { "code": null, "e": 6172, "s": 6123, "text": "cos 75° cos 15° = 1/2(cos (75+15) + cos (75-15))" }, { "code": null, "e": 6202, "s": 6172, "text": "= 1/2 (cos (90°) + cos (60°))" }, { "code": null, "e": 6224, "s": 6202, "text": "Example 2. Solve for " }, { "code": null, "e": 6234, "s": 6224, "text": "Solution:" }, { "code": null, "e": 6252, "s": 6234, "text": "Using the formula" }, { "code": null, "e": 6295, "s": 6252, "text": "2 cos A cos B = cos (A + B) + cos (A – B) " }, { "code": null, "e": 6300, "s": 6297, "text": "= " }, { "code": null, "e": 6303, "s": 6300, "text": "= " }, { "code": null, "e": 6306, "s": 6303, "text": "= " }, { "code": null, "e": 6314, "s": 6306, "text": "Hence, " }, { "code": null, "e": 6319, "s": 6314, "text": " = 0" }, { "code": null, "e": 6435, "s": 6319, "text": "In trigonometry, factorisation means converting sum or difference into the product. The factorisation formulae are:" }, { "code": null, "e": 6470, "s": 6435, "text": "(1) sin (C) + sin (D) = 2 sin cos " }, { "code": null, "e": 6477, "s": 6470, "text": "Proof:" }, { "code": null, "e": 6486, "s": 6477, "text": "We have " }, { "code": null, "e": 6559, "s": 6486, "text": "2 sin A cos B = sin (A + B) + sin (A – B) ...........................(1)" }, { "code": null, "e": 6582, "s": 6559, "text": "So now, we are taking " }, { "code": null, "e": 6606, "s": 6582, "text": "A + B = C and A – B = D" }, { "code": null, "e": 6626, "s": 6606, "text": "Then, A = and B = " }, { "code": null, "e": 6668, "s": 6626, "text": "Now put all these values in eq(1), we get" }, { "code": null, "e": 6704, "s": 6668, "text": "2 sin () cos () = sin (C) + sin (D)" }, { "code": null, "e": 6708, "s": 6704, "text": "Or " }, { "code": null, "e": 6744, "s": 6708, "text": "sin (C) + sin (D) = 2 sin () cos ()" }, { "code": null, "e": 6780, "s": 6744, "text": "(2) sin (C) – sin (D) = 2 cos sin " }, { "code": null, "e": 6787, "s": 6780, "text": "Proof:" }, { "code": null, "e": 6796, "s": 6787, "text": "We have " }, { "code": null, "e": 6869, "s": 6796, "text": "2 cos A sin B = sin (A + B) – sin (A – B) ...........................(1)" }, { "code": null, "e": 6892, "s": 6869, "text": "So now, we are taking " }, { "code": null, "e": 6916, "s": 6892, "text": "A + B = C and A – B = D" }, { "code": null, "e": 6936, "s": 6916, "text": "Then, A = and B = " }, { "code": null, "e": 6978, "s": 6936, "text": "Now put all these values in eq(1), we get" }, { "code": null, "e": 7014, "s": 6978, "text": "2 cos () sin () = sin (C) – sin (D)" }, { "code": null, "e": 7018, "s": 7014, "text": "Or " }, { "code": null, "e": 7054, "s": 7018, "text": "sin (C) – sin (D) = 2 cos () sin ()" }, { "code": null, "e": 7090, "s": 7054, "text": "(3) cos (C) + cos (D) = 2 cos cos " }, { "code": null, "e": 7097, "s": 7090, "text": "Proof:" }, { "code": null, "e": 7106, "s": 7097, "text": "We have " }, { "code": null, "e": 7179, "s": 7106, "text": "2 cos A cos B = cos (A + B) + cos (A – B) ...........................(1)" }, { "code": null, "e": 7202, "s": 7179, "text": "So now, we are taking " }, { "code": null, "e": 7226, "s": 7202, "text": "A + B = C and A – B = D" }, { "code": null, "e": 7246, "s": 7226, "text": "Then, A = and B = " }, { "code": null, "e": 7288, "s": 7246, "text": "Now put all these values in eq(1), we get" }, { "code": null, "e": 7324, "s": 7288, "text": "2 cos () cos () = cos (C) + cos (D)" }, { "code": null, "e": 7328, "s": 7324, "text": "Or " }, { "code": null, "e": 7364, "s": 7328, "text": "cos (C) + cos (D) = 2 cos () cos ()" }, { "code": null, "e": 7401, "s": 7364, "text": "(4) cos (C) – cos (D) = 2 sin sin " }, { "code": null, "e": 7408, "s": 7401, "text": "Proof:" }, { "code": null, "e": 7417, "s": 7408, "text": "We have " }, { "code": null, "e": 7491, "s": 7417, "text": "2 sin A sin B = cos (A – B) – cos (A + B) ...........................(1)" }, { "code": null, "e": 7514, "s": 7491, "text": "So now, we are taking " }, { "code": null, "e": 7538, "s": 7514, "text": "A + B = C and A – B = D" }, { "code": null, "e": 7558, "s": 7538, "text": "Then, A = and B = " }, { "code": null, "e": 7600, "s": 7558, "text": "Now put all these values in eq(1), we get" }, { "code": null, "e": 7636, "s": 7600, "text": "2 sin () sin () = cos (C) – cos (D)" }, { "code": null, "e": 7640, "s": 7636, "text": "Or " }, { "code": null, "e": 7676, "s": 7640, "text": "cos (C) – cos (D) = 2 sin () sin ()" }, { "code": null, "e": 7730, "s": 7676, "text": "Explain 1. Express each of the following as a product" }, { "code": null, "e": 7752, "s": 7730, "text": "(i) sin 40° + sin 20°" }, { "code": null, "e": 7775, "s": 7752, "text": "(ii) sin 60° – sin 20°" }, { "code": null, "e": 7799, "s": 7775, "text": "(iii) cos 40° + cos 80°" }, { "code": null, "e": 7809, "s": 7799, "text": "Solution:" }, { "code": null, "e": 7840, "s": 7809, "text": "(i) Given: C = 40° and D = 20°" }, { "code": null, "e": 7882, "s": 7840, "text": "Now put all these values in the formula, " }, { "code": null, "e": 7914, "s": 7882, "text": "sin (C) + sin (D) = 2 sin cos " }, { "code": null, "e": 7921, "s": 7914, "text": "We get" }, { "code": null, "e": 7952, "s": 7921, "text": "sin 40° + sin 20° = 2 sin cos " }, { "code": null, "e": 7966, "s": 7952, "text": "= 2 sin cos " }, { "code": null, "e": 7986, "s": 7966, "text": "= 2 sin 30° cos 10°" }, { "code": null, "e": 8018, "s": 7986, "text": "(ii) Given: C = 60° and D = 20°" }, { "code": null, "e": 8060, "s": 8018, "text": "Now put all these values in the formula, " }, { "code": null, "e": 8091, "s": 8060, "text": "sin (C) – sin (D) = 2 cos sin " }, { "code": null, "e": 8098, "s": 8091, "text": "We get" }, { "code": null, "e": 8129, "s": 8098, "text": "sin 60° – sin 20° = 2 cos sin " }, { "code": null, "e": 8143, "s": 8129, "text": "= 2 cos sin " }, { "code": null, "e": 8163, "s": 8143, "text": "= 2 cos 40° sin 20°" }, { "code": null, "e": 8196, "s": 8163, "text": "(iii) Given: C = 80° and D = 40°" }, { "code": null, "e": 8239, "s": 8196, "text": " Now put all these values in the formula, " }, { "code": null, "e": 8270, "s": 8239, "text": "cos (C) + cos (D) = 2 cos cos " }, { "code": null, "e": 8277, "s": 8270, "text": "We get" }, { "code": null, "e": 8309, "s": 8277, "text": "cos 40° + cos 80° = 2 cos cos " }, { "code": null, "e": 8323, "s": 8309, "text": "= 2 cos cos " }, { "code": null, "e": 8343, "s": 8323, "text": "= 2 cos 60° cos 20°" }, { "code": null, "e": 8419, "s": 8343, "text": "Example 2. Prove that: 1 + cos 2x + cos 4x + cos 6x = 4 cos x cos 2x cos 3x" }, { "code": null, "e": 8429, "s": 8419, "text": "Solution:" }, { "code": null, "e": 8443, "s": 8429, "text": "Lets take LHS" }, { "code": null, "e": 8472, "s": 8443, "text": "1 + cos 2x + cos 4x + cos 6x" }, { "code": null, "e": 8489, "s": 8472, "text": "Here, cos 0x = 1" }, { "code": null, "e": 8493, "s": 8489, "text": "So," }, { "code": null, "e": 8531, "s": 8493, "text": "(cos 0x + cos 2x) + (cos 4x + cos 6x)" }, { "code": null, "e": 8545, "s": 8531, "text": "Using formula" }, { "code": null, "e": 8577, "s": 8545, "text": "cos (C) + cos (D) = 2 cos cos " }, { "code": null, "e": 8584, "s": 8577, "text": "We get" }, { "code": null, "e": 8613, "s": 8584, "text": "(2 cos cos ) + (2 cos cos )" }, { "code": null, "e": 8648, "s": 8613, "text": "(2 cos x cos x) + (2 cos 5x cos x)" }, { "code": null, "e": 8679, "s": 8648, "text": "Taking 2 cos x common, we have" }, { "code": null, "e": 8704, "s": 8679, "text": "2 cos x (cos x + cos 5x)" }, { "code": null, "e": 8729, "s": 8704, "text": "Again using the formula " }, { "code": null, "e": 8760, "s": 8729, "text": "cos (C) + cos (D) = 2 cos cos " }, { "code": null, "e": 8767, "s": 8760, "text": "We get" }, { "code": null, "e": 8788, "s": 8767, "text": "2 cos x (2 cos cos )" }, { "code": null, "e": 8814, "s": 8788, "text": "2 cos x (2 cos 3x cos 2x)" }, { "code": null, "e": 8836, "s": 8814, "text": "4 cos x cos 2x cos 3x" }, { "code": null, "e": 8846, "s": 8836, "text": "LHS = RHS" }, { "code": null, "e": 8859, "s": 8846, "text": "Hence proved" }, { "code": null, "e": 9122, "s": 8859, "text": "The trigonometric ratios of an angle in a right triangle define the relationship between the angle and the length of its sides. sin 2x or cos 2x, etc. are also, one such trigonometrical formula, also known as double angle formula, as it has a double angle in it." }, { "code": null, "e": 9149, "s": 9122, "text": "(1) sin 2A = 2 sin A cos A" }, { "code": null, "e": 9156, "s": 9149, "text": "Proof:" }, { "code": null, "e": 9173, "s": 9156, "text": "As we know that " }, { "code": null, "e": 9237, "s": 9173, "text": "sin (A + B) = sin A cos B + cos A sin B ....................(1)" }, { "code": null, "e": 9272, "s": 9237, "text": "Now taking B = A, in eq(1), we get" }, { "code": null, "e": 9312, "s": 9272, "text": "sin (A + A) = sin A cos A + cos A sin A" }, { "code": null, "e": 9337, "s": 9312, "text": "sin 2A = 2 sin A cos A " }, { "code": null, "e": 9366, "s": 9337, "text": "(2) cos 2A = cos2 A – sin2 A" }, { "code": null, "e": 9373, "s": 9366, "text": "Proof:" }, { "code": null, "e": 9390, "s": 9373, "text": "As we know that " }, { "code": null, "e": 9454, "s": 9390, "text": "cos (A + B) = cos A cos B – sin A sin B ....................(1)" }, { "code": null, "e": 9489, "s": 9454, "text": "Now taking B = A, in eq(1), we get" }, { "code": null, "e": 9529, "s": 9489, "text": "cos (A + A) = cos A cos A + sin A sin A" }, { "code": null, "e": 9554, "s": 9529, "text": "cos 2A = cos2 A – sin2 A" }, { "code": null, "e": 9581, "s": 9554, "text": "(3) cos 2A = 2cos2 A – 1 " }, { "code": null, "e": 9588, "s": 9581, "text": "Proof:" }, { "code": null, "e": 9605, "s": 9588, "text": "As we know that " }, { "code": null, "e": 9654, "s": 9605, "text": "cos 2A = cos2 A – sin2 A ....................(1)" }, { "code": null, "e": 9673, "s": 9654, "text": "We also know that " }, { "code": null, "e": 9693, "s": 9673, "text": "sin2 A + cos2 A = 1" }, { "code": null, "e": 9717, "s": 9693, "text": "So, sin2 A = 1 – cos2 A" }, { "code": null, "e": 9762, "s": 9717, "text": "Now put the value of sin2 A in eq(1), we get" }, { "code": null, "e": 9793, "s": 9762, "text": "cos 2A = cos2 A – (1 – cos2 A)" }, { "code": null, "e": 9822, "s": 9793, "text": "cos 2A = cos2 A – 1 + cos2 A" }, { "code": null, "e": 9843, "s": 9822, "text": "cos 2A = 2cos2 A – 1" }, { "code": null, "e": 9868, "s": 9843, "text": "(4) cos 2A = 1 – 2sin2 A" }, { "code": null, "e": 9875, "s": 9868, "text": "Proof:" }, { "code": null, "e": 9892, "s": 9875, "text": "As we know that " }, { "code": null, "e": 9937, "s": 9892, "text": "cos 2A = 2cos2 A – 1 ....................(1)" }, { "code": null, "e": 9956, "s": 9937, "text": "We also know that " }, { "code": null, "e": 9976, "s": 9956, "text": "sin2 A + cos2 A = 1" }, { "code": null, "e": 10000, "s": 9976, "text": "So, cos2 A = 1 – sin2 A" }, { "code": null, "e": 10045, "s": 10000, "text": "Now put the value of sin2 A in eq(1), we get" }, { "code": null, "e": 10072, "s": 10045, "text": "cos 2A = 2(1 – sin2 A) – 1" }, { "code": null, "e": 10098, "s": 10072, "text": "cos 2A = 2 – 2sin2 A) – 1" }, { "code": null, "e": 10120, "s": 10098, "text": "cos 2A = 1 – 2sin2 A " }, { "code": null, "e": 10135, "s": 10120, "text": "(5) cos 2A = " }, { "code": null, "e": 10142, "s": 10135, "text": "Proof:" }, { "code": null, "e": 10159, "s": 10142, "text": "As we know that " }, { "code": null, "e": 10185, "s": 10159, "text": "cos 2A = cos2 A – sin2 A " }, { "code": null, "e": 10234, "s": 10185, "text": "So, now dividing, by sin2 A + cos2 A = 1, we get" }, { "code": null, "e": 10244, "s": 10234, "text": "cos 2A = " }, { "code": null, "e": 10307, "s": 10244, "text": "Again dividing the numerator and denominator by cos2 A, we get" }, { "code": null, "e": 10317, "s": 10307, "text": "cos 2A = " }, { "code": null, "e": 10327, "s": 10317, "text": "cos 2A = " }, { "code": null, "e": 10341, "s": 10327, "text": "(6) sin 2A = " }, { "code": null, "e": 10348, "s": 10341, "text": "Proof:" }, { "code": null, "e": 10365, "s": 10348, "text": "As we know that " }, { "code": null, "e": 10429, "s": 10365, "text": "sin (A + B) = sin A cos B + cos A sin B ....................(1)" }, { "code": null, "e": 10464, "s": 10429, "text": "Now taking B = A, in eq(1), we get" }, { "code": null, "e": 10504, "s": 10464, "text": "sin (A + A) = sin A cos A + cos A sin A" }, { "code": null, "e": 10529, "s": 10504, "text": "sin 2A = 2 sin A cos A " }, { "code": null, "e": 10570, "s": 10529, "text": "As we also know that sin2 A + cos2 A = 1" }, { "code": null, "e": 10619, "s": 10570, "text": "So, now dividing, by sin2 A + cos2 A = 1, we get" }, { "code": null, "e": 10629, "s": 10619, "text": "sin 2A = " }, { "code": null, "e": 10694, "s": 10629, "text": "Now, on dividing the numerator and denominator by cos2 A, we get" }, { "code": null, "e": 10704, "s": 10694, "text": "sin 2A = " }, { "code": null, "e": 10718, "s": 10704, "text": "(7) tan 2A = " }, { "code": null, "e": 10725, "s": 10718, "text": "Proof:" }, { "code": null, "e": 10742, "s": 10725, "text": "As we know that " }, { "code": null, "e": 10767, "s": 10742, "text": " ....................(1)" }, { "code": null, "e": 10802, "s": 10767, "text": "Now taking B = A, in eq(1), we get" }, { "code": null, "e": 10816, "s": 10802, "text": "tan(A + A) = " }, { "code": null, "e": 10826, "s": 10816, "text": "tan 2A = " }, { "code": null, "e": 10846, "s": 10826, "text": "Example: Prove that" }, { "code": null, "e": 10859, "s": 10846, "text": "(i) = tan θ" }, { "code": null, "e": 10873, "s": 10859, "text": "(ii) = cot θ" }, { "code": null, "e": 10906, "s": 10873, "text": "(iii) cos 4x = 1 – 8 sin2x cos2x" }, { "code": null, "e": 10916, "s": 10906, "text": "Solution:" }, { "code": null, "e": 10972, "s": 10916, "text": "(i) sin 2θ = 2 sin θ cos θ ...........(from identity 1)" }, { "code": null, "e": 11027, "s": 10972, "text": "and, 1 + cos 2θ = 2cos2θ ...........(from identity 3)" }, { "code": null, "e": 11030, "s": 11027, "text": "= " }, { "code": null, "e": 11039, "s": 11030, "text": "= tan θ " }, { "code": null, "e": 11052, "s": 11039, "text": "Hence Proved" }, { "code": null, "e": 11109, "s": 11052, "text": "(ii) sin 2θ = 2 sin θ cos θ ...........(from identity 1)" }, { "code": null, "e": 11164, "s": 11109, "text": "and, 1 – cos 2θ = 2sin2θ ...........(from identity 4)" }, { "code": null, "e": 11167, "s": 11164, "text": "= " }, { "code": null, "e": 11175, "s": 11167, "text": "= cot θ" }, { "code": null, "e": 11188, "s": 11175, "text": "Hence Proved" }, { "code": null, "e": 11213, "s": 11188, "text": "(iii) cos 4x = cos 2(2x)" }, { "code": null, "e": 11240, "s": 11213, "text": "= 1 – 2sin2(2x) (using 16)" }, { "code": null, "e": 11258, "s": 11240, "text": "= 1 – 2(sin(2x))2" }, { "code": null, "e": 11304, "s": 11258, "text": "= 1 – 2(2 sin x cos x)2 (using identity 1)" }, { "code": null, "e": 11329, "s": 11304, "text": "= 1 – 2(4 sin2 x cos2 x)" }, { "code": null, "e": 11358, "s": 11329, "text": "cos 4x = 1 – 8 sin2 x cos2 x" }, { "code": null, "e": 11371, "s": 11358, "text": "Hence Proved" }, { "code": null, "e": 11634, "s": 11371, "text": "The trigonometric ratios of an angle in a right triangle define the relationship between the angle and the length of its sides. sin 3x or cos 3x, etc. are also, one such trigonometrical formula, also known as triple angle formula, as it has a triple angle in it." }, { "code": null, "e": 11664, "s": 11634, "text": "(1) sin 3A = 3sin A – 4 sin3A" }, { "code": null, "e": 11671, "s": 11664, "text": "Proof:" }, { "code": null, "e": 11686, "s": 11671, "text": "Let’s take LHS" }, { "code": null, "e": 11707, "s": 11686, "text": "sin 3A = sin(2A + A)" }, { "code": null, "e": 11723, "s": 11707, "text": "Using identity " }, { "code": null, "e": 11763, "s": 11723, "text": "sin (A + B) = sin A cos B + cos A sin B" }, { "code": null, "e": 11770, "s": 11763, "text": "We get" }, { "code": null, "e": 11807, "s": 11770, "text": "sin 3A = sin 2A cos A + cos 2A sin A" }, { "code": null, "e": 11849, "s": 11807, "text": "= 2sin A cos A cos A + (1 – 2 sin2A)sin A" }, { "code": null, "e": 11887, "s": 11849, "text": "= 2sin A(1 – sin2A) + sin A – 2 sin3A" }, { "code": null, "e": 11923, "s": 11887, "text": "= 2sin A – 2sin3A + sin A – 2 sin3A" }, { "code": null, "e": 11949, "s": 11923, "text": "sin 3A = 3sin A – 4 sin3A" }, { "code": null, "e": 11980, "s": 11949, "text": "(2) cos 3A = 4 cos3A – 3cos A " }, { "code": null, "e": 11987, "s": 11980, "text": "Proof:" }, { "code": null, "e": 12002, "s": 11987, "text": "Let’s take LHS" }, { "code": null, "e": 12023, "s": 12002, "text": "sin 3A = sin(2A + A)" }, { "code": null, "e": 12039, "s": 12023, "text": "Using identity " }, { "code": null, "e": 12079, "s": 12039, "text": "cos (A + B) = cos A cos B – sin A sin B" }, { "code": null, "e": 12086, "s": 12079, "text": "We get" }, { "code": null, "e": 12123, "s": 12086, "text": "cos 3A = cos 2A cos A – sin 2A sin A" }, { "code": null, "e": 12164, "s": 12123, "text": "= (2cos2A – 1)cos A – 2sin A cos A sin A" }, { "code": null, "e": 12204, "s": 12164, "text": "= (2cos2A – 1)cos A – 2cos A(1 – cos2A)" }, { "code": null, "e": 12240, "s": 12204, "text": "= 2cos3A – cos A – 2cos A + 2cos3A)" }, { "code": null, "e": 12267, "s": 12240, "text": "cos 3A = 4 cos3A – 3cos A " }, { "code": null, "e": 12281, "s": 12267, "text": "(3) tan 3A = " }, { "code": null, "e": 12288, "s": 12281, "text": "Proof:" }, { "code": null, "e": 12303, "s": 12288, "text": "Let’s take LHS" }, { "code": null, "e": 12324, "s": 12303, "text": "tan 3A = tan(2A + A)" }, { "code": null, "e": 12340, "s": 12324, "text": "Using identity " }, { "code": null, "e": 12347, "s": 12340, "text": "We get" }, { "code": null, "e": 12357, "s": 12347, "text": "tan 3A = " }, { "code": null, "e": 12360, "s": 12357, "text": "= " }, { "code": null, "e": 12363, "s": 12360, "text": "= " }, { "code": null, "e": 12366, "s": 12363, "text": "= " }, { "code": null, "e": 12395, "s": 12366, "text": "Example 1. Solve 2sin3xsinx." }, { "code": null, "e": 12405, "s": 12395, "text": "Solution:" }, { "code": null, "e": 12424, "s": 12405, "text": "We have 2sin3xsinx" }, { "code": null, "e": 12462, "s": 12424, "text": "We also write as y = y1 . y2 ....(1)" }, { "code": null, "e": 12480, "s": 12462, "text": "Here, y1 = 2sin3x" }, { "code": null, "e": 12490, "s": 12480, "text": "y2 = sinx" }, { "code": null, "e": 12517, "s": 12490, "text": "So let’s solve y1 = 2sin3x" }, { "code": null, "e": 12533, "s": 12517, "text": "Using identity " }, { "code": null, "e": 12559, "s": 12533, "text": "sin 3A = 3sin A – 4 sin3A" }, { "code": null, "e": 12566, "s": 12559, "text": "We get" }, { "code": null, "e": 12590, "s": 12566, "text": "y1 = 2(sin x – 4 sin3x)" }, { "code": null, "e": 12609, "s": 12590, "text": "= 2sin x – 8 sin3x" }, { "code": null, "e": 12647, "s": 12609, "text": "Now put these values in eq(1), we get" }, { "code": null, "e": 12676, "s": 12647, "text": "y = (2sin x – 8 sin3x)(sinx)" }, { "code": null, "e": 12696, "s": 12676, "text": "= 2sin2 x – 8 sin4x" }, { "code": null, "e": 12725, "s": 12696, "text": "Example 2. Solve 2tan3xtanx." }, { "code": null, "e": 12735, "s": 12725, "text": "Solution:" }, { "code": null, "e": 12754, "s": 12735, "text": "We have 2tan3xtanx" }, { "code": null, "e": 12792, "s": 12754, "text": "We also write as y = y1 . y2 ....(1)" }, { "code": null, "e": 12810, "s": 12792, "text": "Here, y1 = 2tan3x" }, { "code": null, "e": 12820, "s": 12810, "text": "y2 = tanx" }, { "code": null, "e": 12847, "s": 12820, "text": "So let’s solve y1 = 2tan3x" }, { "code": null, "e": 12863, "s": 12847, "text": "Using identity " }, { "code": null, "e": 12873, "s": 12863, "text": "tan 3A = " }, { "code": null, "e": 12880, "s": 12873, "text": "We get" }, { "code": null, "e": 12889, "s": 12880, "text": "y1 = 2()" }, { "code": null, "e": 12892, "s": 12889, "text": "= " }, { "code": null, "e": 12930, "s": 12892, "text": "Now put these values in eq(1), we get" }, { "code": null, "e": 12943, "s": 12930, "text": "y = ()(tanx)" }, { "code": null, "e": 12946, "s": 12943, "text": "= " }, { "code": null, "e": 12959, "s": 12946, "text": "simmytarika5" }, { "code": null, "e": 12966, "s": 12959, "text": "Picked" }, { "code": null, "e": 13002, "s": 12966, "text": "Trigonometry & Height and Distances" }, { "code": null, "e": 13011, "s": 13002, "text": "Class 11" }, { "code": null, "e": 13027, "s": 13011, "text": "School Learning" }, { "code": null, "e": 13046, "s": 13027, "text": "School Mathematics" } ]
Josephus problem | Set 2 (A Simple Solution when k = 2)
02 Dec, 2021 There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.We have discussed a generalized solution in below set 1.Josephus problem | Set 1 (A O(n) Solution)In this post, a special case is discussed when k = 2 Examples : Input : n = 5 Output : The person at position 3 survives Explanation : Firstly, the person at position 2 is killed, then at 4, then at 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. Input : n = 14 Output : The person at position 13 survives Below are some interesting facts. In first round all even positioned persons are killed. For second round two cases arise If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively.If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively. If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively.If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively. If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively. If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively. If n is even and a person is in position x in current round, then the person was in position 2x – 1 in previous round.If n is odd and a person is in position x in current round, then the person was in position 2x + 1 in previous round.From above facts, we can recursively define the formula for finding position of survivor. Let f(n) be position of survivor for input n, the value of f(n) can be recursively written as below. If n is even f(n) = 2f(n/2) - 1 Else f(n) = 2f((n-1)/2) + 1 Solution of above recurrence is f(n) = 2(n - 2floor(Log2n) + 1 = 2n - 21 + floor(Log2n) + 1 Below is the implementation to find value of above formula. C++ Java Python3 C# PHP Javascript // C/C++ program to find solution of Josephus// problem when size of step is 2.#include <stdio.h> // Returns position of survivor among a circle// of n persons and every second person being// killedint josephus(int n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1;} // Driver Program to test above functionint main(){ int n = 16; printf("The chosen place is %d", josephus(n)); return 0;} // Java program to find solution of Josephus// problem when size of step is 2.import java.io.*; class GFG { // Returns position of survivor among // a circle of n persons and every // second person being killed static int josephus(int n) { // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1; } // Driver Program to test above function public static void main(String[] args) { int n = 16; System.out.println("The chosen place is " + josephus(n)); }} // This Code is Contributed by Anuj_67 # Python3 program to find solution of# Josephus problem when size of step is 2. # Returns position of survivor among a# circle of n persons and every second# person being killeddef josephus(n): # Find value of 2 ^ (1 + floor(Log n)) # which is a power of 2 whose value # is just above n. p = 1 while p <= n: p *= 2 # Return 2n - 2^(1 + floor(Logn)) + 1 return (2 * n) - p + 1 # Driver Coden = 16print ("The chosen place is", josephus(n)) # This code is contributed by Shreyanshi Arun. // C# program to find solution of Josephus// problem when size of step is 2.using System; class GFG { // Returns position of survivor among // a circle of n persons and every // second person being killed static int josephus(int n) { // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1; } // Driver Program to test above function static void Main() { int n = 16; Console.Write("The chosen place is " + josephus(n)); }} // This Code is Contributed by Anuj_67 <?php// PHP program to find solution// of Josephus problem when// size of step is 2. // Returns position of survivor// among a circle of n persons// and every second person being// killedfunction josephus($n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. $p = 1; while ($p <= $n) $p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * $n) - $p + 1;} // Driver Code$n = 16;echo "The chosen place is ", josephus($n); // This code is contributed by ajit.?> <script> // Javascript program to find solution of Josephus// problem when size of step is 2. // Returns position of survivor among// a circle of n persons and every// second person being killedfunction josephus(n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. let p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1;} // Driver codelet n = 16; document.write("The chosen place is " + josephus(n)); // This code is contributed by susmitakundugoaldanga </script> The chosen place is 1 Time complexity of above solution is O(Log n).This article is contributed by Rahul Jain. An another interesting solution to the problem while k=2 can be given based on an observation, that we just have to left rotate the binary representation of N to get the required answer. A working code for the same is provided below considering number to be 64-bit number. Below is the implementation of the above approach: C++ Python3 // C++ program to find solution of Josephus// problem when size of step is 2.#include <bits/stdc++.h> using namespace std; // Returns position of survivor among a circle// of n persons and every second person being// killedint josephus(int n){ // An interesting observation is that // for every number of power of two // answer is 1 always. if (!(n & (n - 1)) && n) { return 1; } // The trick is just to right rotate the // binary representation of n once. // Find whether the number shed off // during left shift is set or not bitset<64> Arr(n); // shifting the bitset Arr // f will become true once leftmost // set bit is found bool f = false; for (int i = 63; i >= 0; --i) { if (Arr[i] == 1 && !f) { f = true; Arr[i] = Arr[i - 1]; } if (f) { // shifting bits Arr[i] = Arr[i - 1]; } } Arr[0] = 1; int res; // changing bitset to int res = (int)(Arr.to_ulong()); return res;} // Driver Program to test above functionint main(){ int n = 16; printf("The chosen place is %d", josephus(n)); return 0;} # Python 3 program to find solution of Josephus# problem when size of step is 2. # Returns position of survivor among a circle# of n persons and every second person being# killeddef josephus(n): # An interesting observation is that # for every number of power of two # answer is 1 always. if (~(n & (n - 1)) and n) : return 1 # The trick is just to right rotate the # binary representation of n once. # Find whether the number shed off # during left shift is set or not Arr=list(map(lambda x:int(x),list(bin(n)[2:]))) Arr=[0]*(64-len(Arr))+Arr # shifting the bitset Arr # f will become true once leftmost # set bit is found f = False for i in range(63,-1,-1) : if (Arr[i] == 1 and not f) : f = True Arr[i] = Arr[i - 1] if (f) : # shifting bits Arr[i] = Arr[i - 1] Arr[0] = 1 # changing bitset to int res = int(''.join(Arr),2) return res # Driver Program to test above functionif __name__ == '__main__': n = 16 print("The chosen place is", josephus(n)) The chosen place is 1 Time Complexity : O(log(n))Auxiliary Space: O(log(n)) This idea is contributed by Anukul Chand. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t vt_m Cyberfreak susmitakundugoaldanga pankajsharmagfg amartyaghoshgfg Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Dec, 2021" }, { "code": null, "e": 877, "s": 54, "text": "There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.We have discussed a generalized solution in below set 1.Josephus problem | Set 1 (A O(n) Solution)In this post, a special case is discussed when k = 2" }, { "code": null, "e": 890, "s": 877, "text": "Examples : " }, { "code": null, "e": 1185, "s": 890, "text": "Input : n = 5\nOutput : The person at position 3 survives\nExplanation : Firstly, the person at position 2 is killed, \nthen at 4, then at 1 is killed. Finally, the person at \nposition 5 is killed. So the person at position 3 survives.\n\nInput : n = 14\nOutput : The person at position 13 survives" }, { "code": null, "e": 1220, "s": 1185, "text": "Below are some interesting facts. " }, { "code": null, "e": 1275, "s": 1220, "text": "In first round all even positioned persons are killed." }, { "code": null, "e": 1649, "s": 1275, "text": "For second round two cases arise If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively.If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively." }, { "code": null, "e": 1990, "s": 1649, "text": "If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively.If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively." }, { "code": null, "e": 2171, "s": 1990, "text": "If n is even : For example n = 8. In first round, first 2 is killed, then 4, then 6, then 8. In second round, we have 1, 3, 5 and 7 in positions 1st, 2nd, 3rd and 4th respectively." }, { "code": null, "e": 2332, "s": 2171, "text": "If n is odd : For example n = 7. In first round, first 2 is killed, then 4, then 6. In second round, we have 3, 5, 7 in positions 1st, 2nd and 3rd respectively." }, { "code": null, "e": 2658, "s": 2332, "text": "If n is even and a person is in position x in current round, then the person was in position 2x – 1 in previous round.If n is odd and a person is in position x in current round, then the person was in position 2x + 1 in previous round.From above facts, we can recursively define the formula for finding position of survivor. " }, { "code": null, "e": 2828, "s": 2658, "text": "Let f(n) be position of survivor for input n, \nthe value of f(n) can be recursively written \nas below.\n\nIf n is even\n f(n) = 2f(n/2) - 1\nElse\n f(n) = 2f((n-1)/2) + 1" }, { "code": null, "e": 2861, "s": 2828, "text": "Solution of above recurrence is " }, { "code": null, "e": 2926, "s": 2861, "text": "f(n) = 2(n - 2floor(Log2n) + 1\n = 2n - 21 + floor(Log2n) + 1" }, { "code": null, "e": 2987, "s": 2926, "text": "Below is the implementation to find value of above formula. " }, { "code": null, "e": 2991, "s": 2987, "text": "C++" }, { "code": null, "e": 2996, "s": 2991, "text": "Java" }, { "code": null, "e": 3004, "s": 2996, "text": "Python3" }, { "code": null, "e": 3007, "s": 3004, "text": "C#" }, { "code": null, "e": 3011, "s": 3007, "text": "PHP" }, { "code": null, "e": 3022, "s": 3011, "text": "Javascript" }, { "code": "// C/C++ program to find solution of Josephus// problem when size of step is 2.#include <stdio.h> // Returns position of survivor among a circle// of n persons and every second person being// killedint josephus(int n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1;} // Driver Program to test above functionint main(){ int n = 16; printf(\"The chosen place is %d\", josephus(n)); return 0;}", "e": 3594, "s": 3022, "text": null }, { "code": "// Java program to find solution of Josephus// problem when size of step is 2.import java.io.*; class GFG { // Returns position of survivor among // a circle of n persons and every // second person being killed static int josephus(int n) { // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1; } // Driver Program to test above function public static void main(String[] args) { int n = 16; System.out.println(\"The chosen place is \" + josephus(n)); }} // This Code is Contributed by Anuj_67", "e": 4357, "s": 3594, "text": null }, { "code": "# Python3 program to find solution of# Josephus problem when size of step is 2. # Returns position of survivor among a# circle of n persons and every second# person being killeddef josephus(n): # Find value of 2 ^ (1 + floor(Log n)) # which is a power of 2 whose value # is just above n. p = 1 while p <= n: p *= 2 # Return 2n - 2^(1 + floor(Logn)) + 1 return (2 * n) - p + 1 # Driver Coden = 16print (\"The chosen place is\", josephus(n)) # This code is contributed by Shreyanshi Arun.", "e": 4876, "s": 4357, "text": null }, { "code": "// C# program to find solution of Josephus// problem when size of step is 2.using System; class GFG { // Returns position of survivor among // a circle of n persons and every // second person being killed static int josephus(int n) { // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. int p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1; } // Driver Program to test above function static void Main() { int n = 16; Console.Write(\"The chosen place is \" + josephus(n)); }} // This Code is Contributed by Anuj_67", "e": 5603, "s": 4876, "text": null }, { "code": "<?php// PHP program to find solution// of Josephus problem when// size of step is 2. // Returns position of survivor// among a circle of n persons// and every second person being// killedfunction josephus($n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. $p = 1; while ($p <= $n) $p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * $n) - $p + 1;} // Driver Code$n = 16;echo \"The chosen place is \", josephus($n); // This code is contributed by ajit.?>", "e": 6141, "s": 5603, "text": null }, { "code": "<script> // Javascript program to find solution of Josephus// problem when size of step is 2. // Returns position of survivor among// a circle of n persons and every// second person being killedfunction josephus(n){ // Find value of 2 ^ (1 + floor(Log n)) // which is a power of 2 whose value // is just above n. let p = 1; while (p <= n) p *= 2; // Return 2n - 2^(1+floor(Logn)) + 1 return (2 * n) - p + 1;} // Driver codelet n = 16; document.write(\"The chosen place is \" + josephus(n)); // This code is contributed by susmitakundugoaldanga </script>", "e": 6769, "s": 6141, "text": null }, { "code": null, "e": 6791, "s": 6769, "text": "The chosen place is 1" }, { "code": null, "e": 6883, "s": 6793, "text": "Time complexity of above solution is O(Log n).This article is contributed by Rahul Jain. " }, { "code": null, "e": 7157, "s": 6883, "text": "An another interesting solution to the problem while k=2 can be given based on an observation, that we just have to left rotate the binary representation of N to get the required answer. A working code for the same is provided below considering number to be 64-bit number. " }, { "code": null, "e": 7210, "s": 7157, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 7214, "s": 7210, "text": "C++" }, { "code": null, "e": 7222, "s": 7214, "text": "Python3" }, { "code": "// C++ program to find solution of Josephus// problem when size of step is 2.#include <bits/stdc++.h> using namespace std; // Returns position of survivor among a circle// of n persons and every second person being// killedint josephus(int n){ // An interesting observation is that // for every number of power of two // answer is 1 always. if (!(n & (n - 1)) && n) { return 1; } // The trick is just to right rotate the // binary representation of n once. // Find whether the number shed off // during left shift is set or not bitset<64> Arr(n); // shifting the bitset Arr // f will become true once leftmost // set bit is found bool f = false; for (int i = 63; i >= 0; --i) { if (Arr[i] == 1 && !f) { f = true; Arr[i] = Arr[i - 1]; } if (f) { // shifting bits Arr[i] = Arr[i - 1]; } } Arr[0] = 1; int res; // changing bitset to int res = (int)(Arr.to_ulong()); return res;} // Driver Program to test above functionint main(){ int n = 16; printf(\"The chosen place is %d\", josephus(n)); return 0;}", "e": 8378, "s": 7222, "text": null }, { "code": "# Python 3 program to find solution of Josephus# problem when size of step is 2. # Returns position of survivor among a circle# of n persons and every second person being# killeddef josephus(n): # An interesting observation is that # for every number of power of two # answer is 1 always. if (~(n & (n - 1)) and n) : return 1 # The trick is just to right rotate the # binary representation of n once. # Find whether the number shed off # during left shift is set or not Arr=list(map(lambda x:int(x),list(bin(n)[2:]))) Arr=[0]*(64-len(Arr))+Arr # shifting the bitset Arr # f will become true once leftmost # set bit is found f = False for i in range(63,-1,-1) : if (Arr[i] == 1 and not f) : f = True Arr[i] = Arr[i - 1] if (f) : # shifting bits Arr[i] = Arr[i - 1] Arr[0] = 1 # changing bitset to int res = int(''.join(Arr),2) return res # Driver Program to test above functionif __name__ == '__main__': n = 16 print(\"The chosen place is\", josephus(n))", "e": 9494, "s": 8378, "text": null }, { "code": null, "e": 9516, "s": 9494, "text": "The chosen place is 1" }, { "code": null, "e": 9990, "s": 9518, "text": "Time Complexity : O(log(n))Auxiliary Space: O(log(n)) This idea is contributed by Anukul Chand. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9996, "s": 9990, "text": "jit_t" }, { "code": null, "e": 10001, "s": 9996, "text": "vt_m" }, { "code": null, "e": 10012, "s": 10001, "text": "Cyberfreak" }, { "code": null, "e": 10034, "s": 10012, "text": "susmitakundugoaldanga" }, { "code": null, "e": 10050, "s": 10034, "text": "pankajsharmagfg" }, { "code": null, "e": 10066, "s": 10050, "text": "amartyaghoshgfg" }, { "code": null, "e": 10077, "s": 10066, "text": "Algorithms" }, { "code": null, "e": 10088, "s": 10077, "text": "Algorithms" } ]
Java Equivalent of C++’s lower_bound() Method
29 Apr, 2022 The lower_bound() method of C++ returns the index of the first element in the array which has a value not less than the key. This means that the function returns the index of the next smallest number just greater than or equal to that number. If there are multiple values that are equal to the number, lower_bound() returns the index of the first such value. Examples: Input : 4 6 10 12 18 18 20 20 30 45Output : lower_bound for element 18 at index 4 Input : 4 6 10 12 16 20 28Output : lower_bound for element 18 at index 5 Input : 24 26 40 56Output : lower_bound for element 18 at index 0 Input : 4 6 10 12 16 17Output : lower_bound for element 18 at index 6 Now let us discuss the methods in order to use lower_bound() method in order to get the index of the next smallest number just greater than or equal to that number. Methods: Naive ApproachUsing binary search iterativelyUsing binary search recursivelyUsing binarySearch() method of Arrays utility class Naive Approach Using binary search iteratively Using binary search recursively Using binarySearch() method of Arrays utility class Method 1: Using linear search We can use linear search to find lower_bound. We will iterate over the array starting from the 0th index until we find a value equal to or greater than the key. Below is the implementation of the above approach: Java // Java program for finding lower bound// using linear search // Importing Arrays utility classimport java.util.Arrays; // Main classclass GFG { // Method 1 // To find lower bound of given key static int lower(int array[], int key) { int lowerBound = 0; // Traversing the array using length function while (lowerBound < array.length) { // If key is lesser than current value if (key > array[lowerBound]) lowerBound++; // This is either the first occurrence of key // or value just greater than key else return lowerBound; } return lowerBound; } // Method 2 // Main driver method public static void main(String[] args) { // Custom array input over which lower bound is to // be operated by passing a key int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower(array, key)); }} 4 Time Complexity: O(N), where N is the number of elements in the array.Auxiliary Space: O(1) We can use an efficient approach of binary search to search the key in the sorted array in O(log2 n) as proposed in the below example Method 2: Using binary search iteratively Procedure: Initialize the low as 0 and high as N.Compare key with the middle element(arr[mid])If the middle element is greater than or equal to the key then update the high as a middle index(mid).Else update low as mid + 1.Repeat step 2 to step 4 until low is less than high.After all the above steps the low is the lower_bound of a key in the given array. Initialize the low as 0 and high as N. Compare key with the middle element(arr[mid]) If the middle element is greater than or equal to the key then update the high as a middle index(mid). Else update low as mid + 1. Repeat step 2 to step 4 until low is less than high. After all the above steps the low is the lower_bound of a key in the given array. Below is the implementation of the above approach: Java // Java program to Find lower bound// Using Binary Search Iteratively // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // Iterative approach to find lower bound // using binary search technique static int lower_bound(int array[], int key) { // Initialize starting index and // ending index int low = 0, high = array.length; int mid; // Till high does not crosses low while (low < high) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is less than or equal // to array[mid], then find in // left subarray if (key <= array[mid]) { high = mid; } // If key is greater than array[mid], // then find in right subarray else { low = mid + 1; } } // If key is greater than last element which is // array[n-1] then lower bound // does not exists in the array if (low < array.length && array[low] < key) { low++; } // Returning the lower_bound index return low; } // Method 2 // Driver main method public static void main(String[] args) { // Custom array and key input over which lower bound // is computed int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }} 4 Now as usual optimizing further away by providing a recursive approach following the same procedure as discussed above. Method 3: Using binary search recursively Java // Java program to Find Lower Bound// Using Binary Search Recursively // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To find lower bound using binary search technique static int recursive_lower_bound(int array[], int low, int high, int key) { // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If key is lesser than or equal to // array[mid] , then search // in left subarray if (key <= array[mid]) { return recursive_lower_bound(array, low, mid - 1, key); } // If key is greater than array[mid], // then find in right subarray return recursive_lower_bound(array, mid + 1, high, key); } // Method 2 // To compute the lower bound static int lower_bound(int array[], int key) { // Initialize starting index and // ending index int low = 0, high = array.length; // Call recursive lower bound method return recursive_lower_bound(array, low, high, key); } // Method 3 // Main driver method public static void main(String[] args) { // Custom array and key over which lower bound is to // be computed int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sorting the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }} 4 Method 4: Using binarySearch() method of Arrays utility class We can also use the in-built binary search implementation of the Arrays utility class (or Collections utility class). The function returns an index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array. Approach: Sort the array before applying binary searchSearch the index of the key in the sorted array using Arrays.binarysearch()Check if it key is present in the array, if true then return the index of the key as a positive value.Otherwise, a negative value which specifies the position at which the key should be added to the sorted array.If the key is present in the array we move leftwards to find its first occurrenceelse, we would have got a negative value of an index, using that to calculate the value of the “insertion point” (i.e, the index of the first element greater than the key)Print it. Sort the array before applying binary search Search the index of the key in the sorted array using Arrays.binarysearch()Check if it key is present in the array, if true then return the index of the key as a positive value.Otherwise, a negative value which specifies the position at which the key should be added to the sorted array. Check if it key is present in the array, if true then return the index of the key as a positive value. Otherwise, a negative value which specifies the position at which the key should be added to the sorted array. If the key is present in the array we move leftwards to find its first occurrence else, we would have got a negative value of an index, using that to calculate the value of the “insertion point” (i.e, the index of the first element greater than the key) Print it. Below is the implementation of the above approach: Java // Java program to find lower bound// using binarySearch() method of Arrays class // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To find lower bound using binary search // implementation of Arrays utility class static int lower_bound(int array[], int key) { int index = Arrays.binarySearch(array, key); // If key is not present in the array if (index < 0) { // Index specify the position of the key // when inserted in the sorted array // so the element currently present at // this position will be the lower bound return Math.abs(index) - 1; } // If key is present in the array // we move leftwards to find its first occurrence else { // Decrement the index to find the first // occurrence of the key while (index > 0) { // If previous value is same if (array[index - 1] == key) index--; // Previous value is different which means // current index is the first occurrence of // the key else return index; } return index; } } // Method 2 // Main driver method public static void main(String[] args) { // int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array before applying binary search Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }} 4 Note: We can also find mid-value via any one of them int mid = (high + low)/ 2; int mid = (low + high) >>> 1; anikakapoor amitap Blogathon-2021 Blogathon C++ Java Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2022" }, { "code": null, "e": 387, "s": 28, "text": "The lower_bound() method of C++ returns the index of the first element in the array which has a value not less than the key. This means that the function returns the index of the next smallest number just greater than or equal to that number. If there are multiple values that are equal to the number, lower_bound() returns the index of the first such value." }, { "code": null, "e": 399, "s": 387, "text": "Examples: " }, { "code": null, "e": 482, "s": 399, "text": "Input : 4 6 10 12 18 18 20 20 30 45Output : lower_bound for element 18 at index 4" }, { "code": null, "e": 556, "s": 482, "text": "Input : 4 6 10 12 16 20 28Output : lower_bound for element 18 at index 5" }, { "code": null, "e": 623, "s": 556, "text": "Input : 24 26 40 56Output : lower_bound for element 18 at index 0" }, { "code": null, "e": 694, "s": 623, "text": "Input : 4 6 10 12 16 17Output : lower_bound for element 18 at index 6" }, { "code": null, "e": 859, "s": 694, "text": "Now let us discuss the methods in order to use lower_bound() method in order to get the index of the next smallest number just greater than or equal to that number." }, { "code": null, "e": 868, "s": 859, "text": "Methods:" }, { "code": null, "e": 996, "s": 868, "text": "Naive ApproachUsing binary search iterativelyUsing binary search recursivelyUsing binarySearch() method of Arrays utility class" }, { "code": null, "e": 1011, "s": 996, "text": "Naive Approach" }, { "code": null, "e": 1043, "s": 1011, "text": "Using binary search iteratively" }, { "code": null, "e": 1075, "s": 1043, "text": "Using binary search recursively" }, { "code": null, "e": 1127, "s": 1075, "text": "Using binarySearch() method of Arrays utility class" }, { "code": null, "e": 1318, "s": 1127, "text": "Method 1: Using linear search We can use linear search to find lower_bound. We will iterate over the array starting from the 0th index until we find a value equal to or greater than the key." }, { "code": null, "e": 1369, "s": 1318, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1374, "s": 1369, "text": "Java" }, { "code": "// Java program for finding lower bound// using linear search // Importing Arrays utility classimport java.util.Arrays; // Main classclass GFG { // Method 1 // To find lower bound of given key static int lower(int array[], int key) { int lowerBound = 0; // Traversing the array using length function while (lowerBound < array.length) { // If key is lesser than current value if (key > array[lowerBound]) lowerBound++; // This is either the first occurrence of key // or value just greater than key else return lowerBound; } return lowerBound; } // Method 2 // Main driver method public static void main(String[] args) { // Custom array input over which lower bound is to // be operated by passing a key int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower(array, key)); }}", "e": 2507, "s": 1374, "text": null }, { "code": null, "e": 2509, "s": 2507, "text": "4" }, { "code": null, "e": 2601, "s": 2509, "text": "Time Complexity: O(N), where N is the number of elements in the array.Auxiliary Space: O(1)" }, { "code": null, "e": 2736, "s": 2601, "text": "We can use an efficient approach of binary search to search the key in the sorted array in O(log2 n) as proposed in the below example " }, { "code": null, "e": 2779, "s": 2736, "text": "Method 2: Using binary search iteratively" }, { "code": null, "e": 2790, "s": 2779, "text": "Procedure:" }, { "code": null, "e": 3136, "s": 2790, "text": "Initialize the low as 0 and high as N.Compare key with the middle element(arr[mid])If the middle element is greater than or equal to the key then update the high as a middle index(mid).Else update low as mid + 1.Repeat step 2 to step 4 until low is less than high.After all the above steps the low is the lower_bound of a key in the given array." }, { "code": null, "e": 3175, "s": 3136, "text": "Initialize the low as 0 and high as N." }, { "code": null, "e": 3221, "s": 3175, "text": "Compare key with the middle element(arr[mid])" }, { "code": null, "e": 3324, "s": 3221, "text": "If the middle element is greater than or equal to the key then update the high as a middle index(mid)." }, { "code": null, "e": 3352, "s": 3324, "text": "Else update low as mid + 1." }, { "code": null, "e": 3405, "s": 3352, "text": "Repeat step 2 to step 4 until low is less than high." }, { "code": null, "e": 3487, "s": 3405, "text": "After all the above steps the low is the lower_bound of a key in the given array." }, { "code": null, "e": 3538, "s": 3487, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3543, "s": 3538, "text": "Java" }, { "code": "// Java program to Find lower bound// Using Binary Search Iteratively // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // Iterative approach to find lower bound // using binary search technique static int lower_bound(int array[], int key) { // Initialize starting index and // ending index int low = 0, high = array.length; int mid; // Till high does not crosses low while (low < high) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is less than or equal // to array[mid], then find in // left subarray if (key <= array[mid]) { high = mid; } // If key is greater than array[mid], // then find in right subarray else { low = mid + 1; } } // If key is greater than last element which is // array[n-1] then lower bound // does not exists in the array if (low < array.length && array[low] < key) { low++; } // Returning the lower_bound index return low; } // Method 2 // Driver main method public static void main(String[] args) { // Custom array and key input over which lower bound // is computed int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }}", "e": 5210, "s": 3543, "text": null }, { "code": null, "e": 5212, "s": 5210, "text": "4" }, { "code": null, "e": 5332, "s": 5212, "text": "Now as usual optimizing further away by providing a recursive approach following the same procedure as discussed above." }, { "code": null, "e": 5374, "s": 5332, "text": "Method 3: Using binary search recursively" }, { "code": null, "e": 5379, "s": 5374, "text": "Java" }, { "code": "// Java program to Find Lower Bound// Using Binary Search Recursively // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To find lower bound using binary search technique static int recursive_lower_bound(int array[], int low, int high, int key) { // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If key is lesser than or equal to // array[mid] , then search // in left subarray if (key <= array[mid]) { return recursive_lower_bound(array, low, mid - 1, key); } // If key is greater than array[mid], // then find in right subarray return recursive_lower_bound(array, mid + 1, high, key); } // Method 2 // To compute the lower bound static int lower_bound(int array[], int key) { // Initialize starting index and // ending index int low = 0, high = array.length; // Call recursive lower bound method return recursive_lower_bound(array, low, high, key); } // Method 3 // Main driver method public static void main(String[] args) { // Custom array and key over which lower bound is to // be computed int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sorting the array using Arrays.sort() method Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }}", "e": 7083, "s": 5379, "text": null }, { "code": null, "e": 7085, "s": 7083, "text": "4" }, { "code": null, "e": 7147, "s": 7085, "text": "Method 4: Using binarySearch() method of Arrays utility class" }, { "code": null, "e": 7480, "s": 7147, "text": "We can also use the in-built binary search implementation of the Arrays utility class (or Collections utility class). The function returns an index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array. " }, { "code": null, "e": 7490, "s": 7480, "text": "Approach:" }, { "code": null, "e": 8083, "s": 7490, "text": "Sort the array before applying binary searchSearch the index of the key in the sorted array using Arrays.binarysearch()Check if it key is present in the array, if true then return the index of the key as a positive value.Otherwise, a negative value which specifies the position at which the key should be added to the sorted array.If the key is present in the array we move leftwards to find its first occurrenceelse, we would have got a negative value of an index, using that to calculate the value of the “insertion point” (i.e, the index of the first element greater than the key)Print it." }, { "code": null, "e": 8128, "s": 8083, "text": "Sort the array before applying binary search" }, { "code": null, "e": 8416, "s": 8128, "text": "Search the index of the key in the sorted array using Arrays.binarysearch()Check if it key is present in the array, if true then return the index of the key as a positive value.Otherwise, a negative value which specifies the position at which the key should be added to the sorted array." }, { "code": null, "e": 8519, "s": 8416, "text": "Check if it key is present in the array, if true then return the index of the key as a positive value." }, { "code": null, "e": 8630, "s": 8519, "text": "Otherwise, a negative value which specifies the position at which the key should be added to the sorted array." }, { "code": null, "e": 8712, "s": 8630, "text": "If the key is present in the array we move leftwards to find its first occurrence" }, { "code": null, "e": 8884, "s": 8712, "text": "else, we would have got a negative value of an index, using that to calculate the value of the “insertion point” (i.e, the index of the first element greater than the key)" }, { "code": null, "e": 8894, "s": 8884, "text": "Print it." }, { "code": null, "e": 8945, "s": 8894, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8950, "s": 8945, "text": "Java" }, { "code": "// Java program to find lower bound// using binarySearch() method of Arrays class // Importing Arrays utility classimport java.util.Arrays; // Main classpublic class GFG { // Method 1 // To find lower bound using binary search // implementation of Arrays utility class static int lower_bound(int array[], int key) { int index = Arrays.binarySearch(array, key); // If key is not present in the array if (index < 0) { // Index specify the position of the key // when inserted in the sorted array // so the element currently present at // this position will be the lower bound return Math.abs(index) - 1; } // If key is present in the array // we move leftwards to find its first occurrence else { // Decrement the index to find the first // occurrence of the key while (index > 0) { // If previous value is same if (array[index - 1] == key) index--; // Previous value is different which means // current index is the first occurrence of // the key else return index; } return index; } } // Method 2 // Main driver method public static void main(String[] args) { // int array[] = { 4, 6, 10, 12, 18, 18, 20, 20, 30, 45 }; int key = 18; // Sort the array before applying binary search Arrays.sort(array); // Printing the lower bound System.out.println(lower_bound(array, key)); }}", "e": 10633, "s": 8950, "text": null }, { "code": null, "e": 10635, "s": 10633, "text": "4" }, { "code": null, "e": 10688, "s": 10635, "text": "Note: We can also find mid-value via any one of them" }, { "code": null, "e": 10746, "s": 10688, "text": "int mid = (high + low)/ 2; int mid = (low + high) >>> 1;" }, { "code": null, "e": 10758, "s": 10746, "text": "anikakapoor" }, { "code": null, "e": 10765, "s": 10758, "text": "amitap" }, { "code": null, "e": 10780, "s": 10765, "text": "Blogathon-2021" }, { "code": null, "e": 10790, "s": 10780, "text": "Blogathon" }, { "code": null, "e": 10794, "s": 10790, "text": "C++" }, { "code": null, "e": 10799, "s": 10794, "text": "Java" }, { "code": null, "e": 10804, "s": 10799, "text": "Java" }, { "code": null, "e": 10808, "s": 10804, "text": "CPP" } ]
SQL | Union Clause
02 Sep, 2019 The Union Clause is used to combine two separate select statements and produce the result set as a union of both the select statements.NOTE: The fields to be used in both the select statements must be in same order, same number and same data type.The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION ALL must be used instead of just UNION. The fields to be used in both the select statements must be in same order, same number and same data type. The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION ALL must be used instead of just UNION. Basic Syntax: SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; Resultant set consists of distinct values. SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; Resultant set consists of duplicate values too. Queries To fetch distinct ROLL_NO from Student and Student_Details table.SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student_Details; Output:ROLL_NO1234 SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student_Details; Output: To fetch ROLL_NO from Student and Student_Details table including duplicate values.SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student_Details; Output:ROLL_NO123432 SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student_Details; Output: To fetch ROLL_NO , NAME from Student table WHERE ROLL_NO is greater than 3 and ROLL_NO , Branch from Student_Details table WHERE ROLL_NO is less than 3 , including duplicate values and finally sorting the data by ROLL_NO.SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3 UNION ALL SELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3 ORDER BY 1; Note:The column names in both the select statements can be different but the data type must be same.And in the result set the name of column used in the first select statement will appear. Output:ROLL_NONAME1Information Technology2Computer Science4SURESH SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3 UNION ALL SELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3 ORDER BY 1; Note:The column names in both the select statements can be different but the data type must be same.And in the result set the name of column used in the first select statement will appear. Output: This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SaranshSharma SQL-Clauses-Operators Articles DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2019" }, { "code": null, "e": 193, "s": 52, "text": "The Union Clause is used to combine two separate select statements and produce the result set as a union of both the select statements.NOTE:" }, { "code": null, "e": 440, "s": 193, "text": "The fields to be used in both the select statements must be in same order, same number and same data type.The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION ALL must be used instead of just UNION." }, { "code": null, "e": 547, "s": 440, "text": "The fields to be used in both the select statements must be in same order, same number and same data type." }, { "code": null, "e": 688, "s": 547, "text": "The Union clause produces distinct values in the result set, to fetch the duplicate values too UNION ALL must be used instead of just UNION." }, { "code": null, "e": 702, "s": 688, "text": "Basic Syntax:" }, { "code": null, "e": 822, "s": 702, "text": "SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;\n\nResultant set consists of distinct values.\n" }, { "code": null, "e": 951, "s": 822, "text": "SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;\n\nResultant set consists of duplicate values too.\n" }, { "code": null, "e": 959, "s": 951, "text": "Queries" }, { "code": null, "e": 1116, "s": 959, "text": "To fetch distinct ROLL_NO from Student and Student_Details table.SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student_Details; \nOutput:ROLL_NO1234 " }, { "code": null, "e": 1189, "s": 1116, "text": "SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student_Details; \n" }, { "code": null, "e": 1197, "s": 1189, "text": "Output:" }, { "code": null, "e": 1379, "s": 1199, "text": "To fetch ROLL_NO from Student and Student_Details table including duplicate values.SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student_Details; \nOutput:ROLL_NO123432" }, { "code": null, "e": 1456, "s": 1379, "text": "SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student_Details; \n" }, { "code": null, "e": 1464, "s": 1456, "text": "Output:" }, { "code": null, "e": 2076, "s": 1464, "text": "To fetch ROLL_NO , NAME from Student table WHERE ROLL_NO is greater than 3 and ROLL_NO , Branch from Student_Details table WHERE ROLL_NO is less than 3 , including duplicate values and finally sorting the data by ROLL_NO.SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3 \nUNION ALL\nSELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3\nORDER BY 1; \n\nNote:The column names in both the select statements can be different but the\n data type must be same.And in the result set the name of column used in the first\n select statement will appear. \nOutput:ROLL_NONAME1Information Technology2Computer Science4SURESH" }, { "code": null, "e": 2402, "s": 2076, "text": "SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3 \nUNION ALL\nSELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3\nORDER BY 1; \n\nNote:The column names in both the select statements can be different but the\n data type must be same.And in the result set the name of column used in the first\n select statement will appear. \n" }, { "code": null, "e": 2410, "s": 2402, "text": "Output:" }, { "code": null, "e": 2712, "s": 2410, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2837, "s": 2712, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2851, "s": 2837, "text": "SaranshSharma" }, { "code": null, "e": 2873, "s": 2851, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 2882, "s": 2873, "text": "Articles" }, { "code": null, "e": 2887, "s": 2882, "text": "DBMS" }, { "code": null, "e": 2891, "s": 2887, "text": "SQL" }, { "code": null, "e": 2896, "s": 2891, "text": "DBMS" }, { "code": null, "e": 2900, "s": 2896, "text": "SQL" } ]
Python – Loop through files of certain extensions
10 Jul, 2022 A directory is capable of storing multiple files and python can support a mechanism to loop over them. In this article, we will see different methods to iterate over certain files in a given directory or subdirectory. Path containing different files: This will be used for all methods. Method 1: Using listdir() In this method, we will use the os.listdir() function which is in the os library. This function returns a list of names of files present in the directory and no order. So to get the specific type of file from a particular directory we need to iterate through the directory and subdirectory and print the file with a specific extension. Syntax: listdir(path) Approach Import the os library and pass the directory in the os.listdir() function. Create a tuple having the extensions that you want to fetch. Through a loop iterate over all the files in the directory and print the file having a particular extension. The endswith() function checks if the file ends that particular extension or not is its does then it prints the file name. Example: Python3 # importing the libraryimport os # giving directory namedirname = 'D:\\AllData' # giving file extensionext = ('.exe', 'jpg') # iterating over all filesfor files in os.listdir(dirname): if files.endswith(ext): print(files) # printing file name of desired extension else: continue Output: Method 2: Using scandir() This method uses os.scandir() function returns an iterator that is used to access the file. The entries are yielded in arbitrary order. It lists the directories or files immediately under that directory. Syntax: scandir(path) Example: Python3 # importing the moduleimport os # directory namedirname = 'D:\\AllData' # extensionsext = ('.exe', 'jpg') # scanning the directory to get required filesfor files in os.scandir(dirname): if files.path.endswith(ext): print(files) # printing file name Output: Method 3: Using walk() In this method we will use the os.walk() function which yields us three tuples namely:-(dirpath, dirnames, filenames). Since it is a recursive process it will iterate over all descendant files in subdirectories and print the file name. A further approach is the same as the above method. Syntax: walk(path) Example: Python3 # importing the moduleimport os # giving directory namefolderdir = 'D:\\AllData' # giving file extensionsext = ('.pdf', '.mkv') # iterating over directory and subdirectory to get desired resultfor path, dirc, files in os.walk(folderdir): for name in files: if name.endswith(ext): print(name) # printing file name Output: Method 4: Using glob In this method, we will use the glob.iglob() function which comes under the glob library. Glob is a general term used to define techniques to match specified patterns according to rules related to Unix shell. Linux and Unix systems and shells also support glob and also provide function glob() in system libraries. In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The glob function accepts the directory/path and the \\**\\ pattern tells to look for the files with a specific extension in subfolders also that needs to be a recursive process so recursive should be set to True. Example: Python3 # importing the moduleimport glob # accessing and printing files in directory and subdirectoryfor filename in glob.glob('D:\\AllData\\**\\*.exe', recursive=True): print(filename) # print file name Output: Method 5: Using path() This method uses the Path() function from the pathlib module. The path function accepts the directory name as an argument and in glob function ‘**/*’ pattern is used to find files of specific extensions. It is also a recursive function and lists all files of the same directory and sub-directory. Syntax: path(path) Example: Python3 # importing the modulefrom pathlib import Path # directory namedirname = 'D:\\AllData' # giving directory name to Path() functionpaths = Path(dirname).glob('**/*.exe',) # iterating over all filesfor path in paths: print(path) # printing file name Output: punamsingh628700 mitalibhola94 Picked Python file-handling-programs python-file-handling Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2022" }, { "code": null, "e": 272, "s": 54, "text": "A directory is capable of storing multiple files and python can support a mechanism to loop over them. In this article, we will see different methods to iterate over certain files in a given directory or subdirectory." }, { "code": null, "e": 340, "s": 272, "text": "Path containing different files: This will be used for all methods." }, { "code": null, "e": 366, "s": 340, "text": "Method 1: Using listdir()" }, { "code": null, "e": 534, "s": 366, "text": "In this method, we will use the os.listdir() function which is in the os library. This function returns a list of names of files present in the directory and no order." }, { "code": null, "e": 702, "s": 534, "text": "So to get the specific type of file from a particular directory we need to iterate through the directory and subdirectory and print the file with a specific extension." }, { "code": null, "e": 710, "s": 702, "text": "Syntax:" }, { "code": null, "e": 724, "s": 710, "text": "listdir(path)" }, { "code": null, "e": 733, "s": 724, "text": "Approach" }, { "code": null, "e": 808, "s": 733, "text": "Import the os library and pass the directory in the os.listdir() function." }, { "code": null, "e": 869, "s": 808, "text": "Create a tuple having the extensions that you want to fetch." }, { "code": null, "e": 978, "s": 869, "text": "Through a loop iterate over all the files in the directory and print the file having a particular extension." }, { "code": null, "e": 1101, "s": 978, "text": "The endswith() function checks if the file ends that particular extension or not is its does then it prints the file name." }, { "code": null, "e": 1110, "s": 1101, "text": "Example:" }, { "code": null, "e": 1118, "s": 1110, "text": "Python3" }, { "code": "# importing the libraryimport os # giving directory namedirname = 'D:\\\\AllData' # giving file extensionext = ('.exe', 'jpg') # iterating over all filesfor files in os.listdir(dirname): if files.endswith(ext): print(files) # printing file name of desired extension else: continue", "e": 1418, "s": 1118, "text": null }, { "code": null, "e": 1426, "s": 1418, "text": "Output:" }, { "code": null, "e": 1452, "s": 1426, "text": "Method 2: Using scandir()" }, { "code": null, "e": 1656, "s": 1452, "text": "This method uses os.scandir() function returns an iterator that is used to access the file. The entries are yielded in arbitrary order. It lists the directories or files immediately under that directory." }, { "code": null, "e": 1664, "s": 1656, "text": "Syntax:" }, { "code": null, "e": 1678, "s": 1664, "text": "scandir(path)" }, { "code": null, "e": 1687, "s": 1678, "text": "Example:" }, { "code": null, "e": 1695, "s": 1687, "text": "Python3" }, { "code": "# importing the moduleimport os # directory namedirname = 'D:\\\\AllData' # extensionsext = ('.exe', 'jpg') # scanning the directory to get required filesfor files in os.scandir(dirname): if files.path.endswith(ext): print(files) # printing file name", "e": 1955, "s": 1695, "text": null }, { "code": null, "e": 1963, "s": 1955, "text": "Output:" }, { "code": null, "e": 1986, "s": 1963, "text": "Method 3: Using walk()" }, { "code": null, "e": 2274, "s": 1986, "text": "In this method we will use the os.walk() function which yields us three tuples namely:-(dirpath, dirnames, filenames). Since it is a recursive process it will iterate over all descendant files in subdirectories and print the file name. A further approach is the same as the above method." }, { "code": null, "e": 2282, "s": 2274, "text": "Syntax:" }, { "code": null, "e": 2293, "s": 2282, "text": "walk(path)" }, { "code": null, "e": 2302, "s": 2293, "text": "Example:" }, { "code": null, "e": 2310, "s": 2302, "text": "Python3" }, { "code": "# importing the moduleimport os # giving directory namefolderdir = 'D:\\\\AllData' # giving file extensionsext = ('.pdf', '.mkv') # iterating over directory and subdirectory to get desired resultfor path, dirc, files in os.walk(folderdir): for name in files: if name.endswith(ext): print(name) # printing file name", "e": 2645, "s": 2310, "text": null }, { "code": null, "e": 2653, "s": 2645, "text": "Output:" }, { "code": null, "e": 2675, "s": 2653, "text": "Method 4: Using glob " }, { "code": null, "e": 2990, "s": 2675, "text": "In this method, we will use the glob.iglob() function which comes under the glob library. Glob is a general term used to define techniques to match specified patterns according to rules related to Unix shell. Linux and Unix systems and shells also support glob and also provide function glob() in system libraries." }, { "code": null, "e": 3297, "s": 2990, "text": "In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The glob function accepts the directory/path and the \\\\**\\\\ pattern tells to look for the files with a specific extension in subfolders also that needs to be a recursive process so recursive should be set to True." }, { "code": null, "e": 3306, "s": 3297, "text": "Example:" }, { "code": null, "e": 3314, "s": 3306, "text": "Python3" }, { "code": "# importing the moduleimport glob # accessing and printing files in directory and subdirectoryfor filename in glob.glob('D:\\\\AllData\\\\**\\\\*.exe', recursive=True): print(filename) # print file name", "e": 3515, "s": 3314, "text": null }, { "code": null, "e": 3523, "s": 3515, "text": "Output:" }, { "code": null, "e": 3546, "s": 3523, "text": "Method 5: Using path()" }, { "code": null, "e": 3843, "s": 3546, "text": "This method uses the Path() function from the pathlib module. The path function accepts the directory name as an argument and in glob function ‘**/*’ pattern is used to find files of specific extensions. It is also a recursive function and lists all files of the same directory and sub-directory." }, { "code": null, "e": 3851, "s": 3843, "text": "Syntax:" }, { "code": null, "e": 3862, "s": 3851, "text": "path(path)" }, { "code": null, "e": 3871, "s": 3862, "text": "Example:" }, { "code": null, "e": 3879, "s": 3871, "text": "Python3" }, { "code": "# importing the modulefrom pathlib import Path # directory namedirname = 'D:\\\\AllData' # giving directory name to Path() functionpaths = Path(dirname).glob('**/*.exe',) # iterating over all filesfor path in paths: print(path) # printing file name", "e": 4130, "s": 3879, "text": null }, { "code": null, "e": 4138, "s": 4130, "text": "Output:" }, { "code": null, "e": 4155, "s": 4138, "text": "punamsingh628700" }, { "code": null, "e": 4169, "s": 4155, "text": "mitalibhola94" }, { "code": null, "e": 4176, "s": 4169, "text": "Picked" }, { "code": null, "e": 4206, "s": 4176, "text": "Python file-handling-programs" }, { "code": null, "e": 4227, "s": 4206, "text": "python-file-handling" }, { "code": null, "e": 4251, "s": 4227, "text": "Technical Scripter 2020" }, { "code": null, "e": 4258, "s": 4251, "text": "Python" }, { "code": null, "e": 4277, "s": 4258, "text": "Technical Scripter" } ]
Decrypt the String according to given algorithm
18 Aug, 2021 Given encrypted string str consisting of alphabets and numeric characters, the task is to decrypt the string and find the encrypted message. In order to decrypt the message, find every cluster of numeric characters representing a single alphabetic character which can be obtained by calculating the modulus of the number with 26 and the found value from the range [0, 25] can be mapped with the characters [‘a’, ‘z’]. For example, if str = “32ytAAcV4ui30hf10hj18” then the clusters of numeric characters will be {32, 4, 30, 10, 18} which gives {6, 4, 4, 10, 18} after performing modulus with 26 and can be mapped to {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}Examples: Input: str = “this50hi4huji70” Output: geeksInput: str = “a1s2d3f3” Output: bcdd Approach: The idea is to traverse each character one by one in a string, then check if it is a numeric character or not. If it is then concatenate it into a string. Finally, modulo that number string with 26. While doing modulo operation, we can’t simply do x % 26 as the number can be too large and will result in an integer overflow. To handle this, we will process all digits one by one and use the property that (A * B) mod C = ((A mod C) * (B mod C)) mod CThen, finally decode back each integer to character by 0, 1, 2, 3, ...25 to ‘a’, ‘b’, ‘c’, ...’z’, concatenate all characters and print the final result.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MOD = 26; // Function that returns (num % 26)int modulo_by_26(string num){ // Initialize result int res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res * 10 + (int)num[i] - '0') % MOD; return res;} // Function to return the decrypted stringstring decrypt_message(string s){ // To store the final decrypted answer string decrypted_str = ""; string num_found_so_far = ""; // One by one check for each character // if it is a numeric character for (int i = 0; i < s.length(); ++i) { if (s[i] >= '0' && s[i] <= '9') { num_found_so_far += s[i]; } else if (num_found_so_far.length() > 0) { // Modulo the number found in the string by 26 decrypted_str += 'a' + modulo_by_26(num_found_so_far); num_found_so_far = ""; } } if (num_found_so_far.length() > 0) { decrypted_str += 'a' + modulo_by_26(num_found_so_far); } return decrypted_str;} // Driver codeint main(){ string s = "32ytAAcV4ui30hf10hj18"; // Print the decrypted string cout << decrypt_message(s); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static int MOD = 26; // Function that returns (num % 26)static int modulo_by_26(String num){ // Initialize result int res = 0; // One by one process all digits of 'num' for(int i = 0; i < num.length(); i++) { res = ((res * 10 + (int)num.charAt(i) - '0') % MOD); } return res;} // Function to return the decrypted Stringstatic String decrypt_message(String s){ // To store the final decrypted answer String decrypted_str = ""; String num_found_so_far = ""; // One by one check for each character // if it is a numeric character for(int i = 0; i < s.length(); ++i) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { num_found_so_far += s.charAt(i); } else if (num_found_so_far.length() > 0) { // Modulo the number found in the String by 26 decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); num_found_so_far = ""; } } if (num_found_so_far.length() > 0) { decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver codepublic static void main(String[] args){ String s = "32ytAAcV4ui30hf10hj18"; // Print the decrypted string System.out.print(decrypt_message(s));}} // This code is contributed by amal kumar choubey # Python3 implementation of# the approachMOD = 26 # Function that returns# (num % 26)def modulo_by_26(num): # Initialize result res = 0 # One by one process all # digits of 'num' for i in range(len(num)): res = ((res * 10 + ord(num[i]) - ord('0')) % MOD) return res # Function to return the# decrypted stringdef decrypt_message(s): # To store the final # decrypted answer decrypted_str = "" num_found_so_far = "" # One by one check for # each character if it # is a numeric character for i in range(len(s)): if (s[i] >= '0' and s[i] <= '9'): num_found_so_far += s[i] elif (len(num_found_so_far) > 0): # Modulo the number found # in the string by 26 decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far))) num_found_so_far = "" if (len(num_found_so_far) > 0): decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far))) return decrypted_str # Driver codeif __name__ == "__main__": s = "32ytAAcV4ui30hf10hj18" # Print the decrypted string print(decrypt_message(s)) # This code is contributed by Chitranayal // C# implementation of the approachusing System;class GFG{ static int MOD = 26; // Function that returns (num % 26)static int modulo_by_26(String num){ // Initialize result int res = 0; // One by one process all digits of 'num' for(int i = 0; i < num.Length; i++) { res = ((res * 10 + (int)num[i] - '0') % MOD); } return res;} // Function to return the decrypted Stringstatic String decrypt_message(String s){ // To store the readonly decrypted answer String decrypted_str = ""; String num_found_so_far = ""; // One by one check for each character // if it is a numeric character for(int i = 0; i < s.Length; ++i) { if (s[i] >= '0' && s[i] <= '9') { num_found_so_far += s[i]; } else if (num_found_so_far.Length > 0) { // Modulo the number found // in the String by 26 decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); num_found_so_far = ""; } } if (num_found_so_far.Length > 0) { decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver codepublic static void Main(String[] args){ String s = "32ytAAcV4ui30hf10hj18"; // Print the decrypted string Console.Write(decrypt_message(s));}} // This code is contributed by amal kumar choubey <script> // JavaScript implementation of the approach let MOD = 26; // Function that returns (num % 26)function modulo_by_26(num){ // Initialize result let res = 0; // One by one process all digits of 'num' for(let i = 0; i < num.length; i++) { res = ((res * 10 + num[i].charCodeAt(0) - '0'.charCodeAt(0)) % MOD); } return res;} // Function to return the decrypted Stringfunction decrypt_message(s){ // To store the final decrypted answer let decrypted_str = ""; let num_found_so_far = ""; // One by one check for each character // if it is a numeric character for(let i = 0; i < s.length; ++i) { if (s[i].charCodeAt(0) >= '0'.charCodeAt(0) && s[i].charCodeAt(0) <= '9'.charCodeAt(0)) { num_found_so_far += s[i]; } else if (num_found_so_far.length > 0) { // Modulo the number found in the String by 26 decrypted_str += String.fromCharCode('a'.charCodeAt(0) + modulo_by_26(num_found_so_far)); num_found_so_far = ""; } } if (num_found_so_far.length > 0) { decrypted_str += String.fromCharCode('a'.charCodeAt(0) + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver code let s = "32ytAAcV4ui30hf10hj18"; // Print the decrypted stringdocument.write(decrypt_message(s)); // This code is contributed by rag2127 </script> geeks Time Complexity: O(N)Auxiliary Space: O(N) Amal Kumar Choubey ukasp rag2127 pankajsharmagfg encoding-decoding Modular Arithmetic Algorithms Mathematical Strings Strings Mathematical Modular Arithmetic Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2021" }, { "code": null, "e": 680, "s": 28, "text": "Given encrypted string str consisting of alphabets and numeric characters, the task is to decrypt the string and find the encrypted message. In order to decrypt the message, find every cluster of numeric characters representing a single alphabetic character which can be obtained by calculating the modulus of the number with 26 and the found value from the range [0, 25] can be mapped with the characters [‘a’, ‘z’]. For example, if str = “32ytAAcV4ui30hf10hj18” then the clusters of numeric characters will be {32, 4, 30, 10, 18} which gives {6, 4, 4, 10, 18} after performing modulus with 26 and can be mapped to {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}Examples: " }, { "code": null, "e": 762, "s": 680, "text": "Input: str = “this50hi4huji70” Output: geeksInput: str = “a1s2d3f3” Output: bcdd " }, { "code": null, "e": 1429, "s": 762, "text": "Approach: The idea is to traverse each character one by one in a string, then check if it is a numeric character or not. If it is then concatenate it into a string. Finally, modulo that number string with 26. While doing modulo operation, we can’t simply do x % 26 as the number can be too large and will result in an integer overflow. To handle this, we will process all digits one by one and use the property that (A * B) mod C = ((A mod C) * (B mod C)) mod CThen, finally decode back each integer to character by 0, 1, 2, 3, ...25 to ‘a’, ‘b’, ‘c’, ...’z’, concatenate all characters and print the final result.Below is the implementation of the above approach: " }, { "code": null, "e": 1433, "s": 1429, "text": "C++" }, { "code": null, "e": 1438, "s": 1433, "text": "Java" }, { "code": null, "e": 1446, "s": 1438, "text": "Python3" }, { "code": null, "e": 1449, "s": 1446, "text": "C#" }, { "code": null, "e": 1460, "s": 1449, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MOD = 26; // Function that returns (num % 26)int modulo_by_26(string num){ // Initialize result int res = 0; // One by one process all digits of 'num' for (int i = 0; i < num.length(); i++) res = (res * 10 + (int)num[i] - '0') % MOD; return res;} // Function to return the decrypted stringstring decrypt_message(string s){ // To store the final decrypted answer string decrypted_str = \"\"; string num_found_so_far = \"\"; // One by one check for each character // if it is a numeric character for (int i = 0; i < s.length(); ++i) { if (s[i] >= '0' && s[i] <= '9') { num_found_so_far += s[i]; } else if (num_found_so_far.length() > 0) { // Modulo the number found in the string by 26 decrypted_str += 'a' + modulo_by_26(num_found_so_far); num_found_so_far = \"\"; } } if (num_found_so_far.length() > 0) { decrypted_str += 'a' + modulo_by_26(num_found_so_far); } return decrypted_str;} // Driver codeint main(){ string s = \"32ytAAcV4ui30hf10hj18\"; // Print the decrypted string cout << decrypt_message(s); return 0;}", "e": 2768, "s": 1460, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static int MOD = 26; // Function that returns (num % 26)static int modulo_by_26(String num){ // Initialize result int res = 0; // One by one process all digits of 'num' for(int i = 0; i < num.length(); i++) { res = ((res * 10 + (int)num.charAt(i) - '0') % MOD); } return res;} // Function to return the decrypted Stringstatic String decrypt_message(String s){ // To store the final decrypted answer String decrypted_str = \"\"; String num_found_so_far = \"\"; // One by one check for each character // if it is a numeric character for(int i = 0; i < s.length(); ++i) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { num_found_so_far += s.charAt(i); } else if (num_found_so_far.length() > 0) { // Modulo the number found in the String by 26 decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); num_found_so_far = \"\"; } } if (num_found_so_far.length() > 0) { decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver codepublic static void main(String[] args){ String s = \"32ytAAcV4ui30hf10hj18\"; // Print the decrypted string System.out.print(decrypt_message(s));}} // This code is contributed by amal kumar choubey", "e": 4245, "s": 2768, "text": null }, { "code": "# Python3 implementation of# the approachMOD = 26 # Function that returns# (num % 26)def modulo_by_26(num): # Initialize result res = 0 # One by one process all # digits of 'num' for i in range(len(num)): res = ((res * 10 + ord(num[i]) - ord('0')) % MOD) return res # Function to return the# decrypted stringdef decrypt_message(s): # To store the final # decrypted answer decrypted_str = \"\" num_found_so_far = \"\" # One by one check for # each character if it # is a numeric character for i in range(len(s)): if (s[i] >= '0' and s[i] <= '9'): num_found_so_far += s[i] elif (len(num_found_so_far) > 0): # Modulo the number found # in the string by 26 decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far))) num_found_so_far = \"\" if (len(num_found_so_far) > 0): decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far))) return decrypted_str # Driver codeif __name__ == \"__main__\": s = \"32ytAAcV4ui30hf10hj18\" # Print the decrypted string print(decrypt_message(s)) # This code is contributed by Chitranayal", "e": 5495, "s": 4245, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG{ static int MOD = 26; // Function that returns (num % 26)static int modulo_by_26(String num){ // Initialize result int res = 0; // One by one process all digits of 'num' for(int i = 0; i < num.Length; i++) { res = ((res * 10 + (int)num[i] - '0') % MOD); } return res;} // Function to return the decrypted Stringstatic String decrypt_message(String s){ // To store the readonly decrypted answer String decrypted_str = \"\"; String num_found_so_far = \"\"; // One by one check for each character // if it is a numeric character for(int i = 0; i < s.Length; ++i) { if (s[i] >= '0' && s[i] <= '9') { num_found_so_far += s[i]; } else if (num_found_so_far.Length > 0) { // Modulo the number found // in the String by 26 decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); num_found_so_far = \"\"; } } if (num_found_so_far.Length > 0) { decrypted_str += (char)('a' + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver codepublic static void Main(String[] args){ String s = \"32ytAAcV4ui30hf10hj18\"; // Print the decrypted string Console.Write(decrypt_message(s));}} // This code is contributed by amal kumar choubey", "e": 6959, "s": 5495, "text": null }, { "code": "<script> // JavaScript implementation of the approach let MOD = 26; // Function that returns (num % 26)function modulo_by_26(num){ // Initialize result let res = 0; // One by one process all digits of 'num' for(let i = 0; i < num.length; i++) { res = ((res * 10 + num[i].charCodeAt(0) - '0'.charCodeAt(0)) % MOD); } return res;} // Function to return the decrypted Stringfunction decrypt_message(s){ // To store the final decrypted answer let decrypted_str = \"\"; let num_found_so_far = \"\"; // One by one check for each character // if it is a numeric character for(let i = 0; i < s.length; ++i) { if (s[i].charCodeAt(0) >= '0'.charCodeAt(0) && s[i].charCodeAt(0) <= '9'.charCodeAt(0)) { num_found_so_far += s[i]; } else if (num_found_so_far.length > 0) { // Modulo the number found in the String by 26 decrypted_str += String.fromCharCode('a'.charCodeAt(0) + modulo_by_26(num_found_so_far)); num_found_so_far = \"\"; } } if (num_found_so_far.length > 0) { decrypted_str += String.fromCharCode('a'.charCodeAt(0) + modulo_by_26(num_found_so_far)); } return decrypted_str;} // Driver code let s = \"32ytAAcV4ui30hf10hj18\"; // Print the decrypted stringdocument.write(decrypt_message(s)); // This code is contributed by rag2127 </script>", "e": 8430, "s": 6959, "text": null }, { "code": null, "e": 8436, "s": 8430, "text": "geeks" }, { "code": null, "e": 8481, "s": 8438, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 8500, "s": 8481, "text": "Amal Kumar Choubey" }, { "code": null, "e": 8506, "s": 8500, "text": "ukasp" }, { "code": null, "e": 8514, "s": 8506, "text": "rag2127" }, { "code": null, "e": 8530, "s": 8514, "text": "pankajsharmagfg" }, { "code": null, "e": 8548, "s": 8530, "text": "encoding-decoding" }, { "code": null, "e": 8567, "s": 8548, "text": "Modular Arithmetic" }, { "code": null, "e": 8578, "s": 8567, "text": "Algorithms" }, { "code": null, "e": 8591, "s": 8578, "text": "Mathematical" }, { "code": null, "e": 8599, "s": 8591, "text": "Strings" }, { "code": null, "e": 8607, "s": 8599, "text": "Strings" }, { "code": null, "e": 8620, "s": 8607, "text": "Mathematical" }, { "code": null, "e": 8639, "s": 8620, "text": "Modular Arithmetic" }, { "code": null, "e": 8650, "s": 8639, "text": "Algorithms" } ]
Interning of String in Java
06 Nov, 2019 String Interning is a method of storing only one copy of each distinct String Value, which must be immutable.By applying String.intern() on a couple of strings will ensure that all strings having the same contents share the same memory. For example, if a name ‘Amy’ appears 100 times, by interning you ensure only one ‘Amy’ is actually allocated memory. This can be very useful to reduce the memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don’t have too many duplicate values intern() method : In Java, when we perform any operation using intern() method, it returns a canonical representation for the string object. A pool is managed by String class. When the intern() method is executed then it checks whether the String equals to this String Object is in the pool or not. If it is available, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. It is advised to use equals(), not ==, to compare two strings. This is because == operator compares memory locations, while equals() method compares the content stored in two objects. // Java program to illustrate // intern() method class GFG { public static void main(String[] args) { // S1 refers to Object in the Heap Area String s1 = new String("GFG"); // Line-1 // S2 refers to Object in SCP Area String s2 = s1.intern(); // Line-2 // Comparing memory locations // s1 is in Heap // s2 is in SCP System.out.println(s1 == s2); // Comparing only values System.out.println(s1.equals(s2)); // S3 refers to Object in the SCP Area String s3 = "GFG"; // Line-3 System.out.println(s2 == s3); } } Output: false true true Explanation : Whenever we create a String Object, two objects will be created i.e. One in the Heap Area and One in the String constant pool and the String object reference always points to heap area object. When line-1 execute, it will create two objects and pointing to the heap area created object. Now when line-2 executes, it will refer to the object which is in the SCP. Again when line-3 executes, it refers to the same object which is in the SCP area because the content is already available in the SCP area. No need to create a new one object. If the corresponding String constant pool(SCP) object is not available then intern() method itself will create the corresponding SCP object. // Java program to illustrate // intern() method class GFG { public static void main(String[] args) { // S1 refers to Object in the Heap Area String s1 = new String("GFG"); // Line-1 // S2 now refers to Object in SCP Area String s2 = s1.concat("GFG"); // Line-2 // S3 refers to Object in SCP Area String s3 = s2.intern(); // Line-3 System.out.println(s2 == s3); // S4 refers to Object in the SCP Area String s4 = "GFGGFG"; // Line-4 System.out.println(s3 == s4); } } Output: true true Explanation : We use intern() method to get the reference of corresponding SCP Object. In this case, when Line-2 executes s2 will have the value “GFGGFG” in it only creates one object. In Line-3, we try to intern s3 which is again with s2 in SCP area. s4 is also in SCP so all give output as true when compared. bhagat_dineshbe2006 Java-Functions Java-lang package Java-String-Programs Java-Strings Java Technical Scripter Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Nov, 2019" }, { "code": null, "e": 407, "s": 53, "text": "String Interning is a method of storing only one copy of each distinct String Value, which must be immutable.By applying String.intern() on a couple of strings will ensure that all strings having the same contents share the same memory. For example, if a name ‘Amy’ appears 100 times, by interning you ensure only one ‘Amy’ is actually allocated memory." }, { "code": null, "e": 679, "s": 407, "text": "This can be very useful to reduce the memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don’t have too many duplicate values" }, { "code": null, "e": 855, "s": 679, "text": "intern() method : In Java, when we perform any operation using intern() method, it returns a canonical representation for the string object. A pool is managed by String class." }, { "code": null, "e": 978, "s": 855, "text": "When the intern() method is executed then it checks whether the String equals to this String Object is in the pool or not." }, { "code": null, "e": 1143, "s": 978, "text": "If it is available, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned." }, { "code": null, "e": 1257, "s": 1143, "text": "It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true." }, { "code": null, "e": 1441, "s": 1257, "text": "It is advised to use equals(), not ==, to compare two strings. This is because == operator compares memory locations, while equals() method compares the content stored in two objects." }, { "code": "// Java program to illustrate // intern() method class GFG { public static void main(String[] args) { // S1 refers to Object in the Heap Area String s1 = new String(\"GFG\"); // Line-1 // S2 refers to Object in SCP Area String s2 = s1.intern(); // Line-2 // Comparing memory locations // s1 is in Heap // s2 is in SCP System.out.println(s1 == s2); // Comparing only values System.out.println(s1.equals(s2)); // S3 refers to Object in the SCP Area String s3 = \"GFG\"; // Line-3 System.out.println(s2 == s3); } } ", "e": 2093, "s": 1441, "text": null }, { "code": null, "e": 2101, "s": 2093, "text": "Output:" }, { "code": null, "e": 2118, "s": 2101, "text": "false\ntrue\ntrue\n" }, { "code": null, "e": 2670, "s": 2118, "text": "Explanation : Whenever we create a String Object, two objects will be created i.e. One in the Heap Area and One in the String constant pool and the String object reference always points to heap area object. When line-1 execute, it will create two objects and pointing to the heap area created object. Now when line-2 executes, it will refer to the object which is in the SCP. Again when line-3 executes, it refers to the same object which is in the SCP area because the content is already available in the SCP area. No need to create a new one object." }, { "code": null, "e": 2811, "s": 2670, "text": "If the corresponding String constant pool(SCP) object is not available then intern() method itself will create the corresponding SCP object." }, { "code": "// Java program to illustrate // intern() method class GFG { public static void main(String[] args) { // S1 refers to Object in the Heap Area String s1 = new String(\"GFG\"); // Line-1 // S2 now refers to Object in SCP Area String s2 = s1.concat(\"GFG\"); // Line-2 // S3 refers to Object in SCP Area String s3 = s2.intern(); // Line-3 System.out.println(s2 == s3); // S4 refers to Object in the SCP Area String s4 = \"GFGGFG\"; // Line-4 System.out.println(s3 == s4); } } ", "e": 3380, "s": 2811, "text": null }, { "code": null, "e": 3388, "s": 3380, "text": "Output:" }, { "code": null, "e": 3399, "s": 3388, "text": "true\ntrue\n" }, { "code": null, "e": 3711, "s": 3399, "text": "Explanation : We use intern() method to get the reference of corresponding SCP Object. In this case, when Line-2 executes s2 will have the value “GFGGFG” in it only creates one object. In Line-3, we try to intern s3 which is again with s2 in SCP area. s4 is also in SCP so all give output as true when compared." }, { "code": null, "e": 3731, "s": 3711, "text": "bhagat_dineshbe2006" }, { "code": null, "e": 3746, "s": 3731, "text": "Java-Functions" }, { "code": null, "e": 3764, "s": 3746, "text": "Java-lang package" }, { "code": null, "e": 3785, "s": 3764, "text": "Java-String-Programs" }, { "code": null, "e": 3798, "s": 3785, "text": "Java-Strings" }, { "code": null, "e": 3803, "s": 3798, "text": "Java" }, { "code": null, "e": 3822, "s": 3803, "text": "Technical Scripter" }, { "code": null, "e": 3835, "s": 3822, "text": "Java-Strings" }, { "code": null, "e": 3840, "s": 3835, "text": "Java" } ]
Subtraction of two numbers using 2’s Complement
13 Jun, 2022 Given two numbers a and b. The task is to subtract b from a by using 2’s Complement method.Note: Negative numbers represented as 2’s Complement of Positive Numbers.For example, -5 can be represented in binary form as 2’s Complement of 5. Look at the image below: Examples: Input : a = 2, b = 3 Output : -1 Input : a = 9, b = 7 Output : 2 To subtract b from a. Write the expression (a-b) as: (a - b) = a + (-b) Now (-b) can be written as (2’s complement of b). So the above expression can be now written as: (a - b) = a + (2's complement of b) So, the problem now reduces to “Add a to the 2’s complement of b“. The below image illustrates the above method of subtraction for the first example where a = 2 and b = 3. Below is the implementation of the above method: C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; // function to subtract two values// using 2's complement methodint Subtract(int a, int b){ int c; // ~b is the 1's Complement of b // adding 1 to it make it 2's Complement c = a + (~b + 1); return c;} // Driver codeint main(){ int a = 2, b = 3; cout << Subtract(a, b)<<endl; a = 9; b = 7; cout << Subtract(a, b); return 0;} class GFG{ // function to subtract two values// using 2's complement methodstatic int Subtract(int a, int b){ int c; // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement c = a + (~b + 1); return c;} // Driver codepublic static void main(String[] args){ int a = 2, b = 3; System.out.println(Subtract(a, b)); a = 9; b = 7; System.out.println(Subtract(a, b));}} // This code is contributed// by ChitraNayal # python3 program of subtraction of# two numbers using 2's complement . # function to subtract two values# using 2's complement methoddef Subtract(a,b): # ~b is the 1's Complement of b # adding 1 to it make it 2's Complement c = a + (~b + 1) return c # Driver codeif __name__ == "__main__" : # multiple assignments a,b = 2,3 print(Subtract(a,b)) a,b = 9,7 print(Subtract(a,b)) // C# program of subtraction of// two numbers using 2's complementusing System; class GFG{// function to subtract two values// using 2's complement methodstatic int Subtract(int a, int b){ int c; // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement c = a + (~b + 1); return c;} // Driver codestatic void Main(){ int a = 2, b = 3; Console.WriteLine(Subtract(a, b)); a = 9; b = 7; Console.WriteLine(Subtract(a, b));}} // This code is contributed// by mits <?php// function to subtract two values// using 2's complement methodfunction Subtract($a, $b){ // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement $c = $a + (~$b + 1); return $c;} // Driver code$a = 2;$b = 3; echo Subtract($a, $b) . "\n"; $a = 9;$b = 7;echo Subtract($a, $b) . "\n"; // This code is contributed// by ChitraNayal?> <script> // Function to subtract two values// using 2's complement methodfunction Subtract(a, b){ var c; // ~b is the 1's Complement of b // adding 1 to it make it 2's Complement c = a + (~b + 1); return c;} // Driver codevar a = 2, b = 3;document.write( Subtract(a, b) + "<br>"); a = 9; b = 7;document.write( Subtract(a, b)); // This code is contributed by itsok </script> -1 2 Time complexity – O(nlog2(n))Auxiliary Space – O(1) Method 2: Basic Approach or Brute Force Approach Subtraction of two Binary Numbers, subtract two binary numbers using 2’s Complement method. Step-1: Find the 2’s complement of the subtrahend. Step-2: Add the first number and 2’s complement of the subtrahend. Step-3: If the carry is produced, discard the carry. If there is no carry then take the 2’s complement of the result. Below is the implementation of the above approach. C++ Java Python3 C# Javascript //C++ code for above approach#include<iostream>#include<bits/stdc++.h>using namespace std; // Program to subtractvoid Subtract(int n, int a[], int b[]){ // 1's Complement for(int i = 0; i < n; i++) { //Replace 1 by 0 if(b[i] == 1) { b[i] = 0; } //Replace 0 by 1 else { b[i] = 1; } } //Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if(b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if(a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if(a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } cout << endl; // If carry is generated // discard the carry if(t==1) { // print the result for(int i = 0; i < n; i++) { // Print the result cout<<a[i]; } } // if carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if(a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if(a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent cout << "-"; // -ve result // Print the resultant array for(int i = 0; i < n; i++) { cout << a[i]; } } } // Driver Codeint main(){ int n; n = 5; int a[] = {1, 0, 1, 0, 1}, b[] = {1, 1, 0, 1, 0}; Subtract(n,a,b); return 0;} // Java code for above approachimport java.io.*; class GFG{ // Program to subtractstatic void Subtract(int n, int a[], int b[]){ // 1's Complement for(int i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } System.out.println(); // If carry is generated // discard the carry if (t == 1) { // Print the result for(int i = 0; i < n; i++) { // Print the result System.out.print(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent System.out.print("-"); // -ve result // Print the resultant array for(int i = 0; i < n; i++) { System.out.print(a[i]); } } } // Driver Codepublic static void main (String[] args){ int n; n = 5; int a[] = {1, 0, 1, 0, 1}; int b[] = {1, 1, 0, 1, 0}; Subtract(n, a, b);}} // This code is contributed by avanitrachhadiya2155 # Python implementation of above approach # Program to subtractdef Subtract(n, a, b): # 1's Complement for i in range(n): # Replace 1 by 0 if (b[i] == 1): b[i] = 0 # Replace 0 by 1 else: b[i] = 1 # Add 1 at end to get 2's Complement for i in range(n - 1, -1, -1): if (b[i] == 0): b[i] = 1 break else: b[i] = 0 # Represents carry t = 0 for i in range(n - 1, -1, -1): # Add a, b and carry a[i] = a[i] + b[i] + t # If a[i] is 2 if (a[i] == 2): a[i] = 0 t = 1 # If a[i] is 3 elif (a[i] == 3): a[i] = 1 t = 1 else: t = 0 print() # If carry is generated # discard the carry if (t == 1): # Print the result for i in range(n): # Print the result print(a[i],end="") # If carry is not generated else: # Calculate 2's Complement # of the obtained result for i in range(n): if (a[i] == 1): a[i] = 0 else: a[i] = 1 for i in range(n - 1, -1, -1): if (a[i] == 0): a[i] = 1 break else: a[i] = 0 # Add -ve sign to represent print("-",end="") # -ve result # Print the resultant array for i in range(n): print(a[i],end="") # Driver Coden = 5a=[1, 0, 1, 0, 1]b=[1, 1, 0, 1, 0]Subtract(n, a, b) # This code is contributed by shinjanpatra // C# code for above approachusing System; class GFG{ // Program to subtractstatic void Subtract(int n, int[] a, int[] b){ // 1's Complement for(int i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } Console.WriteLine(); // If carry is generated // discard the carry if (t == 1) { // Print the result for(int i = 0; i < n; i++) { // Print the result Console.Write(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent Console.Write("-"); // -ve result // Print the resultant array for(int i = 0; i < n; i++) { Console.Write(a[i]); } } } // Driver Codestatic public void Main(){ int n; n = 5; int[] a = {1, 0, 1, 0, 1}; int[] b = {1, 1, 0, 1, 0}; Subtract(n, a, b);}} // This code is contributed by rag2127 <script>// Javascript code for above approach // Program to subtract function Subtract(n,a,b) { // 1's Complement for(let i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(let i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry let t = 0; for(let i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } document.write("<br>"); // If carry is generated // discard the carry if (t == 1) { // Print the result for(let i = 0; i < n; i++) { // Print the result document.write(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(let i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(let i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent document.write("-"); // -ve result // Print the resultant array for(let i = 0; i < n; i++) { document.write(a[i]); } } } // Driver Code let n = 5; let a=[1, 0, 1, 0, 1]; let b=[1, 1, 0, 1, 0]; Subtract(n, a, b); // This code is contributed by patel2127</script> -00101 Time complexity : O(N) Auxiliary Space : O(1) ankthon ukasp Mithun Kumar manavgoswami001 avanitrachhadiya2155 rag2127 itsok patel2127 sweetyty as5853535 sooda367 shinjanpatra devendrasalunke Algorithms-Bit Algorithms Bit Algorithms complement school-programming C++ Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 316, "s": 52, "text": "Given two numbers a and b. The task is to subtract b from a by using 2’s Complement method.Note: Negative numbers represented as 2’s Complement of Positive Numbers.For example, -5 can be represented in binary form as 2’s Complement of 5. Look at the image below: " }, { "code": null, "e": 327, "s": 316, "text": "Examples: " }, { "code": null, "e": 394, "s": 327, "text": "Input : a = 2, b = 3\nOutput : -1\n\nInput : a = 9, b = 7\nOutput : 2 " }, { "code": null, "e": 449, "s": 394, "text": "To subtract b from a. Write the expression (a-b) as: " }, { "code": null, "e": 468, "s": 449, "text": "(a - b) = a + (-b)" }, { "code": null, "e": 567, "s": 468, "text": "Now (-b) can be written as (2’s complement of b). So the above expression can be now written as: " }, { "code": null, "e": 603, "s": 567, "text": "(a - b) = a + (2's complement of b)" }, { "code": null, "e": 776, "s": 603, "text": "So, the problem now reduces to “Add a to the 2’s complement of b“. The below image illustrates the above method of subtraction for the first example where a = 2 and b = 3. " }, { "code": null, "e": 826, "s": 776, "text": "Below is the implementation of the above method: " }, { "code": null, "e": 830, "s": 826, "text": "C++" }, { "code": null, "e": 835, "s": 830, "text": "Java" }, { "code": null, "e": 843, "s": 835, "text": "Python3" }, { "code": null, "e": 846, "s": 843, "text": "C#" }, { "code": null, "e": 850, "s": 846, "text": "PHP" }, { "code": null, "e": 861, "s": 850, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // function to subtract two values// using 2's complement methodint Subtract(int a, int b){ int c; // ~b is the 1's Complement of b // adding 1 to it make it 2's Complement c = a + (~b + 1); return c;} // Driver codeint main(){ int a = 2, b = 3; cout << Subtract(a, b)<<endl; a = 9; b = 7; cout << Subtract(a, b); return 0;}", "e": 1266, "s": 861, "text": null }, { "code": "class GFG{ // function to subtract two values// using 2's complement methodstatic int Subtract(int a, int b){ int c; // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement c = a + (~b + 1); return c;} // Driver codepublic static void main(String[] args){ int a = 2, b = 3; System.out.println(Subtract(a, b)); a = 9; b = 7; System.out.println(Subtract(a, b));}} // This code is contributed// by ChitraNayal", "e": 1736, "s": 1266, "text": null }, { "code": "# python3 program of subtraction of# two numbers using 2's complement . # function to subtract two values# using 2's complement methoddef Subtract(a,b): # ~b is the 1's Complement of b # adding 1 to it make it 2's Complement c = a + (~b + 1) return c # Driver codeif __name__ == \"__main__\" : # multiple assignments a,b = 2,3 print(Subtract(a,b)) a,b = 9,7 print(Subtract(a,b))", "e": 2147, "s": 1736, "text": null }, { "code": "// C# program of subtraction of// two numbers using 2's complementusing System; class GFG{// function to subtract two values// using 2's complement methodstatic int Subtract(int a, int b){ int c; // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement c = a + (~b + 1); return c;} // Driver codestatic void Main(){ int a = 2, b = 3; Console.WriteLine(Subtract(a, b)); a = 9; b = 7; Console.WriteLine(Subtract(a, b));}} // This code is contributed// by mits", "e": 2667, "s": 2147, "text": null }, { "code": "<?php// function to subtract two values// using 2's complement methodfunction Subtract($a, $b){ // ~b is the 1's Complement // of b adding 1 to it make // it 2's Complement $c = $a + (~$b + 1); return $c;} // Driver code$a = 2;$b = 3; echo Subtract($a, $b) . \"\\n\"; $a = 9;$b = 7;echo Subtract($a, $b) . \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 3040, "s": 2667, "text": null }, { "code": "<script> // Function to subtract two values// using 2's complement methodfunction Subtract(a, b){ var c; // ~b is the 1's Complement of b // adding 1 to it make it 2's Complement c = a + (~b + 1); return c;} // Driver codevar a = 2, b = 3;document.write( Subtract(a, b) + \"<br>\"); a = 9; b = 7;document.write( Subtract(a, b)); // This code is contributed by itsok </script>", "e": 3431, "s": 3040, "text": null }, { "code": null, "e": 3436, "s": 3431, "text": "-1\n2" }, { "code": null, "e": 3488, "s": 3436, "text": "Time complexity – O(nlog2(n))Auxiliary Space – O(1)" }, { "code": null, "e": 3537, "s": 3488, "text": "Method 2: Basic Approach or Brute Force Approach" }, { "code": null, "e": 3630, "s": 3537, "text": "Subtraction of two Binary Numbers, subtract two binary numbers using 2’s Complement method. " }, { "code": null, "e": 3682, "s": 3630, "text": "Step-1: Find the 2’s complement of the subtrahend. " }, { "code": null, "e": 3750, "s": 3682, "text": "Step-2: Add the first number and 2’s complement of the subtrahend. " }, { "code": null, "e": 3869, "s": 3750, "text": "Step-3: If the carry is produced, discard the carry. If there is no carry then take the 2’s complement of the result. " }, { "code": null, "e": 3920, "s": 3869, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 3924, "s": 3920, "text": "C++" }, { "code": null, "e": 3929, "s": 3924, "text": "Java" }, { "code": null, "e": 3937, "s": 3929, "text": "Python3" }, { "code": null, "e": 3940, "s": 3937, "text": "C#" }, { "code": null, "e": 3951, "s": 3940, "text": "Javascript" }, { "code": "//C++ code for above approach#include<iostream>#include<bits/stdc++.h>using namespace std; // Program to subtractvoid Subtract(int n, int a[], int b[]){ // 1's Complement for(int i = 0; i < n; i++) { //Replace 1 by 0 if(b[i] == 1) { b[i] = 0; } //Replace 0 by 1 else { b[i] = 1; } } //Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if(b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if(a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if(a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } cout << endl; // If carry is generated // discard the carry if(t==1) { // print the result for(int i = 0; i < n; i++) { // Print the result cout<<a[i]; } } // if carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if(a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if(a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent cout << \"-\"; // -ve result // Print the resultant array for(int i = 0; i < n; i++) { cout << a[i]; } } } // Driver Codeint main(){ int n; n = 5; int a[] = {1, 0, 1, 0, 1}, b[] = {1, 1, 0, 1, 0}; Subtract(n,a,b); return 0;}", "e": 6180, "s": 3951, "text": null }, { "code": "// Java code for above approachimport java.io.*; class GFG{ // Program to subtractstatic void Subtract(int n, int a[], int b[]){ // 1's Complement for(int i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } System.out.println(); // If carry is generated // discard the carry if (t == 1) { // Print the result for(int i = 0; i < n; i++) { // Print the result System.out.print(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent System.out.print(\"-\"); // -ve result // Print the resultant array for(int i = 0; i < n; i++) { System.out.print(a[i]); } } } // Driver Codepublic static void main (String[] args){ int n; n = 5; int a[] = {1, 0, 1, 0, 1}; int b[] = {1, 1, 0, 1, 0}; Subtract(n, a, b);}} // This code is contributed by avanitrachhadiya2155", "e": 8526, "s": 6180, "text": null }, { "code": "# Python implementation of above approach # Program to subtractdef Subtract(n, a, b): # 1's Complement for i in range(n): # Replace 1 by 0 if (b[i] == 1): b[i] = 0 # Replace 0 by 1 else: b[i] = 1 # Add 1 at end to get 2's Complement for i in range(n - 1, -1, -1): if (b[i] == 0): b[i] = 1 break else: b[i] = 0 # Represents carry t = 0 for i in range(n - 1, -1, -1): # Add a, b and carry a[i] = a[i] + b[i] + t # If a[i] is 2 if (a[i] == 2): a[i] = 0 t = 1 # If a[i] is 3 elif (a[i] == 3): a[i] = 1 t = 1 else: t = 0 print() # If carry is generated # discard the carry if (t == 1): # Print the result for i in range(n): # Print the result print(a[i],end=\"\") # If carry is not generated else: # Calculate 2's Complement # of the obtained result for i in range(n): if (a[i] == 1): a[i] = 0 else: a[i] = 1 for i in range(n - 1, -1, -1): if (a[i] == 0): a[i] = 1 break else: a[i] = 0 # Add -ve sign to represent print(\"-\",end=\"\") # -ve result # Print the resultant array for i in range(n): print(a[i],end=\"\") # Driver Coden = 5a=[1, 0, 1, 0, 1]b=[1, 1, 0, 1, 0]Subtract(n, a, b) # This code is contributed by shinjanpatra", "e": 10285, "s": 8526, "text": null }, { "code": "// C# code for above approachusing System; class GFG{ // Program to subtractstatic void Subtract(int n, int[] a, int[] b){ // 1's Complement for(int i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(int i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry int t = 0; for(int i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } Console.WriteLine(); // If carry is generated // discard the carry if (t == 1) { // Print the result for(int i = 0; i < n; i++) { // Print the result Console.Write(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(int i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(int i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent Console.Write(\"-\"); // -ve result // Print the resultant array for(int i = 0; i < n; i++) { Console.Write(a[i]); } } } // Driver Codestatic public void Main(){ int n; n = 5; int[] a = {1, 0, 1, 0, 1}; int[] b = {1, 1, 0, 1, 0}; Subtract(n, a, b);}} // This code is contributed by rag2127", "e": 12605, "s": 10285, "text": null }, { "code": "<script>// Javascript code for above approach // Program to subtract function Subtract(n,a,b) { // 1's Complement for(let i = 0; i < n; i++) { // Replace 1 by 0 if (b[i] == 1) { b[i] = 0; } // Replace 0 by 1 else { b[i] = 1; } } // Add 1 at end to get 2's Complement for(let i = n - 1; i >= 0; i--) { if (b[i] == 0) { b[i] = 1; break; } else { b[i] = 0; } } // Represents carry let t = 0; for(let i = n - 1; i >= 0; i--) { // Add a, b and carry a[i] = a[i] + b[i] + t; // If a[i] is 2 if (a[i] == 2) { a[i] = 0; t = 1; } // If a[i] is 3 else if (a[i] == 3) { a[i] = 1; t = 1; } else t = 0; } document.write(\"<br>\"); // If carry is generated // discard the carry if (t == 1) { // Print the result for(let i = 0; i < n; i++) { // Print the result document.write(a[i]); } } // If carry is not generated else { // Calculate 2's Complement // of the obtained result for(let i = 0; i < n; i++) { if (a[i] == 1) a[i] = 0; else a[i] = 1; } for(let i = n - 1; i >= 0; i--) { if (a[i] == 0) { a[i] = 1; break; } else a[i] = 0; } // Add -ve sign to represent document.write(\"-\"); // -ve result // Print the resultant array for(let i = 0; i < n; i++) { document.write(a[i]); } } } // Driver Code let n = 5; let a=[1, 0, 1, 0, 1]; let b=[1, 1, 0, 1, 0]; Subtract(n, a, b); // This code is contributed by patel2127</script>", "e": 14864, "s": 12605, "text": null }, { "code": null, "e": 14871, "s": 14864, "text": "-00101" }, { "code": null, "e": 14894, "s": 14871, "text": "Time complexity : O(N)" }, { "code": null, "e": 14917, "s": 14894, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 14927, "s": 14919, "text": "ankthon" }, { "code": null, "e": 14933, "s": 14927, "text": "ukasp" }, { "code": null, "e": 14946, "s": 14933, "text": "Mithun Kumar" }, { "code": null, "e": 14962, "s": 14946, "text": "manavgoswami001" }, { "code": null, "e": 14983, "s": 14962, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14991, "s": 14983, "text": "rag2127" }, { "code": null, "e": 14997, "s": 14991, "text": "itsok" }, { "code": null, "e": 15007, "s": 14997, "text": "patel2127" }, { "code": null, "e": 15016, "s": 15007, "text": "sweetyty" }, { "code": null, "e": 15026, "s": 15016, "text": "as5853535" }, { "code": null, "e": 15035, "s": 15026, "text": "sooda367" }, { "code": null, "e": 15048, "s": 15035, "text": "shinjanpatra" }, { "code": null, "e": 15064, "s": 15048, "text": "devendrasalunke" }, { "code": null, "e": 15090, "s": 15064, "text": "Algorithms-Bit Algorithms" }, { "code": null, "e": 15105, "s": 15090, "text": "Bit Algorithms" }, { "code": null, "e": 15116, "s": 15105, "text": "complement" }, { "code": null, "e": 15135, "s": 15116, "text": "school-programming" }, { "code": null, "e": 15148, "s": 15135, "text": "C++ Programs" }, { "code": null, "e": 15167, "s": 15148, "text": "School Programming" } ]
Statistical Database Security - GeeksforGeeks
24 Aug, 2020 Prerequisite – Control Methods of Database Security Certain databases may contain confidential or secret data of individuals of country like (Aadhar numbers, PAN card numbers) and this database should not be accessed by attackers. So, therefore it should be protected from user access. The database which contains details of huge population is called Statistical databases and it is used mainly to produce statistics on various populations. But Users are allowed to retrieve certain statistical information of population like averages of population of particular state/district etc and their sum, count, maximum, minimum, and standard deviations, etc. It is the responsibility of ethical hackers to monitor Statistical Database security statistical users are not permitted to access individual data, such as income of specific person, phone number, Debit card numbers of specified person in database because Statistical database security techniques prohibit retrieval of individual data. It is also responsibility of DBMS to provide confidentiality of data about individuals. Statistical Queries :The queries which allow only aggregate functions such as COUNT, SUM, MIN, MAX, AVERAGE, and STANDARD DEVIATION are called statistical queries. Statistical queries are mainly used for knowing population statistics and in companies/industries to maintain their employees’ database etc. Example –Consider the following examples of statistical queries where EMP_SALARY is confidential database that contains the income of each employee of company. Query-1: SELECT COUNT(*) FROM EMP_SALARY WHERE Emp-department = '3'; Query-2: SELECT AVG(income) FROM EMP_SALARY WHERE Emp-id = '2'; Here, the “Where” condition can be manipulated by attacker and there is chance to access income of individual employees or confidential data of employee if he knows id/name of particular employee. The possibility of accessing individual information from statistical queries is reduced by using the following measures – Partitioning of Database – This means the records of database must be not be stored as bulk in single record. It must be divided into groups of some minimum size according to confidentiality of records.The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private.If no statistical queries are permitted whenever number of tuples in population specified by selection condition falls below some threshold.Prohibit sequences of queries that refer repeatedly to same population of tuples. Partitioning of Database – This means the records of database must be not be stored as bulk in single record. It must be divided into groups of some minimum size according to confidentiality of records.The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private. The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private. If no statistical queries are permitted whenever number of tuples in population specified by selection condition falls below some threshold. Prohibit sequences of queries that refer repeatedly to same population of tuples. DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS KDD Process in Data Mining Relational Model in DBMS What is Temporary Table in SQL? Types of Functional dependencies in DBMS Difference between File System and DBMS First Normal Form (1NF) Nested Queries in SQL What is Cursor in SQL ?
[ { "code": null, "e": 24250, "s": 24222, "text": "\n24 Aug, 2020" }, { "code": null, "e": 24302, "s": 24250, "text": "Prerequisite – Control Methods of Database Security" }, { "code": null, "e": 24536, "s": 24302, "text": "Certain databases may contain confidential or secret data of individuals of country like (Aadhar numbers, PAN card numbers) and this database should not be accessed by attackers. So, therefore it should be protected from user access." }, { "code": null, "e": 24902, "s": 24536, "text": "The database which contains details of huge population is called Statistical databases and it is used mainly to produce statistics on various populations. But Users are allowed to retrieve certain statistical information of population like averages of population of particular state/district etc and their sum, count, maximum, minimum, and standard deviations, etc." }, { "code": null, "e": 25326, "s": 24902, "text": "It is the responsibility of ethical hackers to monitor Statistical Database security statistical users are not permitted to access individual data, such as income of specific person, phone number, Debit card numbers of specified person in database because Statistical database security techniques prohibit retrieval of individual data. It is also responsibility of DBMS to provide confidentiality of data about individuals." }, { "code": null, "e": 25631, "s": 25326, "text": "Statistical Queries :The queries which allow only aggregate functions such as COUNT, SUM, MIN, MAX, AVERAGE, and STANDARD DEVIATION are called statistical queries. Statistical queries are mainly used for knowing population statistics and in companies/industries to maintain their employees’ database etc." }, { "code": null, "e": 25791, "s": 25631, "text": "Example –Consider the following examples of statistical queries where EMP_SALARY is confidential database that contains the income of each employee of company." }, { "code": null, "e": 25800, "s": 25791, "text": "Query-1:" }, { "code": null, "e": 25861, "s": 25800, "text": "SELECT COUNT(*) \nFROM EMP_SALARY\nWHERE Emp-department = '3';" }, { "code": null, "e": 25870, "s": 25861, "text": "Query-2:" }, { "code": null, "e": 25928, "s": 25870, "text": "SELECT AVG(income) \nFROM EMP_SALARY \nWHERE Emp-id = '2'; " }, { "code": null, "e": 26125, "s": 25928, "text": "Here, the “Where” condition can be manipulated by attacker and there is chance to access income of individual employees or confidential data of employee if he knows id/name of particular employee." }, { "code": null, "e": 26247, "s": 26125, "text": "The possibility of accessing individual information from statistical queries is reduced by using the following measures –" }, { "code": null, "e": 26912, "s": 26247, "text": "Partitioning of Database – This means the records of database must be not be stored as bulk in single record. It must be divided into groups of some minimum size according to confidentiality of records.The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private.If no statistical queries are permitted whenever number of tuples in population specified by selection condition falls below some threshold.Prohibit sequences of queries that refer repeatedly to same population of tuples." }, { "code": null, "e": 27356, "s": 26912, "text": "Partitioning of Database – This means the records of database must be not be stored as bulk in single record. It must be divided into groups of some minimum size according to confidentiality of records.The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private." }, { "code": null, "e": 27598, "s": 27356, "text": "The advantage of Partitioning of database is queries can refer to any complete group or set of groups, but queries cannot access the subsets of records within a group. So, attacker can access at most one or two groups which are less private." }, { "code": null, "e": 27739, "s": 27598, "text": "If no statistical queries are permitted whenever number of tuples in population specified by selection condition falls below some threshold." }, { "code": null, "e": 27821, "s": 27739, "text": "Prohibit sequences of queries that refer repeatedly to same population of tuples." }, { "code": null, "e": 27826, "s": 27821, "text": "DBMS" }, { "code": null, "e": 27831, "s": 27826, "text": "DBMS" }, { "code": null, "e": 27929, "s": 27831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27938, "s": 27929, "text": "Comments" }, { "code": null, "e": 27951, "s": 27938, "text": "Old Comments" }, { "code": null, "e": 27976, "s": 27951, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 28019, "s": 27976, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 28046, "s": 28019, "text": "KDD Process in Data Mining" }, { "code": null, "e": 28071, "s": 28046, "text": "Relational Model in DBMS" }, { "code": null, "e": 28103, "s": 28071, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28144, "s": 28103, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 28184, "s": 28144, "text": "Difference between File System and DBMS" }, { "code": null, "e": 28208, "s": 28184, "text": "First Normal Form (1NF)" }, { "code": null, "e": 28230, "s": 28208, "text": "Nested Queries in SQL" } ]
Kth Smallest Element in a Sorted Matrix in Python
Suppose we have a n x n matrix where each of the rows and columns are sorted in increasing order, we have to find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth unique element. So if the input is like [[1,5,9],[10,11,13],[12,13,15]], if k = 8, then the output will be 13. To solve this, we will follow these steps − define one method called checkVal() and the arguments are matrix and value i := 0, j := length of matrix[0] – 1, counter := 0 while i < length of matrix and j >= 0if matrix[i, j] > value, then decrease j by 1, otherwise counter := counter + j + 1, increase i by 1 if matrix[i, j] > value, then decrease j by 1, otherwise counter := counter + j + 1, increase i by 1 return counter the main method will be like − n := row of matrix, high := bottom right corner element, low := top left corner element while low <= high, domid = low + (high – low)/2count := checkVal(matrix, mid)if count < k, then low := mid + 1, otherwise high := mid – 1 mid = low + (high – low)/2 count := checkVal(matrix, mid) if count < k, then low := mid + 1, otherwise high := mid – 1 return low Let us see the following implementation to get better understanding − Live Demo class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ n = len(matrix) high = matrix[n-1][n-1] low = matrix[0][0] while low<=high: mid = low + (high - low) /2 count = self.check_value(matrix,mid) if count< k: low = mid+1 else : high = mid-1 return int(low) def check_value(self, matrix, value): i = 0 j = len(matrix[0])-1 counter = 0 while(i<len(matrix) and j >=0): if matrix[i][j] > value: j-=1 else: counter+=j+1 i+=1 return counter matrix = [[1,5,9],[10,11,13],[12,13,15]] ob = Solution() print(ob.kthSmallest(matrix, 8)) matrix =[[1,5,9],[10,11,13],[12,13,15]] k = 8 13
[ { "code": null, "e": 1401, "s": 1062, "text": "Suppose we have a n x n matrix where each of the rows and columns are sorted in increasing order, we have to find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth unique element. So if the input is like [[1,5,9],[10,11,13],[12,13,15]], if k = 8, then the output will be 13." }, { "code": null, "e": 1445, "s": 1401, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1520, "s": 1445, "text": "define one method called checkVal() and the arguments are matrix and value" }, { "code": null, "e": 1571, "s": 1520, "text": "i := 0, j := length of matrix[0] – 1, counter := 0" }, { "code": null, "e": 1709, "s": 1571, "text": "while i < length of matrix and j >= 0if matrix[i, j] > value, then decrease j by 1, otherwise counter := counter + j + 1, increase i by 1" }, { "code": null, "e": 1810, "s": 1709, "text": "if matrix[i, j] > value, then decrease j by 1, otherwise counter := counter + j + 1, increase i by 1" }, { "code": null, "e": 1825, "s": 1810, "text": "return counter" }, { "code": null, "e": 1856, "s": 1825, "text": "the main method will be like −" }, { "code": null, "e": 1944, "s": 1856, "text": "n := row of matrix, high := bottom right corner element, low := top left corner element" }, { "code": null, "e": 2082, "s": 1944, "text": "while low <= high, domid = low + (high – low)/2count := checkVal(matrix, mid)if count < k, then low := mid + 1, otherwise high := mid – 1" }, { "code": null, "e": 2109, "s": 2082, "text": "mid = low + (high – low)/2" }, { "code": null, "e": 2140, "s": 2109, "text": "count := checkVal(matrix, mid)" }, { "code": null, "e": 2201, "s": 2140, "text": "if count < k, then low := mid + 1, otherwise high := mid – 1" }, { "code": null, "e": 2212, "s": 2201, "text": "return low" }, { "code": null, "e": 2282, "s": 2212, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2293, "s": 2282, "text": " Live Demo" }, { "code": null, "e": 3094, "s": 2293, "text": "class Solution(object):\n def kthSmallest(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n n = len(matrix)\n high = matrix[n-1][n-1]\n low = matrix[0][0]\n while low<=high:\n mid = low + (high - low) /2\n count = self.check_value(matrix,mid)\n if count< k:\n low = mid+1\n else :\n high = mid-1\n return int(low)\n def check_value(self, matrix, value):\n i = 0\n j = len(matrix[0])-1\n counter = 0\n while(i<len(matrix) and j >=0):\n if matrix[i][j] > value:\n j-=1\n else:\n counter+=j+1\n i+=1\n return counter\nmatrix = [[1,5,9],[10,11,13],[12,13,15]]\nob = Solution()\nprint(ob.kthSmallest(matrix, 8))" }, { "code": null, "e": 3140, "s": 3094, "text": "matrix =[[1,5,9],[10,11,13],[12,13,15]]\nk = 8" }, { "code": null, "e": 3143, "s": 3140, "text": "13" } ]
Maximum sum combination from two arrays - GeeksforGeeks
04 Sep, 2021 Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both the arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of above-chosen numbers. Examples: Input : arr1[] = {9, 3, 5, 7, 3}, arr2[] = {5, 8, 1, 4, 5} Output : 29 Select first, third and fifth element from the first array. Select the second and fourth element from the second array. Input : arr1[] = {1, 2, 9}, arr2[] = {10, 1, 1} Output : 19 Select last element from the first array and first element from the second array. Approach : This problem is based on dynamic programming. Let dp(i, 1) be the maximum sum of the newly selected elements if the last element was taken from the position(i-1, 1). dp(i, 2) is the same but the last element taken has the position (i-1, 2) dp(i, 3) the same but we didn’t take any element from position i-1 Recursion relations are : dp(i, 1)=max(dp (i – 1, 2) + arr(i, 1), dp(i – 1, 3) + arr(i, 1), arr(i, 1) ); dp(i, 2)=max(dp(i – 1, 1) + arr(i, 2 ), dp(i – 1, 3) + arr (i, 2), arr(i, 2)); dp(i, 3)=max(dp(i- 1, 1), dp( i-1, 2) ). We don’t actually need dp( i, 3), if we update dp(i, 1) as max(dp(i, 1), dp(i-1, 1)) and dp(i, 2) as max(dp(i, 2), dp(i-1, 2)).Thus, dp(i, j) is the maximum total sum of the elements that are selected if the last element was taken from the position (i-1, 1) or less. The same with dp(i, 2). Therefore the answer to the above problem is max(dp(n, 1), dp(n, 2)). Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to maximum sum// combination from two arrays#include <bits/stdc++.h>using namespace std; // Function to maximum sum// combination from two arraysint Max_Sum(int arr1[], int arr2[], int n){ // To store dp value int dp[n][2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i==0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return max(dp[n-1][0], dp[n-1][1]);} // Driver codeint main(){ int arr1[] = {9, 3, 5, 7, 3}; int arr2[] = {5, 8, 1, 4, 5}; int n = sizeof(arr1) / sizeof(arr1[0]); // Function call cout << Max_Sum(arr1, arr2, n); return 0;} // Java program to maximum sum// combination from two arraysclass GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int arr1[], int arr2[], int n){ // To store dp value int [][]dp = new int[n][2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i == 0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return Math.max(dp[n - 1][0], dp[n - 1][1]);} // Driver codepublic static void main(String[] args){ int arr1[] = {9, 3, 5, 7, 3}; int arr2[] = {5, 8, 1, 4, 5}; int n = arr1.length; // Function call System.out.println(Max_Sum(arr1, arr2, n));}} // This code is contributed// by PrinciRaj1992 # Python3 program to maximum sum# combination from two arrays # Function to maximum sum# combination from two arraysdef Max_Sum(arr1, arr2, n): # To store dp value dp = [[0 for i in range(2)] for j in range(n)] # For loop to calculate the value of dp for i in range(n): if(i == 0): dp[i][0] = arr1[i] dp[i][1] = arr2[i] continue else: dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i]) dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i]) # Return the required answer return max(dp[n - 1][0], dp[n - 1][1]) # Driver codeif __name__ == '__main__': arr1 = [9, 3, 5, 7, 3] arr2 = [5, 8, 1, 4, 5] n = len(arr1) # Function call print(Max_Sum(arr1, arr2, n)) # This code is contributed by# Surendra_Gangwar // C# program to maximum sum// combination from two arraysusing System; class GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int []arr1, int []arr2, int n){ // To store dp value int [,]dp = new int[n, 2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i == 0) { dp[i, 0] = arr1[i]; dp[i, 1] = arr2[i]; continue; } dp[i, 0] = Math.Max(dp[i - 1, 0], dp[i - 1, 1] + arr1[i]); dp[i, 1] = Math.Max(dp[i - 1, 1], dp[i - 1, 0] + arr2[i]); } // Return the required answer return Math.Max(dp[n - 1, 0], dp[n - 1, 1]);} // Driver codepublic static void Main(){ int []arr1 = {9, 3, 5, 7, 3}; int []arr2 = {5, 8, 1, 4, 5}; int n = arr1.Length; // Function call Console.WriteLine(Max_Sum(arr1, arr2, n));}} // This code is contributed// by anuj_67.. <script> // Javascript program to maximum sum combination from two arrays // Function to maximum sum // combination from two arrays function Max_Sum(arr1, arr2, n) { // To store dp value let dp = new Array(n); for (let i = 0; i < n; i++) { dp[i] = new Array(2); for (let j = 0; j < 2; j++) { dp[i][j] = 0; } } // For loop to calculate the value of dp for (let i = 0; i < n; i++) { if(i == 0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return Math.max(dp[n - 1][0], dp[n - 1][1]); } let arr1 = [9, 3, 5, 7, 3]; let arr2 = [5, 8, 1, 4, 5]; let n = arr1.length; // Function call document.write(Max_Sum(arr1, arr2, n)); </script> 29 Time Complexity: O(N) princiraj1992 vt_m SURENDRA_GANGWAR divyesh072019 khushboogoyal499 sumitgumber28 Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Linear Search Queue | Set 1 (Introduction and Array Implementation) Python | Using 2D arrays/lists the right way 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24939, "s": 24911, "text": "\n04 Sep, 2021" }, { "code": null, "e": 25217, "s": 24939, "text": "Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both the arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of above-chosen numbers. " }, { "code": null, "e": 25228, "s": 25217, "text": "Examples: " }, { "code": null, "e": 25420, "s": 25228, "text": "Input : arr1[] = {9, 3, 5, 7, 3}, arr2[] = {5, 8, 1, 4, 5} Output : 29 Select first, third and fifth element from the first array. Select the second and fourth element from the second array. " }, { "code": null, "e": 25563, "s": 25420, "text": "Input : arr1[] = {1, 2, 9}, arr2[] = {10, 1, 1} Output : 19 Select last element from the first array and first element from the second array. " }, { "code": null, "e": 25621, "s": 25563, "text": "Approach : This problem is based on dynamic programming. " }, { "code": null, "e": 25741, "s": 25621, "text": "Let dp(i, 1) be the maximum sum of the newly selected elements if the last element was taken from the position(i-1, 1)." }, { "code": null, "e": 25815, "s": 25741, "text": "dp(i, 2) is the same but the last element taken has the position (i-1, 2)" }, { "code": null, "e": 25882, "s": 25815, "text": "dp(i, 3) the same but we didn’t take any element from position i-1" }, { "code": null, "e": 25909, "s": 25882, "text": "Recursion relations are : " }, { "code": null, "e": 26108, "s": 25909, "text": "dp(i, 1)=max(dp (i – 1, 2) + arr(i, 1), dp(i – 1, 3) + arr(i, 1), arr(i, 1) ); dp(i, 2)=max(dp(i – 1, 1) + arr(i, 2 ), dp(i – 1, 3) + arr (i, 2), arr(i, 2)); dp(i, 3)=max(dp(i- 1, 1), dp( i-1, 2) )." }, { "code": null, "e": 26469, "s": 26108, "text": "We don’t actually need dp( i, 3), if we update dp(i, 1) as max(dp(i, 1), dp(i-1, 1)) and dp(i, 2) as max(dp(i, 2), dp(i-1, 2)).Thus, dp(i, j) is the maximum total sum of the elements that are selected if the last element was taken from the position (i-1, 1) or less. The same with dp(i, 2). Therefore the answer to the above problem is max(dp(n, 1), dp(n, 2))." }, { "code": null, "e": 26523, "s": 26469, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 26527, "s": 26523, "text": "C++" }, { "code": null, "e": 26532, "s": 26527, "text": "Java" }, { "code": null, "e": 26540, "s": 26532, "text": "Python3" }, { "code": null, "e": 26543, "s": 26540, "text": "C#" }, { "code": null, "e": 26554, "s": 26543, "text": "Javascript" }, { "code": "// CPP program to maximum sum// combination from two arrays#include <bits/stdc++.h>using namespace std; // Function to maximum sum// combination from two arraysint Max_Sum(int arr1[], int arr2[], int n){ // To store dp value int dp[n][2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i==0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return max(dp[n-1][0], dp[n-1][1]);} // Driver codeint main(){ int arr1[] = {9, 3, 5, 7, 3}; int arr2[] = {5, 8, 1, 4, 5}; int n = sizeof(arr1) / sizeof(arr1[0]); // Function call cout << Max_Sum(arr1, arr2, n); return 0;}", "e": 27425, "s": 26554, "text": null }, { "code": "// Java program to maximum sum// combination from two arraysclass GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int arr1[], int arr2[], int n){ // To store dp value int [][]dp = new int[n][2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i == 0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return Math.max(dp[n - 1][0], dp[n - 1][1]);} // Driver codepublic static void main(String[] args){ int arr1[] = {9, 3, 5, 7, 3}; int arr2[] = {5, 8, 1, 4, 5}; int n = arr1.length; // Function call System.out.println(Max_Sum(arr1, arr2, n));}} // This code is contributed// by PrinciRaj1992", "e": 28454, "s": 27425, "text": null }, { "code": "# Python3 program to maximum sum# combination from two arrays # Function to maximum sum# combination from two arraysdef Max_Sum(arr1, arr2, n): # To store dp value dp = [[0 for i in range(2)] for j in range(n)] # For loop to calculate the value of dp for i in range(n): if(i == 0): dp[i][0] = arr1[i] dp[i][1] = arr2[i] continue else: dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i]) dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i]) # Return the required answer return max(dp[n - 1][0], dp[n - 1][1]) # Driver codeif __name__ == '__main__': arr1 = [9, 3, 5, 7, 3] arr2 = [5, 8, 1, 4, 5] n = len(arr1) # Function call print(Max_Sum(arr1, arr2, n)) # This code is contributed by# Surendra_Gangwar", "e": 29358, "s": 28454, "text": null }, { "code": "// C# program to maximum sum// combination from two arraysusing System; class GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int []arr1, int []arr2, int n){ // To store dp value int [,]dp = new int[n, 2]; // For loop to calculate the value of dp for (int i = 0; i < n; i++) { if(i == 0) { dp[i, 0] = arr1[i]; dp[i, 1] = arr2[i]; continue; } dp[i, 0] = Math.Max(dp[i - 1, 0], dp[i - 1, 1] + arr1[i]); dp[i, 1] = Math.Max(dp[i - 1, 1], dp[i - 1, 0] + arr2[i]); } // Return the required answer return Math.Max(dp[n - 1, 0], dp[n - 1, 1]);} // Driver codepublic static void Main(){ int []arr1 = {9, 3, 5, 7, 3}; int []arr2 = {5, 8, 1, 4, 5}; int n = arr1.Length; // Function call Console.WriteLine(Max_Sum(arr1, arr2, n));}} // This code is contributed// by anuj_67..", "e": 30378, "s": 29358, "text": null }, { "code": "<script> // Javascript program to maximum sum combination from two arrays // Function to maximum sum // combination from two arrays function Max_Sum(arr1, arr2, n) { // To store dp value let dp = new Array(n); for (let i = 0; i < n; i++) { dp[i] = new Array(2); for (let j = 0; j < 2; j++) { dp[i][j] = 0; } } // For loop to calculate the value of dp for (let i = 0; i < n; i++) { if(i == 0) { dp[i][0] = arr1[i]; dp[i][1] = arr2[i]; continue; } dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr1[i]); dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + arr2[i]); } // Return the required answer return Math.max(dp[n - 1][0], dp[n - 1][1]); } let arr1 = [9, 3, 5, 7, 3]; let arr2 = [5, 8, 1, 4, 5]; let n = arr1.length; // Function call document.write(Max_Sum(arr1, arr2, n)); </script>", "e": 31547, "s": 30378, "text": null }, { "code": null, "e": 31550, "s": 31547, "text": "29" }, { "code": null, "e": 31575, "s": 31552, "text": "Time Complexity: O(N) " }, { "code": null, "e": 31589, "s": 31575, "text": "princiraj1992" }, { "code": null, "e": 31594, "s": 31589, "text": "vt_m" }, { "code": null, "e": 31611, "s": 31594, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 31625, "s": 31611, "text": "divyesh072019" }, { "code": null, "e": 31642, "s": 31625, "text": "khushboogoyal499" }, { "code": null, "e": 31656, "s": 31642, "text": "sumitgumber28" }, { "code": null, "e": 31663, "s": 31656, "text": "Arrays" }, { "code": null, "e": 31683, "s": 31663, "text": "Dynamic Programming" }, { "code": null, "e": 31690, "s": 31683, "text": "Arrays" }, { "code": null, "e": 31710, "s": 31690, "text": "Dynamic Programming" }, { "code": null, "e": 31808, "s": 31710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31817, "s": 31808, "text": "Comments" }, { "code": null, "e": 31830, "s": 31817, "text": "Old Comments" }, { "code": null, "e": 31878, "s": 31830, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31910, "s": 31878, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31924, "s": 31910, "text": "Linear Search" }, { "code": null, "e": 31978, "s": 31924, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 32023, "s": 31978, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 32052, "s": 32023, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 32082, "s": 32052, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32116, "s": 32082, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32147, "s": 32116, "text": "Bellman–Ford Algorithm | DP-23" } ]
A Basic Introduction to TensorFlow Lite | by Renu Khandelwal | Towards Data Science
In this article, we will understand the features required to deploy a deep learning model at the Edge, what is TensorFlow Lite, and how the different components of TensorFlow Lite can be used to make an inference at the Edge. You are trying to deploy your deep learning model in an area where they don’t have a good network connection but still need the deep learning model to give an excellent performance. TensorFlow Lite can be used in such a scenario Light-weight: Edge devices have limited resources in terms of storage and computation capacity. Deep learning models are resource-intensive, so the models we deploy on edge devices should be light-weight with smaller binary sizes.Low Latency: Deep Learning models at the Edge should make faster inferences irrespective of network connectivity. As the inferences are made on the Edge device, a round trip from the device to the server will be eliminated, making inferences faster.Secure: The Model is deployed on the Edge device, the inferences are made on the device, no data leaves the device or is shared across the network, so there is no concern for data privacy.Optimal power consumption: Network needs a lot of power, and Edge devices may not be connected to the network, and hence, the power consumption need is low.Pre-trained: Models can be trained on-prem or cloud for different deep learning tasks like image classification, object detection, speech recognition, etc. and can be easily deployed to make inferences at the Edge. Light-weight: Edge devices have limited resources in terms of storage and computation capacity. Deep learning models are resource-intensive, so the models we deploy on edge devices should be light-weight with smaller binary sizes. Low Latency: Deep Learning models at the Edge should make faster inferences irrespective of network connectivity. As the inferences are made on the Edge device, a round trip from the device to the server will be eliminated, making inferences faster. Secure: The Model is deployed on the Edge device, the inferences are made on the device, no data leaves the device or is shared across the network, so there is no concern for data privacy. Optimal power consumption: Network needs a lot of power, and Edge devices may not be connected to the network, and hence, the power consumption need is low. Pre-trained: Models can be trained on-prem or cloud for different deep learning tasks like image classification, object detection, speech recognition, etc. and can be easily deployed to make inferences at the Edge. Tensorflow Lite offers all the features required for making inferences at the Edge. But what is TensorFlow Lite? TensorFlow Lite is an open-source, product ready, cross-platform deep learning framework that converts a pre-trained model in TensorFlow to a special format that can be optimized for speed or storage. The special format model can be deployed on edge devices like mobiles using Android or iOS or Linux based embedded devices like Raspberry Pi or Microcontrollers to make the inference at the Edge. How does Tensorflow Lite(TF Lite) work? let’s say you want to perform the Image Classification task. The first thing is to decide on the Model for the task. Your options are Create a custom model Use a pre-trained model like InceptionNet, MobileNet, NASNetLarge, etc. Apply Transfer Learning on a pre-trained model After the model is trained, you will convert the Model to the Tensorflow Lite version. TF lite model is a special format model efficient in terms of accuracy and also is a light-weight version that will occupy less space, these features make TF Lite models the right fit to work on Mobile and Embedded Devices. TensorFlow Lite conversion Process During the conversion process from a Tensorflow model to a Tensorflow Lite model, the size of the file is reduced. We have a choice to either go for further reducing the file size with a trade-off with the execution speed of the Model. Tensorflow Lite Converter converts a Tensorflow model to Tensorflow Lite flat buffer file(.tflite). Tensorflow Lite flat buffer file is deployed to the client, which in our cases can be a mobile device running on iOS or Android or an embedded device. How can we convert a TensorFlow model to the TFlite Model? After you have trained the Model, you will now need to save the Model. The saved Model serializes the architecture of the Model, the weights and the biases, and training configuration in a single file. The saved model can be easily used for sharing or deploying the models. The Converter supports the Model saved using tf.keras.Model: Create and compile a model using Keras and then convert the Model using TFLite. #Save the keras model after compilingmodel.save('model_keras.h5')model_keras= tf.keras.models.load_model('model_keras.h5')# Converting a tf.Keras model to a TensorFlow Lite model.converter = tf.lite.TFLiteConverter.from_keras_model(model_keras)tflite_model = converter.convert() SavedModel: A SavedModel contains a complete TensorFlow program, including weights and computation. #save your model in the SavedModel formatexport_dir = 'saved_model/1'tf.saved_model.save(model, export_dir)# Converting a SavedModel to a TensorFlow Lite model.converter = lite.TFLiteConverter.from_saved_model(export_dir)tflite_model = converter.convert() export_dir follows a convention where the last path component is the version number of the Model. SavedModel is a meta graph saved on the export_dir, which is converted to the TFLite Model using lite.TFLiteConverter. Concrete Functions: TF 2.0 has eager execution on by default, and that impacts the performance and deployability. To overcome the performance issue, we can use tf.function to create graphs. The graphs contain the model structure with all the computational operations, variables, and weights of the Model. Export the Model as a concrete function and then convert the concrete function to TF Lite model # export model as concrete functionfunc = tf.function(model).get_concrete_function( tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))#Returns a serialized graphdef representation of the concrte functionfunc.graph.as_graph_def()# converting the concrete function to Tf Lite converter = tf.lite.TFLiteConverter.from_concrete_functions([func])tflite_model = converter.convert() Why optimize model? Models at Edge needs to be light-weight Take less space on the Edge devices. Faster download time on networks with lower bandwidth Occupy less Memory for the Model to make inferences faster Models at Edge should also have low latency to run inferences. Light-weight and low latency model can be achieved by reducing the amount of computation required to predict. Optimization reduces the size of the model or improves the latency. There is a trade-off between the size of the model and the accuracy of the model. How is optimization achieved in TensorFlow Lite? Tensorflow Lite achieves optimization using Quantization Weight Pruning Quantization When we save the TensorFlow Model, it stores as graphs containing the computational operation, activation functions, weights, and biases. The activation function, weights, and biases are 32-bit floating points. Quantization reduces the precision of the numbers used to represent different parameters of the TensorFlow model and this makes models light-weight. Quantization can be applied to weight and activations. Weights with 32-bit floating points can be converted to 16-bit floating points or 8-bit floating points or integer and will reduce the size of the Model. Both weights and activations can be quantized by converting to an integer, and this will give low latency, smaller size, and reduced power consumption. Weight Pruning Just as we prune plants to remove non-productive parts of the plant to make it more fruit-bearing and healthier, the same way we can prune weights of the Model. Weight pruning trims parameters within a model that has very less impact on the performance of the model. Weight pruning achieves model sparsity, and sparse models are compressed more efficiently. Pruned models will have the same size, and run-time latency but better compression for faster download time at the Edge. TF lite model can be deployed on mobile devices like Android and iOS, on edge devices like Raspberry and Microcontrollers. To make an inference from the Edge devices, you will need to Initialize the interpreter and load the interpreter with the Model Allocate the tensor and get the input and output tensors Preprocess the image by reading it into a tensor Make the inference on the input tensor using the interpreter by invoking it. Obtain the result of the image by mapping the result from the inference # Load TFLite model and allocate tensors.interpreter = tf.lite.Interpreter(model_content=tflite_model)interpreter.allocate_tensors()#get input and output tensorsinput_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# Read the image and decode to a tensorimg = cv2.imread(image_path)img = cv2.resize(img,(WIDTH,HEIGHT))#Preprocess the image to required size and castinput_shape = input_details[0]['shape']input_tensor= np.array(np.expand_dims(img,0), dtype=np.float32)#set the tensor to point to the input data to be inferredinput_index = interpreter.get_input_details()[0]["index"]interpreter.set_tensor(input_index, input_tensor)#Run the inferenceinterpreter.invoke()output_details = interpreter.get_output_details()[0] Is there any other way to improve latency? Tensorflow lite uses delegates to improve the performance of the TF Lite model at the Edge. TF lite delegate is a way to hand over parts of graph execution to another hardware accelerator like GPU or DSP(Digital Signal Processor). TF lite uses several hardware accelerators for speed, accuracy, and optimizing power consumption, which important features for running inferences at the Edge. Conclusion: TF lite models are light-weight models that can be deployed for a low-latency inference at Edge devices like mobiles, Raspberry Pi, and Micro-controllers. TF lite delegate can be used further to improve the speed, accuracy and power consumption when used with hardware accelerators
[ { "code": null, "e": 398, "s": 172, "text": "In this article, we will understand the features required to deploy a deep learning model at the Edge, what is TensorFlow Lite, and how the different components of TensorFlow Lite can be used to make an inference at the Edge." }, { "code": null, "e": 580, "s": 398, "text": "You are trying to deploy your deep learning model in an area where they don’t have a good network connection but still need the deep learning model to give an excellent performance." }, { "code": null, "e": 627, "s": 580, "text": "TensorFlow Lite can be used in such a scenario" }, { "code": null, "e": 1665, "s": 627, "text": "Light-weight: Edge devices have limited resources in terms of storage and computation capacity. Deep learning models are resource-intensive, so the models we deploy on edge devices should be light-weight with smaller binary sizes.Low Latency: Deep Learning models at the Edge should make faster inferences irrespective of network connectivity. As the inferences are made on the Edge device, a round trip from the device to the server will be eliminated, making inferences faster.Secure: The Model is deployed on the Edge device, the inferences are made on the device, no data leaves the device or is shared across the network, so there is no concern for data privacy.Optimal power consumption: Network needs a lot of power, and Edge devices may not be connected to the network, and hence, the power consumption need is low.Pre-trained: Models can be trained on-prem or cloud for different deep learning tasks like image classification, object detection, speech recognition, etc. and can be easily deployed to make inferences at the Edge." }, { "code": null, "e": 1896, "s": 1665, "text": "Light-weight: Edge devices have limited resources in terms of storage and computation capacity. Deep learning models are resource-intensive, so the models we deploy on edge devices should be light-weight with smaller binary sizes." }, { "code": null, "e": 2146, "s": 1896, "text": "Low Latency: Deep Learning models at the Edge should make faster inferences irrespective of network connectivity. As the inferences are made on the Edge device, a round trip from the device to the server will be eliminated, making inferences faster." }, { "code": null, "e": 2335, "s": 2146, "text": "Secure: The Model is deployed on the Edge device, the inferences are made on the device, no data leaves the device or is shared across the network, so there is no concern for data privacy." }, { "code": null, "e": 2492, "s": 2335, "text": "Optimal power consumption: Network needs a lot of power, and Edge devices may not be connected to the network, and hence, the power consumption need is low." }, { "code": null, "e": 2707, "s": 2492, "text": "Pre-trained: Models can be trained on-prem or cloud for different deep learning tasks like image classification, object detection, speech recognition, etc. and can be easily deployed to make inferences at the Edge." }, { "code": null, "e": 2791, "s": 2707, "text": "Tensorflow Lite offers all the features required for making inferences at the Edge." }, { "code": null, "e": 2820, "s": 2791, "text": "But what is TensorFlow Lite?" }, { "code": null, "e": 3021, "s": 2820, "text": "TensorFlow Lite is an open-source, product ready, cross-platform deep learning framework that converts a pre-trained model in TensorFlow to a special format that can be optimized for speed or storage." }, { "code": null, "e": 3217, "s": 3021, "text": "The special format model can be deployed on edge devices like mobiles using Android or iOS or Linux based embedded devices like Raspberry Pi or Microcontrollers to make the inference at the Edge." }, { "code": null, "e": 3257, "s": 3217, "text": "How does Tensorflow Lite(TF Lite) work?" }, { "code": null, "e": 3391, "s": 3257, "text": "let’s say you want to perform the Image Classification task. The first thing is to decide on the Model for the task. Your options are" }, { "code": null, "e": 3413, "s": 3391, "text": "Create a custom model" }, { "code": null, "e": 3485, "s": 3413, "text": "Use a pre-trained model like InceptionNet, MobileNet, NASNetLarge, etc." }, { "code": null, "e": 3532, "s": 3485, "text": "Apply Transfer Learning on a pre-trained model" }, { "code": null, "e": 3843, "s": 3532, "text": "After the model is trained, you will convert the Model to the Tensorflow Lite version. TF lite model is a special format model efficient in terms of accuracy and also is a light-weight version that will occupy less space, these features make TF Lite models the right fit to work on Mobile and Embedded Devices." }, { "code": null, "e": 3878, "s": 3843, "text": "TensorFlow Lite conversion Process" }, { "code": null, "e": 4114, "s": 3878, "text": "During the conversion process from a Tensorflow model to a Tensorflow Lite model, the size of the file is reduced. We have a choice to either go for further reducing the file size with a trade-off with the execution speed of the Model." }, { "code": null, "e": 4214, "s": 4114, "text": "Tensorflow Lite Converter converts a Tensorflow model to Tensorflow Lite flat buffer file(.tflite)." }, { "code": null, "e": 4365, "s": 4214, "text": "Tensorflow Lite flat buffer file is deployed to the client, which in our cases can be a mobile device running on iOS or Android or an embedded device." }, { "code": null, "e": 4424, "s": 4365, "text": "How can we convert a TensorFlow model to the TFlite Model?" }, { "code": null, "e": 4495, "s": 4424, "text": "After you have trained the Model, you will now need to save the Model." }, { "code": null, "e": 4698, "s": 4495, "text": "The saved Model serializes the architecture of the Model, the weights and the biases, and training configuration in a single file. The saved model can be easily used for sharing or deploying the models." }, { "code": null, "e": 4743, "s": 4698, "text": "The Converter supports the Model saved using" }, { "code": null, "e": 4839, "s": 4743, "text": "tf.keras.Model: Create and compile a model using Keras and then convert the Model using TFLite." }, { "code": null, "e": 5118, "s": 4839, "text": "#Save the keras model after compilingmodel.save('model_keras.h5')model_keras= tf.keras.models.load_model('model_keras.h5')# Converting a tf.Keras model to a TensorFlow Lite model.converter = tf.lite.TFLiteConverter.from_keras_model(model_keras)tflite_model = converter.convert()" }, { "code": null, "e": 5218, "s": 5118, "text": "SavedModel: A SavedModel contains a complete TensorFlow program, including weights and computation." }, { "code": null, "e": 5474, "s": 5218, "text": "#save your model in the SavedModel formatexport_dir = 'saved_model/1'tf.saved_model.save(model, export_dir)# Converting a SavedModel to a TensorFlow Lite model.converter = lite.TFLiteConverter.from_saved_model(export_dir)tflite_model = converter.convert()" }, { "code": null, "e": 5572, "s": 5474, "text": "export_dir follows a convention where the last path component is the version number of the Model." }, { "code": null, "e": 5691, "s": 5572, "text": "SavedModel is a meta graph saved on the export_dir, which is converted to the TFLite Model using lite.TFLiteConverter." }, { "code": null, "e": 5996, "s": 5691, "text": "Concrete Functions: TF 2.0 has eager execution on by default, and that impacts the performance and deployability. To overcome the performance issue, we can use tf.function to create graphs. The graphs contain the model structure with all the computational operations, variables, and weights of the Model." }, { "code": null, "e": 6092, "s": 5996, "text": "Export the Model as a concrete function and then convert the concrete function to TF Lite model" }, { "code": null, "e": 6482, "s": 6092, "text": "# export model as concrete functionfunc = tf.function(model).get_concrete_function( tf.TensorSpec(model.inputs[0].shape, model.inputs[0].dtype))#Returns a serialized graphdef representation of the concrte functionfunc.graph.as_graph_def()# converting the concrete function to Tf Lite converter = tf.lite.TFLiteConverter.from_concrete_functions([func])tflite_model = converter.convert()" }, { "code": null, "e": 6502, "s": 6482, "text": "Why optimize model?" }, { "code": null, "e": 6542, "s": 6502, "text": "Models at Edge needs to be light-weight" }, { "code": null, "e": 6579, "s": 6542, "text": "Take less space on the Edge devices." }, { "code": null, "e": 6633, "s": 6579, "text": "Faster download time on networks with lower bandwidth" }, { "code": null, "e": 6692, "s": 6633, "text": "Occupy less Memory for the Model to make inferences faster" }, { "code": null, "e": 6865, "s": 6692, "text": "Models at Edge should also have low latency to run inferences. Light-weight and low latency model can be achieved by reducing the amount of computation required to predict." }, { "code": null, "e": 7015, "s": 6865, "text": "Optimization reduces the size of the model or improves the latency. There is a trade-off between the size of the model and the accuracy of the model." }, { "code": null, "e": 7064, "s": 7015, "text": "How is optimization achieved in TensorFlow Lite?" }, { "code": null, "e": 7108, "s": 7064, "text": "Tensorflow Lite achieves optimization using" }, { "code": null, "e": 7121, "s": 7108, "text": "Quantization" }, { "code": null, "e": 7136, "s": 7121, "text": "Weight Pruning" }, { "code": null, "e": 7149, "s": 7136, "text": "Quantization" }, { "code": null, "e": 7360, "s": 7149, "text": "When we save the TensorFlow Model, it stores as graphs containing the computational operation, activation functions, weights, and biases. The activation function, weights, and biases are 32-bit floating points." }, { "code": null, "e": 7509, "s": 7360, "text": "Quantization reduces the precision of the numbers used to represent different parameters of the TensorFlow model and this makes models light-weight." }, { "code": null, "e": 7564, "s": 7509, "text": "Quantization can be applied to weight and activations." }, { "code": null, "e": 7718, "s": 7564, "text": "Weights with 32-bit floating points can be converted to 16-bit floating points or 8-bit floating points or integer and will reduce the size of the Model." }, { "code": null, "e": 7870, "s": 7718, "text": "Both weights and activations can be quantized by converting to an integer, and this will give low latency, smaller size, and reduced power consumption." }, { "code": null, "e": 7885, "s": 7870, "text": "Weight Pruning" }, { "code": null, "e": 8046, "s": 7885, "text": "Just as we prune plants to remove non-productive parts of the plant to make it more fruit-bearing and healthier, the same way we can prune weights of the Model." }, { "code": null, "e": 8152, "s": 8046, "text": "Weight pruning trims parameters within a model that has very less impact on the performance of the model." }, { "code": null, "e": 8364, "s": 8152, "text": "Weight pruning achieves model sparsity, and sparse models are compressed more efficiently. Pruned models will have the same size, and run-time latency but better compression for faster download time at the Edge." }, { "code": null, "e": 8487, "s": 8364, "text": "TF lite model can be deployed on mobile devices like Android and iOS, on edge devices like Raspberry and Microcontrollers." }, { "code": null, "e": 8548, "s": 8487, "text": "To make an inference from the Edge devices, you will need to" }, { "code": null, "e": 8615, "s": 8548, "text": "Initialize the interpreter and load the interpreter with the Model" }, { "code": null, "e": 8672, "s": 8615, "text": "Allocate the tensor and get the input and output tensors" }, { "code": null, "e": 8721, "s": 8672, "text": "Preprocess the image by reading it into a tensor" }, { "code": null, "e": 8798, "s": 8721, "text": "Make the inference on the input tensor using the interpreter by invoking it." }, { "code": null, "e": 8870, "s": 8798, "text": "Obtain the result of the image by mapping the result from the inference" }, { "code": null, "e": 9633, "s": 8870, "text": "# Load TFLite model and allocate tensors.interpreter = tf.lite.Interpreter(model_content=tflite_model)interpreter.allocate_tensors()#get input and output tensorsinput_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# Read the image and decode to a tensorimg = cv2.imread(image_path)img = cv2.resize(img,(WIDTH,HEIGHT))#Preprocess the image to required size and castinput_shape = input_details[0]['shape']input_tensor= np.array(np.expand_dims(img,0), dtype=np.float32)#set the tensor to point to the input data to be inferredinput_index = interpreter.get_input_details()[0][\"index\"]interpreter.set_tensor(input_index, input_tensor)#Run the inferenceinterpreter.invoke()output_details = interpreter.get_output_details()[0]" }, { "code": null, "e": 9676, "s": 9633, "text": "Is there any other way to improve latency?" }, { "code": null, "e": 9907, "s": 9676, "text": "Tensorflow lite uses delegates to improve the performance of the TF Lite model at the Edge. TF lite delegate is a way to hand over parts of graph execution to another hardware accelerator like GPU or DSP(Digital Signal Processor)." }, { "code": null, "e": 10066, "s": 9907, "text": "TF lite uses several hardware accelerators for speed, accuracy, and optimizing power consumption, which important features for running inferences at the Edge." } ]
Conversational AI: Design & Build a Contextual AI Assistant | by Mady Mantha | Towards Data Science
Though Conversational AI has been around since the 1960s, it’s experiencing a renewed focus in recent years. While we’re still in the early days of the design and development of intelligent conversational AI, Google quite rightly announced that we were moving from a mobile-first to an AI- first world, where we expect technology to be naturally conversational, thoughtfully contextual, and evolutionarily competent. In other words, we expect technology to learn and evolve. Most chatbots today can handle simple questions and respond with prebuilt responses based on rule-based conversation processing. For instance, if user says X, respond with Y; if user says Z, call a REST API, and so forth. However, at this juncture, we expect more from conversation. We want contextual assistants that transcend answering simple questions or sending push notifications. In this series, I’ll walk you through the design, development and deployment of a contextual AI assistant that designs curated travel experiences. First, let’s talk about the maturity levels of contextual assistants as explained by their capabilities: Level 1 Maturity: at this level, the chatbot is essentially a traditional notification assistant; it can answer a question with a pre-built response. It can send you notifications about certain events or reminders about things in which you’ve explicitly expressed interest. For instance, a level 1 travel bot can provide a link for you to book travel. Level 2 Maturity: at this level, the chatbot can answer FAQs but is also capable of handling a simple follow up. Level 3 Maturity: at this level, the contextual assistant can engage in a flexible back-and-forth with you and offer more than prebuilt answers because it knows how to respond to unexpected user utterances. The assistant also begins to understand context at this point. For instance, the travel bot will be able to walk you through a few popular destinations and make the necessary travel arrangements. Level 4 Maturity: at this level, the contextual assistant has gotten to know you better. It remembers your preferences, and can offer personalized, contextualized recommendations or “nudges” to be more proactive in its care. For instance, the assistant would proactively reach out to order you a ride after you’ve landed. Level 5 and beyond: at this level, contextual assistants are able to monitor and manage a host of other assistants in order to run certain aspects of enterprise operations. They’d be able to run promotions on certain travel experiences, target certain customer segments more effectively based on historical trends, increase conversion rates and adoption, and so forth. Natural Language Processing (NLP) is an application of Artificial Intelligence that enables computers to process and understand human language. Recent advances in machine learning, and more specifically its subset, deep learning, have made it possible for computers to better understand natural language. These deep learning models can analyze large volumes of text and provide things like text summarization, language translation, context modeling, and sentiment analysis. Natural Language Understanding (NLU) is a subset of NLP that turns natural language into structured data. NLU is able to do two things — intent classification and entity extraction. When we read a sentence, we immediately understand the meaning or intent behind that sentence. An intent is something that a user is trying to convey or accomplish. Intent classification is a two step process. First, we feed an NLU model with labeled data that provides the list of known intents and example sentences that correspond to those intents. Once trained, the model is able to classify a new sentence that it sees into one of the predefined intents. Entity extraction is the process of recognizing key pieces of information in a given text. Things like time, place and and name of a person all provide additional context and information related to an intent. Intent classification and entity extraction are the primary drivers of conversational AI. For the purposes of this article, we will use the Rasa, an open source stack that provides tools to build contextual AI assistants. There are two main components in the Rasa stack that will help us build a travel assistant — Rasa NLU and Rasa core. Rasa NLU provides intent classification and entity extraction services. Rasa core is the main framework of the stack the provides conversation or dialogue management backed by machine learning. Assuming for a second that the NLU and core components have been trained, let’s see how Rasa stack works. Let’s use this sample dialogue: The NLU component identifies that the user intends to engage in vacation based travel (intent classification) and that he or she is the only one going on this trip (entity extraction). The core component is responsible for controlling the conversation flow. Based on the input from NLU, the current state of the conversation and its trained model, the core component decides on the next best course of action which could be sending a reply back to user or taking an action. Rasa’s ML based dialogue management is context aware and doesn’t rely on hard coded rules to process conversation. Now, let’s install Rasa and start creating the initial set of training data for our travel assistant. Rasa can be setup in two ways. You can either install the Rasa stack using python/pip on your local machine or you can use docker to setup Rasa stack using preconfigured docker images. We’re going to install the Rasa stack using python and pip. If you don’t have python installed on your machine, you can use Anaconda to set it up. Note that you need python 3.6.x version to run the Rasa stack. The latest version of python (3.7.x at the time of this post) is not fully compatible. Run the following command to install Rasa core: pip install -U rasa_core Install Rasa NLU by running this command: pip install rasa_nlu[tensorflow] Now let’s skaffold our application by cloning the starter pack provided by Rasa: git clone https://github.com/RasaHQ/starter-pack-rasa-stack.git travel-bot Once cloned, run these commands to install the required packages and the spaCy english language model for entity extraction. pip install -r requirements.txt \ && python -m spacy download en At this point we have everything we need to begin developing our travel assistant. Let’s take a look at the folder structure and the files that were created during the scaffolding process. The “domain.yml” file describes the travel assistant’s domain. It specifies the list of intents, entities, slots, and response templates that the assistant understands and operates with. Let’s update the file to add an initial set of intents corresponding to our travel domain. Here’s a snippet: intents: - greet - request_vacation - affirm - inform...entities: - location - people - startdate - enddate...slots: people: type: unfeaturized location: type: unfeaturized...actions: - utter_greet - utter_ask_who - utter_ask_where - utter_confirm_booking...templates: utter_ask_who: - text: "Fun! Let's do it. Who's going?" utter_ask_where: - text: "Perfect. Where would you like to go?"... The “data/nlu_data.md” file describes each intent with a set of examples that are then fed to Rasa NLU for training. Here’s a snippet: ## intent:request_vacation- I want to go on vacation- I want to book a trip- Help me plan my vacation- Can you book a trip for me?...## intent:inform- just me- we're [2](people)- anywhere in the [amazon](location)- [Paris](location)- somewhere [warm](weather_attribute)- somewhere [tropical](weather_attribute)- going by myself... The “data/stories.md” file provides Rasa with sample conversations between users and the travel assistant that it can use to train its dialog management model. Here’s a snippet: ## vacation happy path 1* request_vacation - utter_ask_who* inform{"people": "1"} - utter_ask_where* inform{"location": "paris"} - utter_ask_duration* inform{"startdate": "2019-10-03T00:00:00", "enddate": "2019-10-13T00:00:00"} - utter_confirm_booking* affirm - goodbye... Rasa provides a lot flexibility in terms of configuring the NLU and core components. For now, we’ll use the default “nlu_config.yml” for NLU and “policies.yml” for the core model. Run the following command to train Rasa NLU: make train-nlu Run the following command to train Rasa Core: make train-core We can now run the server to test Rasa through the command line: make cmdline Rasa stack provides hooks to connect our assistant to various front end channels like Slack and Facebook. Let’s configure and deploy our travel assistant to Slack. Let’s start by creating a new app in slack Under features, go to “OAuth & Permissions”, add permission scopes like “chat:write:bot” and save your changes Go to “Bot Users”, add a bot user and save your changes Go back to “OAuth & Permissions” and install the app to your workspace Copy the “Bot User OAuth Access Token” under tokens for your workspace Back to the “travel-bot” folder on your local machine, create a new “credentials.yml” file. Paste the token into the file so it looks like this: slack: slack_token: "xoxb-XXXXXXXXXXX" We need to pass these credentials to Rasa. To make our lives easier, let’s update the “Makefile” under the “travel-bot” folder to add a new command called “start” ...start: python -m rasa_core.run \ --enable_api \ -d models/current/dialogue \ -u models/current/nlu \ -c rest --cors "*" \ --endpoints endpoints.yml \ --credentials credentials.yml \ --connector slack Caution: Based on your requirements, update ‘cors’ settings before deploying your bot to production. Let’s start the server by calling: make start Our travel assistant is now running on the local port 5005 and it’s configured to talk to slack via REST APIs. We need to make these endpoints reachable to the outside world. Let’s use ngrok to make our server available to Slack. Ngrok helps in setting up a secure tunnel to our local server for quick development and testing. Once you have ngrok installed, run the following command in a new command line terminal: ngrok http 5005 Make a note of the “https” URL provided by ngrok. Back in the Slack app management UI: Enable “Event Subscriptions”. In the request URL textbox, paste your ngrok URL and add “/webhooks/slack/webhook” to the end of that URL. Complete the event subscription by subscribing to bot events like “message.im” and save your changes Optionally, enable “Interactive Components” and pass the same request URL that you used in the previous step. Be sure to save your changes At this point we have fully configured our bot assistant to interact with Slack. To test the travel assistant, slack your newly created travel bot. In the next part of the series, we’ll deep dive into our NLU pipeline, custom components like Google’s BERT and Recurrent Embedding Dialogue Policy (REDP), and approach concepts like context, attention, and non-linear conversation.
[ { "code": null, "e": 647, "s": 172, "text": "Though Conversational AI has been around since the 1960s, it’s experiencing a renewed focus in recent years. While we’re still in the early days of the design and development of intelligent conversational AI, Google quite rightly announced that we were moving from a mobile-first to an AI- first world, where we expect technology to be naturally conversational, thoughtfully contextual, and evolutionarily competent. In other words, we expect technology to learn and evolve." }, { "code": null, "e": 1180, "s": 647, "text": "Most chatbots today can handle simple questions and respond with prebuilt responses based on rule-based conversation processing. For instance, if user says X, respond with Y; if user says Z, call a REST API, and so forth. However, at this juncture, we expect more from conversation. We want contextual assistants that transcend answering simple questions or sending push notifications. In this series, I’ll walk you through the design, development and deployment of a contextual AI assistant that designs curated travel experiences." }, { "code": null, "e": 1285, "s": 1180, "text": "First, let’s talk about the maturity levels of contextual assistants as explained by their capabilities:" }, { "code": null, "e": 1637, "s": 1285, "text": "Level 1 Maturity: at this level, the chatbot is essentially a traditional notification assistant; it can answer a question with a pre-built response. It can send you notifications about certain events or reminders about things in which you’ve explicitly expressed interest. For instance, a level 1 travel bot can provide a link for you to book travel." }, { "code": null, "e": 1750, "s": 1637, "text": "Level 2 Maturity: at this level, the chatbot can answer FAQs but is also capable of handling a simple follow up." }, { "code": null, "e": 2153, "s": 1750, "text": "Level 3 Maturity: at this level, the contextual assistant can engage in a flexible back-and-forth with you and offer more than prebuilt answers because it knows how to respond to unexpected user utterances. The assistant also begins to understand context at this point. For instance, the travel bot will be able to walk you through a few popular destinations and make the necessary travel arrangements." }, { "code": null, "e": 2475, "s": 2153, "text": "Level 4 Maturity: at this level, the contextual assistant has gotten to know you better. It remembers your preferences, and can offer personalized, contextualized recommendations or “nudges” to be more proactive in its care. For instance, the assistant would proactively reach out to order you a ride after you’ve landed." }, { "code": null, "e": 2844, "s": 2475, "text": "Level 5 and beyond: at this level, contextual assistants are able to monitor and manage a host of other assistants in order to run certain aspects of enterprise operations. They’d be able to run promotions on certain travel experiences, target certain customer segments more effectively based on historical trends, increase conversion rates and adoption, and so forth." }, { "code": null, "e": 3318, "s": 2844, "text": "Natural Language Processing (NLP) is an application of Artificial Intelligence that enables computers to process and understand human language. Recent advances in machine learning, and more specifically its subset, deep learning, have made it possible for computers to better understand natural language. These deep learning models can analyze large volumes of text and provide things like text summarization, language translation, context modeling, and sentiment analysis." }, { "code": null, "e": 3500, "s": 3318, "text": "Natural Language Understanding (NLU) is a subset of NLP that turns natural language into structured data. NLU is able to do two things — intent classification and entity extraction." }, { "code": null, "e": 4259, "s": 3500, "text": "When we read a sentence, we immediately understand the meaning or intent behind that sentence. An intent is something that a user is trying to convey or accomplish. Intent classification is a two step process. First, we feed an NLU model with labeled data that provides the list of known intents and example sentences that correspond to those intents. Once trained, the model is able to classify a new sentence that it sees into one of the predefined intents. Entity extraction is the process of recognizing key pieces of information in a given text. Things like time, place and and name of a person all provide additional context and information related to an intent. Intent classification and entity extraction are the primary drivers of conversational AI." }, { "code": null, "e": 4508, "s": 4259, "text": "For the purposes of this article, we will use the Rasa, an open source stack that provides tools to build contextual AI assistants. There are two main components in the Rasa stack that will help us build a travel assistant — Rasa NLU and Rasa core." }, { "code": null, "e": 4808, "s": 4508, "text": "Rasa NLU provides intent classification and entity extraction services. Rasa core is the main framework of the stack the provides conversation or dialogue management backed by machine learning. Assuming for a second that the NLU and core components have been trained, let’s see how Rasa stack works." }, { "code": null, "e": 4840, "s": 4808, "text": "Let’s use this sample dialogue:" }, { "code": null, "e": 5025, "s": 4840, "text": "The NLU component identifies that the user intends to engage in vacation based travel (intent classification) and that he or she is the only one going on this trip (entity extraction)." }, { "code": null, "e": 5429, "s": 5025, "text": "The core component is responsible for controlling the conversation flow. Based on the input from NLU, the current state of the conversation and its trained model, the core component decides on the next best course of action which could be sending a reply back to user or taking an action. Rasa’s ML based dialogue management is context aware and doesn’t rely on hard coded rules to process conversation." }, { "code": null, "e": 5531, "s": 5429, "text": "Now, let’s install Rasa and start creating the initial set of training data for our travel assistant." }, { "code": null, "e": 5776, "s": 5531, "text": "Rasa can be setup in two ways. You can either install the Rasa stack using python/pip on your local machine or you can use docker to setup Rasa stack using preconfigured docker images. We’re going to install the Rasa stack using python and pip." }, { "code": null, "e": 6013, "s": 5776, "text": "If you don’t have python installed on your machine, you can use Anaconda to set it up. Note that you need python 3.6.x version to run the Rasa stack. The latest version of python (3.7.x at the time of this post) is not fully compatible." }, { "code": null, "e": 6061, "s": 6013, "text": "Run the following command to install Rasa core:" }, { "code": null, "e": 6086, "s": 6061, "text": "pip install -U rasa_core" }, { "code": null, "e": 6128, "s": 6086, "text": "Install Rasa NLU by running this command:" }, { "code": null, "e": 6161, "s": 6128, "text": "pip install rasa_nlu[tensorflow]" }, { "code": null, "e": 6242, "s": 6161, "text": "Now let’s skaffold our application by cloning the starter pack provided by Rasa:" }, { "code": null, "e": 6317, "s": 6242, "text": "git clone https://github.com/RasaHQ/starter-pack-rasa-stack.git travel-bot" }, { "code": null, "e": 6442, "s": 6317, "text": "Once cloned, run these commands to install the required packages and the spaCy english language model for entity extraction." }, { "code": null, "e": 6508, "s": 6442, "text": "pip install -r requirements.txt \\ && python -m spacy download en" }, { "code": null, "e": 6697, "s": 6508, "text": "At this point we have everything we need to begin developing our travel assistant. Let’s take a look at the folder structure and the files that were created during the scaffolding process." }, { "code": null, "e": 6993, "s": 6697, "text": "The “domain.yml” file describes the travel assistant’s domain. It specifies the list of intents, entities, slots, and response templates that the assistant understands and operates with. Let’s update the file to add an initial set of intents corresponding to our travel domain. Here’s a snippet:" }, { "code": null, "e": 7413, "s": 6993, "text": "intents: - greet - request_vacation - affirm - inform...entities: - location - people - startdate - enddate...slots: people: type: unfeaturized location: type: unfeaturized...actions: - utter_greet - utter_ask_who - utter_ask_where - utter_confirm_booking...templates: utter_ask_who: - text: \"Fun! Let's do it. Who's going?\" utter_ask_where: - text: \"Perfect. Where would you like to go?\"..." }, { "code": null, "e": 7548, "s": 7413, "text": "The “data/nlu_data.md” file describes each intent with a set of examples that are then fed to Rasa NLU for training. Here’s a snippet:" }, { "code": null, "e": 7879, "s": 7548, "text": "## intent:request_vacation- I want to go on vacation- I want to book a trip- Help me plan my vacation- Can you book a trip for me?...## intent:inform- just me- we're [2](people)- anywhere in the [amazon](location)- [Paris](location)- somewhere [warm](weather_attribute)- somewhere [tropical](weather_attribute)- going by myself..." }, { "code": null, "e": 8057, "s": 7879, "text": "The “data/stories.md” file provides Rasa with sample conversations between users and the travel assistant that it can use to train its dialog management model. Here’s a snippet:" }, { "code": null, "e": 8345, "s": 8057, "text": "## vacation happy path 1* request_vacation - utter_ask_who* inform{\"people\": \"1\"} - utter_ask_where* inform{\"location\": \"paris\"} - utter_ask_duration* inform{\"startdate\": \"2019-10-03T00:00:00\", \"enddate\": \"2019-10-13T00:00:00\"} - utter_confirm_booking* affirm - goodbye..." }, { "code": null, "e": 8525, "s": 8345, "text": "Rasa provides a lot flexibility in terms of configuring the NLU and core components. For now, we’ll use the default “nlu_config.yml” for NLU and “policies.yml” for the core model." }, { "code": null, "e": 8570, "s": 8525, "text": "Run the following command to train Rasa NLU:" }, { "code": null, "e": 8585, "s": 8570, "text": "make train-nlu" }, { "code": null, "e": 8631, "s": 8585, "text": "Run the following command to train Rasa Core:" }, { "code": null, "e": 8647, "s": 8631, "text": "make train-core" }, { "code": null, "e": 8712, "s": 8647, "text": "We can now run the server to test Rasa through the command line:" }, { "code": null, "e": 8725, "s": 8712, "text": "make cmdline" }, { "code": null, "e": 8889, "s": 8725, "text": "Rasa stack provides hooks to connect our assistant to various front end channels like Slack and Facebook. Let’s configure and deploy our travel assistant to Slack." }, { "code": null, "e": 8932, "s": 8889, "text": "Let’s start by creating a new app in slack" }, { "code": null, "e": 9043, "s": 8932, "text": "Under features, go to “OAuth & Permissions”, add permission scopes like “chat:write:bot” and save your changes" }, { "code": null, "e": 9099, "s": 9043, "text": "Go to “Bot Users”, add a bot user and save your changes" }, { "code": null, "e": 9170, "s": 9099, "text": "Go back to “OAuth & Permissions” and install the app to your workspace" }, { "code": null, "e": 9241, "s": 9170, "text": "Copy the “Bot User OAuth Access Token” under tokens for your workspace" }, { "code": null, "e": 9386, "s": 9241, "text": "Back to the “travel-bot” folder on your local machine, create a new “credentials.yml” file. Paste the token into the file so it looks like this:" }, { "code": null, "e": 9426, "s": 9386, "text": "slack: slack_token: \"xoxb-XXXXXXXXXXX\"" }, { "code": null, "e": 9589, "s": 9426, "text": "We need to pass these credentials to Rasa. To make our lives easier, let’s update the “Makefile” under the “travel-bot” folder to add a new command called “start”" }, { "code": null, "e": 9816, "s": 9589, "text": "...start: python -m rasa_core.run \\ --enable_api \\ -d models/current/dialogue \\ -u models/current/nlu \\ -c rest --cors \"*\" \\ --endpoints endpoints.yml \\ --credentials credentials.yml \\ --connector slack" }, { "code": null, "e": 9917, "s": 9816, "text": "Caution: Based on your requirements, update ‘cors’ settings before deploying your bot to production." }, { "code": null, "e": 9952, "s": 9917, "text": "Let’s start the server by calling:" }, { "code": null, "e": 9963, "s": 9952, "text": "make start" }, { "code": null, "e": 10379, "s": 9963, "text": "Our travel assistant is now running on the local port 5005 and it’s configured to talk to slack via REST APIs. We need to make these endpoints reachable to the outside world. Let’s use ngrok to make our server available to Slack. Ngrok helps in setting up a secure tunnel to our local server for quick development and testing. Once you have ngrok installed, run the following command in a new command line terminal:" }, { "code": null, "e": 10395, "s": 10379, "text": "ngrok http 5005" }, { "code": null, "e": 10482, "s": 10395, "text": "Make a note of the “https” URL provided by ngrok. Back in the Slack app management UI:" }, { "code": null, "e": 10720, "s": 10482, "text": "Enable “Event Subscriptions”. In the request URL textbox, paste your ngrok URL and add “/webhooks/slack/webhook” to the end of that URL. Complete the event subscription by subscribing to bot events like “message.im” and save your changes" }, { "code": null, "e": 10859, "s": 10720, "text": "Optionally, enable “Interactive Components” and pass the same request URL that you used in the previous step. Be sure to save your changes" }, { "code": null, "e": 11007, "s": 10859, "text": "At this point we have fully configured our bot assistant to interact with Slack. To test the travel assistant, slack your newly created travel bot." } ]
How to select only non - numeric values from varchar column in MySQL?
You need to use REGEXP for this. The syntax is as follows SELECT *FROM yourTableName WHERE yourColumnName REGEXP '[a-zA-Z]'; To understand the concept, let us create a table. The query to create a table is as follows mysql> create table SelectNonNumericValue -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserId varchar(100) -> ); Query OK, 0 rows affected (0.58 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into SelectNonNumericValue(UserId) values('123John'); Query OK, 1 row affected (0.12 sec) mysql> insert into SelectNonNumericValue(UserId) values('58475Carol98457Taylor24'); Query OK, 1 row affected (0.52 sec) mysql> insert into SelectNonNumericValue(UserId) values('199575Sam124'); Query OK, 1 row affected (0.14 sec) mysql> insert into SelectNonNumericValue(UserId) values('Mike2456'); Query OK, 1 row affected (0.14 sec) mysql> insert into SelectNonNumericValue(UserId) values('1000'); Query OK, 1 row affected (0.12 sec) mysql> insert into SelectNonNumericValue(UserId) values('1001'); Query OK, 1 row affected (0.21 sec) mysql> insert into SelectNonNumericValue(UserId) values('10293Bob'); Query OK, 1 row affected (0.13 sec) mysql> insert into SelectNonNumericValue(UserId) values('David'); Query OK, 1 row affected (0.30 sec) mysql> insert into SelectNonNumericValue(UserId) values('2456'); Query OK, 1 row affected (0.15 sec) Display all records from the table using a select statement. The query is as follows mysql> select *from SelectNonNumericValue; The following is the output +----+-------------------------+ | Id | UserId | +----+-------------------------+ | 1 | 123John | | 2 | 58475Carol98457Taylor24 | | 3 | 199575Sam124 | | 4 | Mike2456 | | 5 | 1000 | | 6 | 1001 | | 7 | 10293Bob | | 8 | David | | 9 | 2456 | +----+-------------------------+ 9 rows in set (0.00 sec) Here is the query to select non-numeric values mysql> select *from SelectNonNumericValue WHERE UserId REGEXP '[a-zA-Z]'; The following is the output that ignores the numeric values +----+-------------------------+ | Id | UserId | +----+-------------------------+ | 1 | 123John | | 2 | 58475Carol98457Taylor24 | | 3 | 199575Sam124 | | 4 | Mike2456 | | 7 | 10293Bob | | 8 | David | +----+-------------------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1120, "s": 1062, "text": "You need to use REGEXP for this. The syntax is as follows" }, { "code": null, "e": 1187, "s": 1120, "text": "SELECT *FROM yourTableName WHERE yourColumnName REGEXP '[a-zA-Z]';" }, { "code": null, "e": 1279, "s": 1187, "text": "To understand the concept, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1451, "s": 1279, "text": "mysql> create table SelectNonNumericValue\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserId varchar(100)\n -> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1530, "s": 1451, "text": "Insert some records in the table using insert command. The query is as follows" }, { "code": null, "e": 2478, "s": 1530, "text": "mysql> insert into SelectNonNumericValue(UserId) values('123John');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('58475Carol98457Taylor24');\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('199575Sam124');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('Mike2456');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('1000');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('1001');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('10293Bob');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('David');\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into SelectNonNumericValue(UserId) values('2456');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2563, "s": 2478, "text": "Display all records from the table using a select statement. The query is as follows" }, { "code": null, "e": 2606, "s": 2563, "text": "mysql> select *from SelectNonNumericValue;" }, { "code": null, "e": 2634, "s": 2606, "text": "The following is the output" }, { "code": null, "e": 3088, "s": 2634, "text": "+----+-------------------------+\n| Id | UserId |\n+----+-------------------------+\n| 1 | 123John |\n| 2 | 58475Carol98457Taylor24 |\n| 3 | 199575Sam124 |\n| 4 | Mike2456 |\n| 5 | 1000 |\n| 6 | 1001 |\n| 7 | 10293Bob |\n| 8 | David |\n| 9 | 2456 |\n+----+-------------------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 3135, "s": 3088, "text": "Here is the query to select non-numeric values" }, { "code": null, "e": 3209, "s": 3135, "text": "mysql> select *from SelectNonNumericValue WHERE UserId REGEXP '[a-zA-Z]';" }, { "code": null, "e": 3269, "s": 3209, "text": "The following is the output that ignores the numeric values" }, { "code": null, "e": 3624, "s": 3269, "text": "+----+-------------------------+\n| Id | UserId |\n+----+-------------------------+\n| 1 | 123John |\n| 2 | 58475Carol98457Taylor24 |\n| 3 | 199575Sam124 |\n| 4 | Mike2456 |\n| 7 | 10293Bob |\n| 8 | David |\n+----+-------------------------+\n6 rows in set (0.00 sec)" } ]
Node.js url.parse(urlString, parseQueryString, slashesDenoteHost) API
14 Oct, 2021 The url.parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Syntax: url.parse( urlString, parseQueryString, slashesDenoteHost) Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse. parseQueryString: It is a boolean value. If it set to true then the query property will be set to an object returned by the querystring module’s parse() method. If it set to false then the query property on the returned URL object will be an unparsed, undecoded string. Its default value is false. slashesDenoteHost: It is a boolean value. If it set to true then the first token after the literal string // and preceding the next / will be interpreted as the host. For example: //geeksforgeeks.org/web-technology contains the result {host: ‘geeksforgeeks.org’, pathname: ‘/web-technology’} rather than {pathname: ‘//geeksforgeeks.org/web-technology’}. Its default value is false. Return Value: The url.parse() method returns an object with each part of the address as properties.Note: If urlString is not a string then it threw TypeError. If auth property exists but not decoded then it threw URIError. Example 1: javascript // Node program to demonstrate the // url.parse() method // Importing the module 'url'const url = require('url'); // URL addressconst address = 'https://geeksforgeeks.org/projects?sort=newest&lang=nodejs'; // Call parse() method using url modulelet urlObject = url.parse(address, true); console.log('URL Object returned after parsing'); // Returns an URL Objectconsole.log(urlObject) Output: Example 2: This example illustrates the properties of url object. javascript // Node program to demonstrate the // url object properties // Get different parts of the URL// using object propertiesconst url = require('url'); // URL addressconst address = 'https://geeksforgeeks.org/projects?sort=newest&lang=nodejs'; // Call parse() method using url modulelet urlObject = url.parse(address, true); console.log('Url host'); // Returns 'geeksforgeeks.org'console.log(urlObject.host); console.log('Url pathname'); // Returns '/projects'console.log(urlObject.pathname); console.log('Url search'); // Returns '?sort=newest&lang=nodejs'console.log(urlObject.search); // Get query data as an object// Returns an object: // { sort: 'newest', lang: 'nodejs' }let queryData = urlObject.query; console.log(queryData);console.log('Url query object'); // Returns 'nodejs'console.log(queryData.lang); Output: Note: The above program will compile and run by using the node myapp.js command.Reference: https://nodejs.org/docs/latest/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost mridulmanochagfg Node-URL Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 160, "s": 28, "text": "The url.parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. " }, { "code": null, "e": 169, "s": 160, "text": "Syntax: " }, { "code": null, "e": 228, "s": 169, "text": "url.parse( urlString, parseQueryString, slashesDenoteHost)" }, { "code": null, "e": 318, "s": 228, "text": "Parameters: This method accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 375, "s": 318, "text": "urlString: It holds the URL string which needs to parse." }, { "code": null, "e": 673, "s": 375, "text": "parseQueryString: It is a boolean value. If it set to true then the query property will be set to an object returned by the querystring module’s parse() method. If it set to false then the query property on the returned URL object will be an unparsed, undecoded string. Its default value is false." }, { "code": null, "e": 1055, "s": 673, "text": "slashesDenoteHost: It is a boolean value. If it set to true then the first token after the literal string // and preceding the next / will be interpreted as the host. For example: //geeksforgeeks.org/web-technology contains the result {host: ‘geeksforgeeks.org’, pathname: ‘/web-technology’} rather than {pathname: ‘//geeksforgeeks.org/web-technology’}. Its default value is false." }, { "code": null, "e": 1162, "s": 1055, "text": "Return Value: The url.parse() method returns an object with each part of the address as properties.Note: " }, { "code": null, "e": 1216, "s": 1162, "text": "If urlString is not a string then it threw TypeError." }, { "code": null, "e": 1280, "s": 1216, "text": "If auth property exists but not decoded then it threw URIError." }, { "code": null, "e": 1295, "s": 1282, "text": "Example 1: " }, { "code": null, "e": 1306, "s": 1295, "text": "javascript" }, { "code": "// Node program to demonstrate the // url.parse() method // Importing the module 'url'const url = require('url'); // URL addressconst address = 'https://geeksforgeeks.org/projects?sort=newest&lang=nodejs'; // Call parse() method using url modulelet urlObject = url.parse(address, true); console.log('URL Object returned after parsing'); // Returns an URL Objectconsole.log(urlObject)", "e": 1702, "s": 1306, "text": null }, { "code": null, "e": 1712, "s": 1702, "text": "Output: " }, { "code": null, "e": 1780, "s": 1712, "text": "Example 2: This example illustrates the properties of url object. " }, { "code": null, "e": 1791, "s": 1780, "text": "javascript" }, { "code": "// Node program to demonstrate the // url object properties // Get different parts of the URL// using object propertiesconst url = require('url'); // URL addressconst address = 'https://geeksforgeeks.org/projects?sort=newest&lang=nodejs'; // Call parse() method using url modulelet urlObject = url.parse(address, true); console.log('Url host'); // Returns 'geeksforgeeks.org'console.log(urlObject.host); console.log('Url pathname'); // Returns '/projects'console.log(urlObject.pathname); console.log('Url search'); // Returns '?sort=newest&lang=nodejs'console.log(urlObject.search); // Get query data as an object// Returns an object: // { sort: 'newest', lang: 'nodejs' }let queryData = urlObject.query; console.log(queryData);console.log('Url query object'); // Returns 'nodejs'console.log(queryData.lang); ", "e": 2615, "s": 1791, "text": null }, { "code": null, "e": 2625, "s": 2615, "text": "Output: " }, { "code": null, "e": 2820, "s": 2625, "text": "Note: The above program will compile and run by using the node myapp.js command.Reference: https://nodejs.org/docs/latest/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost " }, { "code": null, "e": 2837, "s": 2820, "text": "mridulmanochagfg" }, { "code": null, "e": 2846, "s": 2837, "text": "Node-URL" }, { "code": null, "e": 2853, "s": 2846, "text": "Picked" }, { "code": null, "e": 2861, "s": 2853, "text": "Node.js" }, { "code": null, "e": 2878, "s": 2861, "text": "Web Technologies" }, { "code": null, "e": 2976, "s": 2878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3008, "s": 2976, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3043, "s": 3008, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3113, "s": 3043, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 3140, "s": 3113, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3165, "s": 3140, "text": "Mongoose find() Function" }, { "code": null, "e": 3227, "s": 3165, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3288, "s": 3227, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3338, "s": 3288, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3381, "s": 3338, "text": "How to fetch data from an API in ReactJS ?" } ]
Node.js util.inherits() Method
13 Aug, 2020 The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘). The util.inherits() (Added in v0.3.0) method is an inbuilt application programming interface of the util module in which the constructor inherits the prototype methods from one to another and the prototype of that constructor is set to a new object which is created from superConstructor. It is mostly used for adding or inheriting some input validation on top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). And superConstructor can be accessed through the constructor.super_property for additional convenience. Its (i.e, util.inherits()) usage is not much encouraged instead use of ES6 class and extends keywords is recommended in order to get language level inheritance support. Syntax: const util = require('util'); util.inherits(constructor, superConstructor) Parameters: This function accepts two parameters as mentioned above and described below: constructor <Function>: It is any <function> that the user wants to be inherited from the class. constructor <Function>: It is any <function> that the user wants to be inherited from the class. superConstructor <Function>: It is any <function> which is mostly used for adding or inheriting some input validation. superConstructor <Function>: It is any <function> which is mostly used for adding or inheriting some input validation. Return Value <undefined>: It returns undefined value. Example 1: Filename: index.js // Node.js program to demonstrate the // util.inherits() method // Using require to access util module const util = require('util'); const emitEvent = require('events'); // MyStream function calling EventEmitterfunction streamData() { emitEvent.call(this);} // Trying to print valueconsole.log("1.> Returning util.inherits():", util.inherits(streamData, emitEvent)); // Returns undefined // Inheriting library via constructorconsole.log("2.>", streamData);// Whole library of the constructor console.log("3.>", emitEvent);// Inheriting from EventEmitter util.inherits(streamData, emitEvent); // Emiting eventsstreamData.prototype.write = function(responseData) { this.emit('send_data', responseData);}; // Creating new stream by calling functionconst stream = new streamData('default');// Printing instance of eventemitterconsole.log("4.> Instance of EventEmitter", stream instanceof emitEvent); // Returns true // Comparing value and type of an // instance with eventEmitterconsole.log("5.> '===' comparison of an " + "Instance with EventEmitter", streamData.super_ === emitEvent); // Returns true stream.on('send_data', (responseData) => { console.log("6.>", `Data Stream Received: "${responseData}"`);}); // Writing on consolestream.write('Finally it started!'); // Finally Received the data Run index.js file using the following command: node index.js Output: 1.> Returning util.inherits(): undefined 2.> [Function: streamData] 3.> <ref *1> [Function: EventEmitter] {once: [Function: once], ....., listenerCount: [Function (anonymous)]} 4.> Instance of EventEmitter true 5.> ‘===’ comparison of an Instance with EventEmitter true 6.> Data Stream Received: “Finally it started!” Example 2: Filename: index.js // Node.js program to demonstrate the // util.inherits() method in ES6 // Using require to access util module const util = require('util');const { inspect } = require('util');const emitEvent = require('events'); class streamData extends emitEvent { write(stream_data) { // Emitting the data stream this.emit('stream_data', stream_data); }} const manageStream = new streamData('default');console.log("1.>", inspect(manageStream, false, 0, true))console.log("2.>", streamData) // Returns trueconsole.log("3.>", streamData === manageStream) console.log("4.>", manageStream)manageStream.on('stream_data', (stream_data) => { // Prints the write statement after streaming console.log("5.>", `Data Stream Received: "${stream_data}"`);}); // Write on consolemanageStream.write('Finally it started streaming with ES6'); Run index.js file using the following command: node index.js Output: 1.> streamData { _events: [Object: null prototype] {}, ........................, [Symbol(kCapture)]: false} 2.> [Function: streamData] 3.> false 4.> streamData {_events: [Object: null prototype] {}, ........................, [Symbol(kCapture)]: false} 5.> Data Stream Received: “Finally it started streaming with ES6” Reference: https://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor Node.js-util-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2020" }, { "code": null, "e": 188, "s": 28, "text": "The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘)." }, { "code": null, "e": 899, "s": 188, "text": "The util.inherits() (Added in v0.3.0) method is an inbuilt application programming interface of the util module in which the constructor inherits the prototype methods from one to another and the prototype of that constructor is set to a new object which is created from superConstructor. It is mostly used for adding or inheriting some input validation on top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). And superConstructor can be accessed through the constructor.super_property for additional convenience. Its (i.e, util.inherits()) usage is not much encouraged instead use of ES6 class and extends keywords is recommended in order to get language level inheritance support." }, { "code": null, "e": 907, "s": 899, "text": "Syntax:" }, { "code": null, "e": 983, "s": 907, "text": "const util = require('util');\nutil.inherits(constructor, superConstructor)\n" }, { "code": null, "e": 1072, "s": 983, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 1170, "s": 1072, "text": "constructor <Function>: It is any <function> that the user wants to be inherited from the class." }, { "code": null, "e": 1268, "s": 1170, "text": "constructor <Function>: It is any <function> that the user wants to be inherited from the class." }, { "code": null, "e": 1387, "s": 1268, "text": "superConstructor <Function>: It is any <function> which is mostly used for adding or inheriting some input validation." }, { "code": null, "e": 1506, "s": 1387, "text": "superConstructor <Function>: It is any <function> which is mostly used for adding or inheriting some input validation." }, { "code": null, "e": 1560, "s": 1506, "text": "Return Value <undefined>: It returns undefined value." }, { "code": null, "e": 1590, "s": 1560, "text": "Example 1: Filename: index.js" }, { "code": "// Node.js program to demonstrate the // util.inherits() method // Using require to access util module const util = require('util'); const emitEvent = require('events'); // MyStream function calling EventEmitterfunction streamData() { emitEvent.call(this);} // Trying to print valueconsole.log(\"1.> Returning util.inherits():\", util.inherits(streamData, emitEvent)); // Returns undefined // Inheriting library via constructorconsole.log(\"2.>\", streamData);// Whole library of the constructor console.log(\"3.>\", emitEvent);// Inheriting from EventEmitter util.inherits(streamData, emitEvent); // Emiting eventsstreamData.prototype.write = function(responseData) { this.emit('send_data', responseData);}; // Creating new stream by calling functionconst stream = new streamData('default');// Printing instance of eventemitterconsole.log(\"4.> Instance of EventEmitter\", stream instanceof emitEvent); // Returns true // Comparing value and type of an // instance with eventEmitterconsole.log(\"5.> '===' comparison of an \" + \"Instance with EventEmitter\", streamData.super_ === emitEvent); // Returns true stream.on('send_data', (responseData) => { console.log(\"6.>\", `Data Stream Received: \"${responseData}\"`);}); // Writing on consolestream.write('Finally it started!'); // Finally Received the data", "e": 2924, "s": 1590, "text": null }, { "code": null, "e": 2971, "s": 2924, "text": "Run index.js file using the following command:" }, { "code": null, "e": 2985, "s": 2971, "text": "node index.js" }, { "code": null, "e": 2993, "s": 2985, "text": "Output:" }, { "code": null, "e": 3034, "s": 2993, "text": "1.> Returning util.inherits(): undefined" }, { "code": null, "e": 3061, "s": 3034, "text": "2.> [Function: streamData]" }, { "code": null, "e": 3170, "s": 3061, "text": "3.> <ref *1> [Function: EventEmitter] {once: [Function: once], ....., listenerCount: [Function (anonymous)]}" }, { "code": null, "e": 3204, "s": 3170, "text": "4.> Instance of EventEmitter true" }, { "code": null, "e": 3263, "s": 3204, "text": "5.> ‘===’ comparison of an Instance with EventEmitter true" }, { "code": null, "e": 3311, "s": 3263, "text": "6.> Data Stream Received: “Finally it started!”" }, { "code": null, "e": 3341, "s": 3311, "text": "Example 2: Filename: index.js" }, { "code": "// Node.js program to demonstrate the // util.inherits() method in ES6 // Using require to access util module const util = require('util');const { inspect } = require('util');const emitEvent = require('events'); class streamData extends emitEvent { write(stream_data) { // Emitting the data stream this.emit('stream_data', stream_data); }} const manageStream = new streamData('default');console.log(\"1.>\", inspect(manageStream, false, 0, true))console.log(\"2.>\", streamData) // Returns trueconsole.log(\"3.>\", streamData === manageStream) console.log(\"4.>\", manageStream)manageStream.on('stream_data', (stream_data) => { // Prints the write statement after streaming console.log(\"5.>\", `Data Stream Received: \"${stream_data}\"`);}); // Write on consolemanageStream.write('Finally it started streaming with ES6');", "e": 4171, "s": 3341, "text": null }, { "code": null, "e": 4218, "s": 4171, "text": "Run index.js file using the following command:" }, { "code": null, "e": 4232, "s": 4218, "text": "node index.js" }, { "code": null, "e": 4240, "s": 4232, "text": "Output:" }, { "code": null, "e": 4348, "s": 4240, "text": "1.> streamData { _events: [Object: null prototype] {}, ........................, [Symbol(kCapture)]: false}" }, { "code": null, "e": 4375, "s": 4348, "text": "2.> [Function: streamData]" }, { "code": null, "e": 4385, "s": 4375, "text": "3.> false" }, { "code": null, "e": 4492, "s": 4385, "text": "4.> streamData {_events: [Object: null prototype] {}, ........................, [Symbol(kCapture)]: false}" }, { "code": null, "e": 4558, "s": 4492, "text": "5.> Data Stream Received: “Finally it started streaming with ES6”" }, { "code": null, "e": 4650, "s": 4558, "text": "Reference: https://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor" }, { "code": null, "e": 4670, "s": 4650, "text": "Node.js-util-module" }, { "code": null, "e": 4678, "s": 4670, "text": "Node.js" }, { "code": null, "e": 4695, "s": 4678, "text": "Web Technologies" }, { "code": null, "e": 4793, "s": 4695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4841, "s": 4793, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4874, "s": 4841, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 4904, "s": 4874, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 4924, "s": 4904, "text": "How to update NPM ?" }, { "code": null, "e": 4978, "s": 4924, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 5040, "s": 4978, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5101, "s": 5040, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5151, "s": 5101, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5194, "s": 5151, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Fix: KeyError in Pandas
28 Nov, 2021 In this article, we will discuss how to fix the KeyError in pandas. Pandas KeyError occurs when we try to access some column/row label in our DataFrame that doesn’t exist. Usually, this error occurs when you misspell a column/row name or include an unwanted space before or after the column/row name. The link to dataset used is here Example Python3 # importing pandas as pdimport pandas as pd # using .read_csv method to import datasetdf = pd.read_csv('data.csv') Output: Python3 # intentionally passing wrong spelling of# the key present in datasetdf['country'] output: KeyError: 'country' Since there is no column with the name country we get a KeyError. We can simply fix the error by correcting the spelling of the key. If we are not sure about the spelling we can simply print the list of all column names and crosscheck. Python3 # printing all columns of the dataframeprint(df.columns.tolist()) Output: ['Country', 'Age', 'Salary', 'Purchased'] Python3 # printing the column 'Country'df['Country'] Output: 0 France 1 Spain 2 Germany 3 Spain 4 Germany 5 France 6 Spain 7 France 8 Germany 9 France Name: Country, dtype: object If we want to avoid errors raised by the compiler when an invalid key is passed, we can use df.get(‘your column’) to print column value. No error is raised if the key is invalid. Syntax : DataFrame.get( ‘column_name’ , default = default_value_if_column_is_not_present) Python3 # Again using incorrect spelling of the # column name 'Country' but this time# we will use df.get method with default # value "no_country"df.get('country', default="no_country") Output: 'no_country' But when we will use correct spelling we will get the value of the column instead of the default value. Python3 # printing column 'Country'df.get('Country', default="no_country") Output: 0 France 1 Spain 2 Germany 3 Spain 4 Germany 5 France 6 Spain 7 France 8 Germany 9 France Name: Country, dtype: object Picked Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 329, "s": 28, "text": "In this article, we will discuss how to fix the KeyError in pandas. Pandas KeyError occurs when we try to access some column/row label in our DataFrame that doesn’t exist. Usually, this error occurs when you misspell a column/row name or include an unwanted space before or after the column/row name." }, { "code": null, "e": 362, "s": 329, "text": "The link to dataset used is here" }, { "code": null, "e": 370, "s": 362, "text": "Example" }, { "code": null, "e": 378, "s": 370, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # using .read_csv method to import datasetdf = pd.read_csv('data.csv')", "e": 494, "s": 378, "text": null }, { "code": null, "e": 502, "s": 494, "text": "Output:" }, { "code": null, "e": 510, "s": 502, "text": "Python3" }, { "code": "# intentionally passing wrong spelling of# the key present in datasetdf['country']", "e": 593, "s": 510, "text": null }, { "code": null, "e": 601, "s": 593, "text": "output:" }, { "code": null, "e": 621, "s": 601, "text": "KeyError: 'country'" }, { "code": null, "e": 687, "s": 621, "text": "Since there is no column with the name country we get a KeyError." }, { "code": null, "e": 857, "s": 687, "text": "We can simply fix the error by correcting the spelling of the key. If we are not sure about the spelling we can simply print the list of all column names and crosscheck." }, { "code": null, "e": 865, "s": 857, "text": "Python3" }, { "code": "# printing all columns of the dataframeprint(df.columns.tolist())", "e": 931, "s": 865, "text": null }, { "code": null, "e": 939, "s": 931, "text": "Output:" }, { "code": null, "e": 981, "s": 939, "text": "['Country', 'Age', 'Salary', 'Purchased']" }, { "code": null, "e": 989, "s": 981, "text": "Python3" }, { "code": "# printing the column 'Country'df['Country']", "e": 1034, "s": 989, "text": null }, { "code": null, "e": 1042, "s": 1034, "text": "Output:" }, { "code": null, "e": 1201, "s": 1042, "text": "0 France\n1 Spain\n2 Germany\n3 Spain\n4 Germany\n5 France\n6 Spain\n7 France\n8 Germany\n9 France\nName: Country, dtype: object" }, { "code": null, "e": 1380, "s": 1201, "text": "If we want to avoid errors raised by the compiler when an invalid key is passed, we can use df.get(‘your column’) to print column value. No error is raised if the key is invalid." }, { "code": null, "e": 1471, "s": 1380, "text": "Syntax : DataFrame.get( ‘column_name’ , default = default_value_if_column_is_not_present)" }, { "code": null, "e": 1479, "s": 1471, "text": "Python3" }, { "code": "# Again using incorrect spelling of the # column name 'Country' but this time# we will use df.get method with default # value \"no_country\"df.get('country', default=\"no_country\")", "e": 1657, "s": 1479, "text": null }, { "code": null, "e": 1665, "s": 1657, "text": "Output:" }, { "code": null, "e": 1678, "s": 1665, "text": "'no_country'" }, { "code": null, "e": 1782, "s": 1678, "text": "But when we will use correct spelling we will get the value of the column instead of the default value." }, { "code": null, "e": 1790, "s": 1782, "text": "Python3" }, { "code": "# printing column 'Country'df.get('Country', default=\"no_country\")", "e": 1857, "s": 1790, "text": null }, { "code": null, "e": 1865, "s": 1857, "text": "Output:" }, { "code": null, "e": 2024, "s": 1865, "text": "0 France\n1 Spain\n2 Germany\n3 Spain\n4 Germany\n5 France\n6 Spain\n7 France\n8 Germany\n9 France\nName: Country, dtype: object" }, { "code": null, "e": 2031, "s": 2024, "text": "Picked" }, { "code": null, "e": 2045, "s": 2031, "text": "Python-pandas" }, { "code": null, "e": 2052, "s": 2045, "text": "Python" }, { "code": null, "e": 2150, "s": 2052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2182, "s": 2150, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2209, "s": 2182, "text": "Python Classes and Objects" }, { "code": null, "e": 2230, "s": 2209, "text": "Python OOPs Concepts" }, { "code": null, "e": 2253, "s": 2230, "text": "Introduction To PYTHON" }, { "code": null, "e": 2309, "s": 2253, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2340, "s": 2309, "text": "Python | os.path.join() method" }, { "code": null, "e": 2382, "s": 2340, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2424, "s": 2382, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2463, "s": 2424, "text": "Python | Get unique values from a list" } ]
Difference between LOOK and C-LOOK Disk scheduling algorithms
05 Jun, 2020 1. LOOK disk scheduling algorithm :Look Algorithm is actually an improves version of SCAN Algorithm. In this algorithm, the head starts from first request at one side of disk and moves towards the other end by serving all requests in between. After reaching the last request of one end, the head reverse its direction and returns to first request, servicing all requests in between. Unlike SCAN, in this the head instead of going till last track, it goes till last request and then direction is changed. Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65. The current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using LOOK algorithm. Total head movements, = (65-53)+(98-65)+(122-98) +(124-122)+(183-124)+(183-40)+(40-10) = 303 2. C-LOOK disk scheduling algorithm :C-LOOK is the modified version of both LOOK and SCAN algorithms. In this algorithm, the head starts from first request in one direction and moves towards the last request at other end, serving all request in between. After reaching last request in one end, the head jumps in other direction and move towards the remaining requests and then satisfies them in same direction as before. Unlike LOOK, it satisfies requests only in one direction. Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65. The current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using C-LOOK algorithm. Total head movements, = (65-53)+(98-65)+(122-98) +(124-122)+(183-124)+(183-10)+(40-10) = 333 Difference between LOOK and C-LOOK disk scheduling algorithm : Picked Difference Between GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Differences between IPv4 and IPv6 Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jun, 2020" }, { "code": null, "e": 556, "s": 52, "text": "1. LOOK disk scheduling algorithm :Look Algorithm is actually an improves version of SCAN Algorithm. In this algorithm, the head starts from first request at one side of disk and moves towards the other end by serving all requests in between. After reaching the last request of one end, the head reverse its direction and returns to first request, servicing all requests in between. Unlike SCAN, in this the head instead of going till last track, it goes till last request and then direction is changed." }, { "code": null, "e": 887, "s": 556, "text": "Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65. The current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using LOOK algorithm." }, { "code": null, "e": 909, "s": 887, "text": "Total head movements," }, { "code": null, "e": 992, "s": 909, "text": "= (65-53)+(98-65)+(122-98)\n +(124-122)+(183-124)+(183-40)+(40-10)\n= 303 " }, { "code": null, "e": 1471, "s": 992, "text": "2. C-LOOK disk scheduling algorithm :C-LOOK is the modified version of both LOOK and SCAN algorithms. In this algorithm, the head starts from first request in one direction and moves towards the last request at other end, serving all request in between. After reaching last request in one end, the head jumps in other direction and move towards the remaining requests and then satisfies them in same direction as before. Unlike LOOK, it satisfies requests only in one direction." }, { "code": null, "e": 1804, "s": 1471, "text": "Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65. The current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using C-LOOK algorithm." }, { "code": null, "e": 1826, "s": 1804, "text": "Total head movements," }, { "code": null, "e": 1913, "s": 1826, "text": "= (65-53)+(98-65)+(122-98)\n +(124-122)+(183-124)+(183-10)+(40-10)\n= 333 " }, { "code": null, "e": 1976, "s": 1913, "text": "Difference between LOOK and C-LOOK disk scheduling algorithm :" }, { "code": null, "e": 1983, "s": 1976, "text": "Picked" }, { "code": null, "e": 2002, "s": 1983, "text": "Difference Between" }, { "code": null, "e": 2010, "s": 2002, "text": "GATE CS" }, { "code": null, "e": 2028, "s": 2010, "text": "Operating Systems" }, { "code": null, "e": 2046, "s": 2028, "text": "Operating Systems" }, { "code": null, "e": 2144, "s": 2046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2205, "s": 2144, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2273, "s": 2205, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2311, "s": 2273, "text": "Difference between Process and Thread" }, { "code": null, "e": 2364, "s": 2311, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2398, "s": 2364, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2418, "s": 2398, "text": "Layers of OSI Model" }, { "code": null, "e": 2442, "s": 2418, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2469, "s": 2442, "text": "Types of Operating Systems" }, { "code": null, "e": 2482, "s": 2469, "text": "TCP/IP Model" } ]
How to check if mod_rewrite is enabled in PHP ?
20 Dec, 2019 In PHP, there is an inbuilt function called ‘phpinfo’. By using this function, we can output all the Loaded Modules and see the ‘mod_rewrite’ is enabled or not. Syntax: phpinfo(); Here is a process to check the ‘mod_rewrite’ load module is enabled or not. Note: The local server used here is XAMPP. Create a ‘check.php’ file in ‘c:/xampp/htdocs’ directory and write the below code in that file and save it.<?php phpinfo();?>Now, start the Apache server from the XAMPP Control Panel.Open any web browser browser and type following the URL, ‘localhost/check.php’. It will display the PHP version details and Apache Configuration.In Apache Configuration, search for the Loaded Modules section, and there you will find all the modules that are enabled.If it is enabled then it will be displayed in the list, as shown in the above screenshot. Create a ‘check.php’ file in ‘c:/xampp/htdocs’ directory and write the below code in that file and save it.<?php phpinfo();?> <?php phpinfo();?> Now, start the Apache server from the XAMPP Control Panel. Open any web browser browser and type following the URL, ‘localhost/check.php’. It will display the PHP version details and Apache Configuration. In Apache Configuration, search for the Loaded Modules section, and there you will find all the modules that are enabled. If it is enabled then it will be displayed in the list, as shown in the above screenshot. PHP-basics Picked PHP Technical Scripter Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to delete an array element based on key in PHP? PHP in_array() Function How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Dec, 2019" }, { "code": null, "e": 214, "s": 53, "text": "In PHP, there is an inbuilt function called ‘phpinfo’. By using this function, we can output all the Loaded Modules and see the ‘mod_rewrite’ is enabled or not." }, { "code": null, "e": 222, "s": 214, "text": "Syntax:" }, { "code": null, "e": 234, "s": 222, "text": "phpinfo();\n" }, { "code": null, "e": 310, "s": 234, "text": "Here is a process to check the ‘mod_rewrite’ load module is enabled or not." }, { "code": null, "e": 353, "s": 310, "text": "Note: The local server used here is XAMPP." }, { "code": null, "e": 893, "s": 353, "text": "Create a ‘check.php’ file in ‘c:/xampp/htdocs’ directory and write the below code in that file and save it.<?php phpinfo();?>Now, start the Apache server from the XAMPP Control Panel.Open any web browser browser and type following the URL, ‘localhost/check.php’. It will display the PHP version details and Apache Configuration.In Apache Configuration, search for the Loaded Modules section, and there you will find all the modules that are enabled.If it is enabled then it will be displayed in the list, as shown in the above screenshot." }, { "code": null, "e": 1020, "s": 893, "text": "Create a ‘check.php’ file in ‘c:/xampp/htdocs’ directory and write the below code in that file and save it.<?php phpinfo();?>" }, { "code": "<?php phpinfo();?>", "e": 1040, "s": 1020, "text": null }, { "code": null, "e": 1099, "s": 1040, "text": "Now, start the Apache server from the XAMPP Control Panel." }, { "code": null, "e": 1245, "s": 1099, "text": "Open any web browser browser and type following the URL, ‘localhost/check.php’. It will display the PHP version details and Apache Configuration." }, { "code": null, "e": 1367, "s": 1245, "text": "In Apache Configuration, search for the Loaded Modules section, and there you will find all the modules that are enabled." }, { "code": null, "e": 1457, "s": 1367, "text": "If it is enabled then it will be displayed in the list, as shown in the above screenshot." }, { "code": null, "e": 1468, "s": 1457, "text": "PHP-basics" }, { "code": null, "e": 1475, "s": 1468, "text": "Picked" }, { "code": null, "e": 1479, "s": 1475, "text": "PHP" }, { "code": null, "e": 1498, "s": 1479, "text": "Technical Scripter" }, { "code": null, "e": 1515, "s": 1498, "text": "Web Technologies" }, { "code": null, "e": 1542, "s": 1515, "text": "Web technologies Questions" }, { "code": null, "e": 1546, "s": 1542, "text": "PHP" }, { "code": null, "e": 1644, "s": 1546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1689, "s": 1644, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 1741, "s": 1689, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 1765, "s": 1741, "text": "PHP in_array() Function" }, { "code": null, "e": 1815, "s": 1765, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1855, "s": 1815, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1888, "s": 1855, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1950, "s": 1888, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2011, "s": 1950, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2061, "s": 2011, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Time Series Analysis using ARIMA model in R Programming
08 Jul, 2020 In R programming, data analysis and visualization is so easy to learn the behaviour of the data. Moreover, the R language is used mostly in the data science field after Python. Time series analysis is a type of analysis of data used to check the behaviour of data over a period of time. The data is collected over time sequentially by the ts() function along with some parameters. It helps in analyzing the pattern of the data over a graph. There are many techniques used to forecast the time series object over the plot graph but the ARIMA model is the most widely used approach out of them. Time series forecasting is a process of predicting future values with the help of some statistical tools and methods used on a data set with historical data. Some of the applications of time series forecasting are: Predicting stock prices Forecast weather Forecast the sales of a product ARIMA stands for AutoRegressive Integrated Moving Average and is specified by three order parameters: (p, d, q). AR(p) Autoregression: A regression model that utilizes the dependent relationship between a current observation and observations over a previous period.An auto regressive (AR(p)) component refers to the use of past values in the regression equation for the time series. I(d) Integration: Uses differencing of observations (subtracting an observation from observation at the previous time step) in order to make the time series stationary. Differencing involves the subtraction of the current values of a series with its previous values d number of times. MA(q) Moving Average: A model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations. A moving average component depicts the error of the model as a combination of previous error terms. The order q represents the number of terms to be included in the model. Types of ARIMA Model ARIMA: Non-seasonal Autoregressive Integrated Moving Averages SARIMA: Seasonal ARIMA SARIMAX: Seasonal ARIMA with exogenous variables In R programming, arima() function is used to perform this technique. ARIMA model is used to fit a univariate data. auto.arima() function returns the best ARIMA model by searching over many models. Syntax:auto.arima(x) Parameters:x: represents univariate time series object To know about more optional parameters, use below command in the console: help(“auto.arima”) Example 1:In this example, let’s predict the next 10 sale values by using BJsales dataset present in R packages. This dataset is already a time series object, so there is no need to apply ts() function. # R program to illustrate# Time Series Analysis # Using ARIMA model in R # Install the library for forecast()install.packages("forecast") # library required for forecasting library(forecast) # Output to be created as png filepng(file = "TimeSeriesGFG.png") # Plotting graph without forecastingplot(BJsales, main = "Graph without forecasting",col.main = "darkgreen") # Saving the filedev.off() # Output to be created as png file png(file = "TimeSeriesARIMAGFG.png") # Fitting model using arima model fit <- auto.arima(BJsales) # Next 10 forecasted values forecastedValues <- forecast(fit, 10) # Print forecasted valuesprint(forecastedValues) plot(forecastedValues, main = "Graph with forecasting",col.main = "darkgreen") # saving the file dev.off() Output: Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 151 262.8620 261.1427 264.5814 260.2325 265.4915 152 263.0046 260.2677 265.7415 258.8189 267.1903 153 263.1301 259.4297 266.8304 257.4709 268.7893 154 263.2405 258.5953 267.8857 256.1363 270.3447 155 263.3377 257.7600 268.9153 254.8074 271.8680 156 263.4232 256.9253 269.9211 253.4855 273.3608 157 263.4984 256.0941 270.9028 252.1744 274.8224 158 263.5647 255.2691 271.8602 250.8778 276.2516 159 263.6229 254.4529 272.7930 249.5986 277.6473 160 263.6742 253.6474 273.7011 248.3395 279.0089 Explanation:Following output is produced by executing the above code. 10 next values are predicted by using forecast() function based on ARIMA model of BJsales dataset. First graph shows the visuals of BJsales without forecasting and second graphs shows the visuals of BJsales with forecasted values. Example 2:In this example, let’s predict next 50 values of DAX in EuStockMarkets dataset present in R base package. It can take longer time than usual as the dataset is large enough as compared to BJsales dataset. This dataset is already a time series object, so there is no need to apply ts() function. # R program to illustrate# Time Series Analysis # Using ARIMA model in R # Install the library for forecast()install.packages("forecast") # library required for forecasting library(forecast) # Output to be created as png filepng(file = "TimeSeries2GFG.png") # Plotting graph without forecastingplot(EuStockMarkets[, "DAX"],main = "Graph without forecasting",col.main = "darkgreen") # Saving the filedev.off() # Output to be created as png file png(file = "TimeSeriesARIMA2GFG.png") # Fitting model using arima model fit <- auto.arima(EuStockMarkets[, "DAX"]) # Next 50 forecasted values forecastedValues <- forecast(fit, 50) # Print forecasted valuesprint(forecastedValues) plot(forecastedValues, main = "Graph with forecasting",col.main = "darkgreen") # saving the file dev.off() Output: Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 1998.650 5477.071 5432.030 5522.113 5408.186 5545.957 1998.654 5455.437 5385.726 5525.148 5348.823 5562.051 1998.658 5438.930 5345.840 5532.020 5296.561 5581.299 1998.662 5470.902 5353.454 5588.349 5291.281 5650.522 1998.665 5478.529 5334.560 5622.498 5258.347 5698.710 1998.669 5505.691 5333.182 5678.199 5241.862 5769.519 1998.673 5512.314 5306.115 5718.513 5196.960 5827.669 1998.677 5517.260 5276.482 5758.037 5149.022 5885.497 1998.681 5524.894 5248.363 5801.426 5101.976 5947.813 1998.685 5540.523 5226.767 5854.279 5060.675 6020.371 1998.688 5551.386 5198.746 5904.026 5012.070 6090.702 1998.692 5564.652 5171.572 5957.732 4963.488 6165.815 1998.696 5574.519 5139.172 6009.867 4908.713 6240.326 1998.700 5584.631 5105.761 6063.500 4852.263 6316.998 1998.704 5595.439 5071.763 6119.116 4794.545 6396.333 1998.708 5607.468 5037.671 6177.265 4736.039 6478.897 1998.712 5618.547 5001.313 6235.781 4674.569 6562.524 1998.715 5629.916 4963.981 6295.852 4611.456 6648.377 1998.719 5640.767 4924.864 6356.669 4545.888 6735.645 1998.723 5651.753 4884.718 6418.789 4478.674 6824.833 1998.727 5662.881 4843.558 6482.203 4409.835 6915.926 1998.731 5674.177 4801.426 6546.928 4339.419 7008.934 1998.735 5685.286 4757.984 6612.588 4267.100 7103.472 1998.738 5696.434 4713.486 6679.383 4193.144 7199.725 1998.742 5707.511 4667.838 6747.183 4117.468 7297.553 1998.746 5718.625 4621.180 6816.069 4040.228 7397.022 1998.750 5729.763 4573.514 6886.012 3961.433 7498.093 1998.754 5740.921 4524.851 6956.990 3881.103 7600.739 1998.758 5752.044 4475.153 7028.934 3799.208 7704.879 1998.762 5763.173 4424.479 7101.867 3715.817 7810.528 1998.765 5774.293 4372.828 7175.758 3630.938 7917.649 1998.769 5785.422 4320.235 7250.610 3544.611 8026.233 1998.773 5796.554 4266.706 7326.403 3456.853 8136.256 1998.777 5807.688 4212.254 7403.123 3367.682 8247.695 1998.781 5818.816 4156.883 7480.749 3277.109 8360.523 1998.785 5829.945 4100.614 7559.276 3185.162 8474.729 1998.788 5841.073 4043.457 7638.690 3091.856 8590.291 1998.792 5852.203 3985.425 7718.982 2997.212 8707.195 1998.796 5863.333 3926.528 7800.139 2901.245 8825.422 1998.800 5874.464 3866.776 7882.152 2803.970 8944.957 1998.804 5885.593 3806.178 7965.007 2705.402 9065.783 1998.808 5896.722 3744.746 8048.698 2605.559 9187.886 1998.812 5907.852 3682.489 8133.214 2504.453 9311.250 1998.815 5918.981 3619.416 8218.547 2402.100 9435.863 1998.819 5930.111 3555.536 8304.686 2298.512 9561.710 1998.823 5941.241 3490.857 8391.624 2193.702 9688.779 1998.827 5952.370 3425.388 8479.352 2087.684 9817.056 1998.831 5963.500 3359.137 8567.862 1980.470 9946.529 1998.835 5974.629 3292.111 8657.147 1872.072 10077.186 1998.838 5985.759 3224.319 8747.198 1762.502 10209.016 Explanation:The following output is produced by executing the above code. 50 future stock price of DAX is predicted by using forecast() function based on the ARIMA model of DAX of EuStockMarkets dataset. The first graph shows the visuals of DAX of EuStockMarkets dataset without forecasting and second graphs show the visuals of DAX of EuStockMarkets dataset with forecasted values. data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Printing Output of an R Program Group by function in R using Dplyr How to change Row Names of DataFrame in R ? R Programming Language - Introduction How to Change Axis Scales in R Plots?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 621, "s": 28, "text": "In R programming, data analysis and visualization is so easy to learn the behaviour of the data. Moreover, the R language is used mostly in the data science field after Python. Time series analysis is a type of analysis of data used to check the behaviour of data over a period of time. The data is collected over time sequentially by the ts() function along with some parameters. It helps in analyzing the pattern of the data over a graph. There are many techniques used to forecast the time series object over the plot graph but the ARIMA model is the most widely used approach out of them." }, { "code": null, "e": 836, "s": 621, "text": "Time series forecasting is a process of predicting future values with the help of some statistical tools and methods used on a data set with historical data. Some of the applications of time series forecasting are:" }, { "code": null, "e": 860, "s": 836, "text": "Predicting stock prices" }, { "code": null, "e": 877, "s": 860, "text": "Forecast weather" }, { "code": null, "e": 909, "s": 877, "text": "Forecast the sales of a product" }, { "code": null, "e": 1022, "s": 909, "text": "ARIMA stands for AutoRegressive Integrated Moving Average and is specified by three order parameters: (p, d, q)." }, { "code": null, "e": 1292, "s": 1022, "text": "AR(p) Autoregression: A regression model that utilizes the dependent relationship between a current observation and observations over a previous period.An auto regressive (AR(p)) component refers to the use of past values in the regression equation for the time series." }, { "code": null, "e": 1577, "s": 1292, "text": "I(d) Integration: Uses differencing of observations (subtracting an observation from observation at the previous time step) in order to make the time series stationary. Differencing involves the subtraction of the current values of a series with its previous values d number of times." }, { "code": null, "e": 1908, "s": 1577, "text": "MA(q) Moving Average: A model that uses the dependency between an observation and a residual error from a moving average model applied to lagged observations. A moving average component depicts the error of the model as a combination of previous error terms. The order q represents the number of terms to be included in the model." }, { "code": null, "e": 1929, "s": 1908, "text": "Types of ARIMA Model" }, { "code": null, "e": 1991, "s": 1929, "text": "ARIMA: Non-seasonal Autoregressive Integrated Moving Averages" }, { "code": null, "e": 2014, "s": 1991, "text": "SARIMA: Seasonal ARIMA" }, { "code": null, "e": 2063, "s": 2014, "text": "SARIMAX: Seasonal ARIMA with exogenous variables" }, { "code": null, "e": 2261, "s": 2063, "text": "In R programming, arima() function is used to perform this technique. ARIMA model is used to fit a univariate data. auto.arima() function returns the best ARIMA model by searching over many models." }, { "code": null, "e": 2282, "s": 2261, "text": "Syntax:auto.arima(x)" }, { "code": null, "e": 2337, "s": 2282, "text": "Parameters:x: represents univariate time series object" }, { "code": null, "e": 2430, "s": 2337, "text": "To know about more optional parameters, use below command in the console: help(“auto.arima”)" }, { "code": null, "e": 2633, "s": 2430, "text": "Example 1:In this example, let’s predict the next 10 sale values by using BJsales dataset present in R packages. This dataset is already a time series object, so there is no need to apply ts() function." }, { "code": "# R program to illustrate# Time Series Analysis # Using ARIMA model in R # Install the library for forecast()install.packages(\"forecast\") # library required for forecasting library(forecast) # Output to be created as png filepng(file = \"TimeSeriesGFG.png\") # Plotting graph without forecastingplot(BJsales, main = \"Graph without forecasting\",col.main = \"darkgreen\") # Saving the filedev.off() # Output to be created as png file png(file = \"TimeSeriesARIMAGFG.png\") # Fitting model using arima model fit <- auto.arima(BJsales) # Next 10 forecasted values forecastedValues <- forecast(fit, 10) # Print forecasted valuesprint(forecastedValues) plot(forecastedValues, main = \"Graph with forecasting\",col.main = \"darkgreen\") # saving the file dev.off() ", "e": 3398, "s": 2633, "text": null }, { "code": null, "e": 3406, "s": 3398, "text": "Output:" }, { "code": null, "e": 4010, "s": 3406, "text": "Point Forecast Lo 80 Hi 80 Lo 95 Hi 95\n151 262.8620 261.1427 264.5814 260.2325 265.4915\n152 263.0046 260.2677 265.7415 258.8189 267.1903\n153 263.1301 259.4297 266.8304 257.4709 268.7893\n154 263.2405 258.5953 267.8857 256.1363 270.3447\n155 263.3377 257.7600 268.9153 254.8074 271.8680\n156 263.4232 256.9253 269.9211 253.4855 273.3608\n157 263.4984 256.0941 270.9028 252.1744 274.8224\n158 263.5647 255.2691 271.8602 250.8778 276.2516\n159 263.6229 254.4529 272.7930 249.5986 277.6473\n160 263.6742 253.6474 273.7011 248.3395 279.0089\n" }, { "code": null, "e": 4311, "s": 4010, "text": "Explanation:Following output is produced by executing the above code. 10 next values are predicted by using forecast() function based on ARIMA model of BJsales dataset. First graph shows the visuals of BJsales without forecasting and second graphs shows the visuals of BJsales with forecasted values." }, { "code": null, "e": 4615, "s": 4311, "text": "Example 2:In this example, let’s predict next 50 values of DAX in EuStockMarkets dataset present in R base package. It can take longer time than usual as the dataset is large enough as compared to BJsales dataset. This dataset is already a time series object, so there is no need to apply ts() function." }, { "code": "# R program to illustrate# Time Series Analysis # Using ARIMA model in R # Install the library for forecast()install.packages(\"forecast\") # library required for forecasting library(forecast) # Output to be created as png filepng(file = \"TimeSeries2GFG.png\") # Plotting graph without forecastingplot(EuStockMarkets[, \"DAX\"],main = \"Graph without forecasting\",col.main = \"darkgreen\") # Saving the filedev.off() # Output to be created as png file png(file = \"TimeSeriesARIMA2GFG.png\") # Fitting model using arima model fit <- auto.arima(EuStockMarkets[, \"DAX\"]) # Next 50 forecasted values forecastedValues <- forecast(fit, 50) # Print forecasted valuesprint(forecastedValues) plot(forecastedValues, main = \"Graph with forecasting\",col.main = \"darkgreen\") # saving the file dev.off() ", "e": 5413, "s": 4615, "text": null }, { "code": null, "e": 5421, "s": 5413, "text": "Output:" }, { "code": null, "e": 8533, "s": 5421, "text": " Point Forecast Lo 80 Hi 80 Lo 95 Hi 95\n1998.650 5477.071 5432.030 5522.113 5408.186 5545.957\n1998.654 5455.437 5385.726 5525.148 5348.823 5562.051\n1998.658 5438.930 5345.840 5532.020 5296.561 5581.299\n1998.662 5470.902 5353.454 5588.349 5291.281 5650.522\n1998.665 5478.529 5334.560 5622.498 5258.347 5698.710\n1998.669 5505.691 5333.182 5678.199 5241.862 5769.519\n1998.673 5512.314 5306.115 5718.513 5196.960 5827.669\n1998.677 5517.260 5276.482 5758.037 5149.022 5885.497\n1998.681 5524.894 5248.363 5801.426 5101.976 5947.813\n1998.685 5540.523 5226.767 5854.279 5060.675 6020.371\n1998.688 5551.386 5198.746 5904.026 5012.070 6090.702\n1998.692 5564.652 5171.572 5957.732 4963.488 6165.815\n1998.696 5574.519 5139.172 6009.867 4908.713 6240.326\n1998.700 5584.631 5105.761 6063.500 4852.263 6316.998\n1998.704 5595.439 5071.763 6119.116 4794.545 6396.333\n1998.708 5607.468 5037.671 6177.265 4736.039 6478.897\n1998.712 5618.547 5001.313 6235.781 4674.569 6562.524\n1998.715 5629.916 4963.981 6295.852 4611.456 6648.377\n1998.719 5640.767 4924.864 6356.669 4545.888 6735.645\n1998.723 5651.753 4884.718 6418.789 4478.674 6824.833\n1998.727 5662.881 4843.558 6482.203 4409.835 6915.926\n1998.731 5674.177 4801.426 6546.928 4339.419 7008.934\n1998.735 5685.286 4757.984 6612.588 4267.100 7103.472\n1998.738 5696.434 4713.486 6679.383 4193.144 7199.725\n1998.742 5707.511 4667.838 6747.183 4117.468 7297.553\n1998.746 5718.625 4621.180 6816.069 4040.228 7397.022\n1998.750 5729.763 4573.514 6886.012 3961.433 7498.093\n1998.754 5740.921 4524.851 6956.990 3881.103 7600.739\n1998.758 5752.044 4475.153 7028.934 3799.208 7704.879\n1998.762 5763.173 4424.479 7101.867 3715.817 7810.528\n1998.765 5774.293 4372.828 7175.758 3630.938 7917.649\n1998.769 5785.422 4320.235 7250.610 3544.611 8026.233\n1998.773 5796.554 4266.706 7326.403 3456.853 8136.256\n1998.777 5807.688 4212.254 7403.123 3367.682 8247.695\n1998.781 5818.816 4156.883 7480.749 3277.109 8360.523\n1998.785 5829.945 4100.614 7559.276 3185.162 8474.729\n1998.788 5841.073 4043.457 7638.690 3091.856 8590.291\n1998.792 5852.203 3985.425 7718.982 2997.212 8707.195\n1998.796 5863.333 3926.528 7800.139 2901.245 8825.422\n1998.800 5874.464 3866.776 7882.152 2803.970 8944.957\n1998.804 5885.593 3806.178 7965.007 2705.402 9065.783\n1998.808 5896.722 3744.746 8048.698 2605.559 9187.886\n1998.812 5907.852 3682.489 8133.214 2504.453 9311.250\n1998.815 5918.981 3619.416 8218.547 2402.100 9435.863\n1998.819 5930.111 3555.536 8304.686 2298.512 9561.710\n1998.823 5941.241 3490.857 8391.624 2193.702 9688.779\n1998.827 5952.370 3425.388 8479.352 2087.684 9817.056\n1998.831 5963.500 3359.137 8567.862 1980.470 9946.529\n1998.835 5974.629 3292.111 8657.147 1872.072 10077.186\n1998.838 5985.759 3224.319 8747.198 1762.502 10209.016\n" }, { "code": null, "e": 8916, "s": 8533, "text": "Explanation:The following output is produced by executing the above code. 50 future stock price of DAX is predicted by using forecast() function based on the ARIMA model of DAX of EuStockMarkets dataset. The first graph shows the visuals of DAX of EuStockMarkets dataset without forecasting and second graphs show the visuals of DAX of EuStockMarkets dataset with forecasted values." }, { "code": null, "e": 8929, "s": 8916, "text": "data-science" }, { "code": null, "e": 8948, "s": 8929, "text": "R Machine-Learning" }, { "code": null, "e": 8959, "s": 8948, "text": "R Language" }, { "code": null, "e": 9057, "s": 8959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9109, "s": 9057, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 9167, "s": 9109, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 9219, "s": 9167, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 9277, "s": 9219, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 9309, "s": 9277, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 9341, "s": 9309, "text": "Printing Output of an R Program" }, { "code": null, "e": 9376, "s": 9341, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 9420, "s": 9376, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 9458, "s": 9420, "text": "R Programming Language - Introduction" } ]
HTML | lang Attribute
19 Jul, 2019 This attribute is used to specify the language of the element content. Some examples of languages are en for English, es for Spanish, etc. Syntax: <element lang = "language_code"> Attribute Value: This attribute contains single value language_code which is used to specify the language of content. Difference between HTML 4.1 and HTML 5: In HTML 5, the lang attribute can be used with any HTML elements but in HTML 4.1 the lang attribute is used with <base>, <br>, <frame>, <frameset>, <hr>, <iframe>, <param>, and <script> elements. Example: <!DOCTYPE html><html> <head> <title>lang attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>lang attribute</h2> <p lang = "en">A computer science portal for geeks</p> </body></html> Output: Supported Browsers: The browser supported by lang attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari HTML-Attributes CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Jul, 2019" }, { "code": null, "e": 192, "s": 53, "text": "This attribute is used to specify the language of the element content. Some examples of languages are en for English, es for Spanish, etc." }, { "code": null, "e": 200, "s": 192, "text": "Syntax:" }, { "code": null, "e": 233, "s": 200, "text": "<element lang = \"language_code\">" }, { "code": null, "e": 351, "s": 233, "text": "Attribute Value: This attribute contains single value language_code which is used to specify the language of content." }, { "code": null, "e": 587, "s": 351, "text": "Difference between HTML 4.1 and HTML 5: In HTML 5, the lang attribute can be used with any HTML elements but in HTML 4.1 the lang attribute is used with <base>, <br>, <frame>, <frameset>, <hr>, <iframe>, <param>, and <script> elements." }, { "code": null, "e": 596, "s": 587, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>lang attribute</title> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>lang attribute</h2> <p lang = \"en\">A computer science portal for geeks</p> </body></html>", "e": 990, "s": 596, "text": null }, { "code": null, "e": 998, "s": 990, "text": "Output:" }, { "code": null, "e": 1076, "s": 998, "text": "Supported Browsers: The browser supported by lang attribute are listed below:" }, { "code": null, "e": 1090, "s": 1076, "text": "Google Chrome" }, { "code": null, "e": 1108, "s": 1090, "text": "Internet Explorer" }, { "code": null, "e": 1116, "s": 1108, "text": "Firefox" }, { "code": null, "e": 1122, "s": 1116, "text": "Opera" }, { "code": null, "e": 1129, "s": 1122, "text": "Safari" }, { "code": null, "e": 1145, "s": 1129, "text": "HTML-Attributes" }, { "code": null, "e": 1149, "s": 1145, "text": "CSS" }, { "code": null, "e": 1154, "s": 1149, "text": "HTML" }, { "code": null, "e": 1171, "s": 1154, "text": "Web Technologies" }, { "code": null, "e": 1176, "s": 1171, "text": "HTML" }, { "code": null, "e": 1274, "s": 1176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1322, "s": 1274, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1384, "s": 1322, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1434, "s": 1384, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1492, "s": 1434, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 1542, "s": 1492, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1590, "s": 1542, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1652, "s": 1590, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1702, "s": 1652, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1726, "s": 1702, "text": "REST API (Introduction)" } ]
Count of distinct substrings of a string using Suffix Trie
06 Jul, 2022 Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples: Input : str = “ababa” Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa" The idea is create a Trie of all suffixes of given string. Once the Trie is constricted, our answer is total number of nodes in the constructed Trie. For example below diagram represent Trie of all suffixes for “ababa”. Total number of nodes is 10 which is our answer. How does this work? Each root to node path of a Trie represents a prefix of words present in Trie. Here we words are suffixes. So each node represents a prefix of suffixes. Every substring of a string “str” is a prefix of a suffix of “str”. Below is implementation based on above idea. C++ Java C# // A C++ program to find the count of distinct substring// of a string using trie data structure#include <bits/stdc++.h>#define MAX_CHAR 26using namespace std; // A Suffix Trie (A Trie of all suffixes) Nodeclass SuffixTrieNode{public: SuffixTrieNode *children[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = NULL; } // A recursive function to insert a suffix of the s // in subtree rooted with this node void insertSuffix(string suffix);}; // A Trie of all suffixesclass SuffixTrie{ SuffixTrieNode *root; int _countNodesInTrie(SuffixTrieNode *);public: // Constructor (Builds a trie of suffies of the given text) SuffixTrie(string s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root->insertSuffix(s.substr(i)); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); }}; // A recursive function to insert a suffix of the s in// subtree rooted with this nodevoid SuffixTrieNode::insertSuffix(string s){ // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = s.at(0) - 'a'; // If there is no edge for this character, // add a new edge if (children[cIndex] == NULL) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex]->insertSuffix(s.substr(1)); }} // A recursive function to count nodes in trieint SuffixTrie::_countNodesInTrie(SuffixTrieNode* node){ // If all characters of pattern have been processed, if (node == NULL) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node->children[i] != NULL) count += _countNodesInTrie(node->children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count);} // Returns count of distinct substrings of strint countDistinctSubstring(string str){ // Construct a Trie of all suffixes SuffixTrie sTrie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie();} // Driver program to test above functionint main(){ string str = "ababa"; cout << "Count of distinct substrings is " << countDistinctSubstring(str); return 0;} // A Java program to find the count of distinct substring// of a string using trie data structurepublic class Suffix{ // A Suffix Trie (A Trie of all suffixes) Node static class SuffixTrieNode { static final int MAX_CHAR = 26; SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = null; } // A recursive function to insert a suffix of the s in // subtree rooted with this node void insertSuffix(String s) { // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = (char) (s.charAt(0) - 'a'); // If there is no edge for this character, // add a new edge if (children[cIndex] == null) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex].insertSuffix(s.substring(1)); } } } // A Trie of all suffixes static class Suffix_trie { static final int MAX_CHAR = 26; SuffixTrieNode root; // Constructor (Builds a trie of suffies of the given text) Suffix_trie(String s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root.insertSuffix(s.substring(i)); } // A recursive function to count nodes in trie int _countNodesInTrie(SuffixTrieNode node) { // If all characters of pattern have been processed, if (node == null) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node.children[i] != null) count += _countNodesInTrie(node.children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); } } // Returns count of distinct substrings of str static int countDistinctSubstring(String str) { // Construct a Trie of all suffixes Suffix_trie sTrie = new Suffix_trie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function public static void main(String args[]) { String str = "ababa"; System.out.println("Count of distinct substrings is " + countDistinctSubstring(str)); }}// This code is contributed by Sumit Ghosh // C# program to find the count of distinct substring// of a string using trie data structureusing System; public class Suffix{ // A Suffix Trie (A Trie of all suffixes) Node public class SuffixTrieNode { static readonly int MAX_CHAR = 26; public SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR]; public SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = null; } // A recursive function to insert a suffix of the s in // subtree rooted with this node public void insertSuffix(String s) { // If string has more characters if (s.Length > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = (char) (s[0] - 'a'); // If there is no edge for this character, // add a new edge if (children[cIndex] == null) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex].insertSuffix(s.Substring(1)); } } } // A Trie of all suffixes public class Suffix_trie { static readonly int MAX_CHAR = 26; public SuffixTrieNode root; // Constructor (Builds a trie of suffies of the given text) public Suffix_trie(String s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.Length; i++) root.insertSuffix(s.Substring(i)); } // A recursive function to count nodes in trie public int _countNodesInTrie(SuffixTrieNode node) { // If all characters of pattern have been processed, if (node == null) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node.children[i] != null) count += _countNodesInTrie(node.children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // method to count total nodes in suffix trie public int countNodesInTrie() { return _countNodesInTrie(root); } } // Returns count of distinct substrings of str static int countDistinctSubstring(String str) { // Construct a Trie of all suffixes Suffix_trie sTrie = new Suffix_trie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function public static void Main(String []args) { String str = "ababa"; Console.WriteLine("Count of distinct substrings is " + countDistinctSubstring(str)); }} // This code contributed by Rajput-Ji Count of distinct substrings is 10 Time Complexity: O(n), where n is the length of string.Auxiliary Space: O(1) We will soon be discussing Suffix Array and Suffix Tree based approaches for this problem. This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Rajput-Ji anandkumarshivam2266 hardikkoriintern Suffix-Tree Trie Advanced Data Structure Arrays Strings Arrays Strings Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 192, "s": 52, "text": "Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples:" }, { "code": null, "e": 348, "s": 192, "text": "Input : str = “ababa”\nOutput : 10\nTotal number of distinct substring are 10, which are,\n\"\", \"a\", \"b\", \"ab\", \"ba\", \"aba\", \"bab\", \"abab\", \"baba\"\nand \"ababa\"" }, { "code": null, "e": 618, "s": 348, "text": "The idea is create a Trie of all suffixes of given string. Once the Trie is constricted, our answer is total number of nodes in the constructed Trie. For example below diagram represent Trie of all suffixes for “ababa”. Total number of nodes is 10 which is our answer. " }, { "code": null, "e": 640, "s": 620, "text": "How does this work?" }, { "code": null, "e": 793, "s": 640, "text": "Each root to node path of a Trie represents a prefix of words present in Trie. Here we words are suffixes. So each node represents a prefix of suffixes." }, { "code": null, "e": 861, "s": 793, "text": "Every substring of a string “str” is a prefix of a suffix of “str”." }, { "code": null, "e": 907, "s": 861, "text": "Below is implementation based on above idea. " }, { "code": null, "e": 911, "s": 907, "text": "C++" }, { "code": null, "e": 916, "s": 911, "text": "Java" }, { "code": null, "e": 919, "s": 916, "text": "C#" }, { "code": "// A C++ program to find the count of distinct substring// of a string using trie data structure#include <bits/stdc++.h>#define MAX_CHAR 26using namespace std; // A Suffix Trie (A Trie of all suffixes) Nodeclass SuffixTrieNode{public: SuffixTrieNode *children[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = NULL; } // A recursive function to insert a suffix of the s // in subtree rooted with this node void insertSuffix(string suffix);}; // A Trie of all suffixesclass SuffixTrie{ SuffixTrieNode *root; int _countNodesInTrie(SuffixTrieNode *);public: // Constructor (Builds a trie of suffies of the given text) SuffixTrie(string s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root->insertSuffix(s.substr(i)); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); }}; // A recursive function to insert a suffix of the s in// subtree rooted with this nodevoid SuffixTrieNode::insertSuffix(string s){ // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = s.at(0) - 'a'; // If there is no edge for this character, // add a new edge if (children[cIndex] == NULL) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex]->insertSuffix(s.substr(1)); }} // A recursive function to count nodes in trieint SuffixTrie::_countNodesInTrie(SuffixTrieNode* node){ // If all characters of pattern have been processed, if (node == NULL) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node->children[i] != NULL) count += _countNodesInTrie(node->children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count);} // Returns count of distinct substrings of strint countDistinctSubstring(string str){ // Construct a Trie of all suffixes SuffixTrie sTrie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie();} // Driver program to test above functionint main(){ string str = \"ababa\"; cout << \"Count of distinct substrings is \" << countDistinctSubstring(str); return 0;}", "e": 3652, "s": 919, "text": null }, { "code": "// A Java program to find the count of distinct substring// of a string using trie data structurepublic class Suffix{ // A Suffix Trie (A Trie of all suffixes) Node static class SuffixTrieNode { static final int MAX_CHAR = 26; SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = null; } // A recursive function to insert a suffix of the s in // subtree rooted with this node void insertSuffix(String s) { // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = (char) (s.charAt(0) - 'a'); // If there is no edge for this character, // add a new edge if (children[cIndex] == null) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex].insertSuffix(s.substring(1)); } } } // A Trie of all suffixes static class Suffix_trie { static final int MAX_CHAR = 26; SuffixTrieNode root; // Constructor (Builds a trie of suffies of the given text) Suffix_trie(String s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root.insertSuffix(s.substring(i)); } // A recursive function to count nodes in trie int _countNodesInTrie(SuffixTrieNode node) { // If all characters of pattern have been processed, if (node == null) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node.children[i] != null) count += _countNodesInTrie(node.children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); } } // Returns count of distinct substrings of str static int countDistinctSubstring(String str) { // Construct a Trie of all suffixes Suffix_trie sTrie = new Suffix_trie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function public static void main(String args[]) { String str = \"ababa\"; System.out.println(\"Count of distinct substrings is \" + countDistinctSubstring(str)); }}// This code is contributed by Sumit Ghosh", "e": 6838, "s": 3652, "text": null }, { "code": "// C# program to find the count of distinct substring// of a string using trie data structureusing System; public class Suffix{ // A Suffix Trie (A Trie of all suffixes) Node public class SuffixTrieNode { static readonly int MAX_CHAR = 26; public SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR]; public SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = null; } // A recursive function to insert a suffix of the s in // subtree rooted with this node public void insertSuffix(String s) { // If string has more characters if (s.Length > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = (char) (s[0] - 'a'); // If there is no edge for this character, // add a new edge if (children[cIndex] == null) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex].insertSuffix(s.Substring(1)); } } } // A Trie of all suffixes public class Suffix_trie { static readonly int MAX_CHAR = 26; public SuffixTrieNode root; // Constructor (Builds a trie of suffies of the given text) public Suffix_trie(String s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.Length; i++) root.insertSuffix(s.Substring(i)); } // A recursive function to count nodes in trie public int _countNodesInTrie(SuffixTrieNode node) { // If all characters of pattern have been processed, if (node == null) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node.children[i] != null) count += _countNodesInTrie(node.children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // method to count total nodes in suffix trie public int countNodesInTrie() { return _countNodesInTrie(root); } } // Returns count of distinct substrings of str static int countDistinctSubstring(String str) { // Construct a Trie of all suffixes Suffix_trie sTrie = new Suffix_trie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function public static void Main(String []args) { String str = \"ababa\"; Console.WriteLine(\"Count of distinct substrings is \" + countDistinctSubstring(str)); }} // This code contributed by Rajput-Ji", "e": 10091, "s": 6838, "text": null }, { "code": null, "e": 10126, "s": 10091, "text": "Count of distinct substrings is 10" }, { "code": null, "e": 10203, "s": 10126, "text": "Time Complexity: O(n), where n is the length of string.Auxiliary Space: O(1)" }, { "code": null, "e": 10593, "s": 10203, "text": "We will soon be discussing Suffix Array and Suffix Tree based approaches for this problem. This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 10603, "s": 10593, "text": "Rajput-Ji" }, { "code": null, "e": 10624, "s": 10603, "text": "anandkumarshivam2266" }, { "code": null, "e": 10641, "s": 10624, "text": "hardikkoriintern" }, { "code": null, "e": 10653, "s": 10641, "text": "Suffix-Tree" }, { "code": null, "e": 10658, "s": 10653, "text": "Trie" }, { "code": null, "e": 10682, "s": 10658, "text": "Advanced Data Structure" }, { "code": null, "e": 10689, "s": 10682, "text": "Arrays" }, { "code": null, "e": 10697, "s": 10689, "text": "Strings" }, { "code": null, "e": 10704, "s": 10697, "text": "Arrays" }, { "code": null, "e": 10712, "s": 10704, "text": "Strings" }, { "code": null, "e": 10717, "s": 10712, "text": "Trie" } ]
Regression and Classification | Supervised Machine Learning
28 Jun, 2022 What is Regression and Classification in Machine Learning? Data scientists use many different kinds of machine learning algorithms to discover patterns in big data that lead to actionable insights. At a high level, these different algorithms can be classified into two groups based on the way they “learn” about data to make predictions: supervised and unsupervised learning. Supervised Machine Learning: The majority of practical machine learning uses supervised learning. Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output Y = f(X) . The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data.Techniques of Supervised Machine Learning algorithms include linear and logistic regression, multi-class classification, Decision Trees and support vector machines. Supervised learning requires that the data used to train the algorithm is already labelled with correct answers. For example, a classification algorithm will learn to identify animals after being trained on a dataset of images that are properly labelled with the species of the animal and some identifying characteristics. Supervised learning problems can be further grouped into Regression and Classification problems. Both problems have a goal of the construction of a succinct model that can predict the value of the dependent attribute from the attribute variables. The difference between the two tasks is the fact that the dependent attribute is numerical for regression and categorical for classification. Regression A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”. Many different models can be used, the simplest is the linear regression. It tries to fit data with the best hyper-plane which goes through the points. Types of Regression Models: For Examples: Which of the following is a regression task? Predicting age of a person Predicting nationality of a person Predicting whether stock price of a company will increase tomorrow Predicting whether a document is related to sighting of UFOs? Solution : Predicting age of a person (because it is a real value, predicting nationality is categorical, whether stock price will increase is discrete-yes/no answer, predicting whether a document is related to UFO is again discrete- a yes/no answer).Let’s take an example of linear regression. We have a Housing data set and we want to predict the price of the house. Following is the python code for it. Python3 # Python code to illustrate # regression using data setimport matplotlibmatplotlib.use('GTKAgg') import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets, linear_modelimport pandas as pd # Load CSV and columnsdf = pd.read_csv("Housing.csv") Y = df['price']X = df['lotsize'] X=X.values.reshape(len(X),1)Y=Y.values.reshape(len(Y),1) # Split the data into training/testing setsX_train = X[:-250]X_test = X[-250:] # Split the targets into training/testing setsY_train = Y[:-250]Y_test = Y[-250:] # Plot outputsplt.scatter(X_test, Y_test, color='black')plt.title('Test Data')plt.xlabel('Size')plt.ylabel('Price')plt.xticks(())plt.yticks(()) # Create linear regression objectregr = linear_model.LinearRegression() # Train the model using the training setsregr.fit(X_train, Y_train) # Plot outputsplt.plot(X_test, regr.predict(X_test), color='red',linewidth=3)plt.show() The output of the above code will be: Here in this graph, we plot the test data. The red line indicates the best fit line for predicting the price. To make an individual prediction using the linear regression model: print( str(round(regr.predict(5000))) ) Classification A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease”. A classification model attempts to draw some conclusion from observed values. Given one or more inputs a classification model will try to predict the value of one or more outcomes. For example, when filtering emails “spam” or “not spam”, when looking at transaction data, “fraudulent”, or “authorized”. In short Classification either predicts categorical class labels or classifies data (construct a model) based on the training set and the values (class labels) in classifying attributes and uses it in classifying new data. There are a number of classification models. Classification models include logistic regression, decision tree, random forest, gradient-boosted tree, multilayer perceptron, one-vs-rest, and Naive Bayes.For example : Which of the following is/are classification problem(s)? Predicting the gender of a person by his/her handwriting style Predicting house price based on area Predicting whether monsoon will be normal next year Predict the number of copies a music album will be sold next month Solution : Predicting the gender of a person Predicting whether monsoon will be normal next year. The other two are regression. As we discussed classification with some examples. Now there is an example of classification in which we are performing classification on the iris dataset using RandomForestClassifier in python. You can download the dataset from Here Dataset Description Title: Iris Plants Database Attribute Information: 1. sepal length in cm 2. sepal width in cm 3. petal length in cm 4. petal width in cm 5. class: -- Iris Setosa -- Iris Versicolour -- Iris Virginica Missing Attribute Values: None Class Distribution: 33.3% for each of 3 classes Python3 # Python code to illustrate # classification using data set#Importing the required libraryimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.preprocessing import LabelEncoderfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report #Importing the datasetdataset = pd.read_csv( 'https://archive.ics.uci.edu/ml/machine-learning-'+ 'databases/iris/iris.data',sep= ',', header= None)data = dataset.iloc[:, :] #checking for null valuesprint("Sum of NULL values in each column. ")print(data.isnull().sum()) #separating the predicting column from the whole datasetX = data.iloc[:, :-1].valuesy = dataset.iloc[:, 4].values #Encoding the predicting variablelabelencoder_y = LabelEncoder()y = labelencoder_y.fit_transform(y) #Splitting the data into test and train datasetX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0) #Using the random forest classifier for the predictionclassifier=RandomForestClassifier()classifier=classifier.fit(X_train,y_train)predicted=classifier.predict(X_test) #printing the resultsprint ('Confusion Matrix :')print(confusion_matrix(y_test, predicted))print ('Accuracy Score :',accuracy_score(y_test, predicted))print ('Report : ')print (classification_report(y_test, predicted)) Output: Sum of NULL values in each column. 0 0 1 0 2 0 3 0 4 0 Confusion Matrix : [[16 0 0] [ 0 17 1] [ 0 0 11]] Accuracy Score : 97.7 Report : precision recall f1-score support 0 1.00 1.00 1.00 16 1 1.00 0.94 0.97 18 2 0.92 1.00 0.96 11 avg/total 0.98 0.98 0.98 45 References: https://machinelearningmastery.com/logistic-regression-for-machine-learning/ https://machinelearningmastery.com/linear-regression-for-machine-learning/ The_one shubham_singh kowerjani_aakansha saurabh1990aror Machine Learning Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Getting started with Machine Learning Support Vector Machine Algorithm Introduction to Recurrent Neural Network Random Forest Regression in Python ML | Underfitting and Overfitting Running Python script on GPU. Association Rule Clustering in Machine Learning Elbow Method for optimal value of k in KMeans Python | Decision tree implementation
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 111, "s": 52, "text": "What is Regression and Classification in Machine Learning?" }, { "code": null, "e": 428, "s": 111, "text": "Data scientists use many different kinds of machine learning algorithms to discover patterns in big data that lead to actionable insights. At a high level, these different algorithms can be classified into two groups based on the way they “learn” about data to make predictions: supervised and unsupervised learning." }, { "code": null, "e": 1738, "s": 428, "text": "Supervised Machine Learning: The majority of practical machine learning uses supervised learning. Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output Y = f(X) . The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data.Techniques of Supervised Machine Learning algorithms include linear and logistic regression, multi-class classification, Decision Trees and support vector machines. Supervised learning requires that the data used to train the algorithm is already labelled with correct answers. For example, a classification algorithm will learn to identify animals after being trained on a dataset of images that are properly labelled with the species of the animal and some identifying characteristics. Supervised learning problems can be further grouped into Regression and Classification problems. Both problems have a goal of the construction of a succinct model that can predict the value of the dependent attribute from the attribute variables. The difference between the two tasks is the fact that the dependent attribute is numerical for regression and categorical for classification. " }, { "code": null, "e": 1749, "s": 1738, "text": "Regression" }, { "code": null, "e": 2012, "s": 1749, "text": "A regression problem is when the output variable is a real or continuous value, such as “salary” or “weight”. Many different models can be used, the simplest is the linear regression. It tries to fit data with the best hyper-plane which goes through the points. " }, { "code": null, "e": 2042, "s": 2012, "text": "Types of Regression Models: " }, { "code": null, "e": 2103, "s": 2042, "text": "For Examples: Which of the following is a regression task? " }, { "code": null, "e": 2130, "s": 2103, "text": "Predicting age of a person" }, { "code": null, "e": 2165, "s": 2130, "text": "Predicting nationality of a person" }, { "code": null, "e": 2232, "s": 2165, "text": "Predicting whether stock price of a company will increase tomorrow" }, { "code": null, "e": 2294, "s": 2232, "text": "Predicting whether a document is related to sighting of UFOs?" }, { "code": null, "e": 2701, "s": 2294, "text": "Solution : Predicting age of a person (because it is a real value, predicting nationality is categorical, whether stock price will increase is discrete-yes/no answer, predicting whether a document is related to UFO is again discrete- a yes/no answer).Let’s take an example of linear regression. We have a Housing data set and we want to predict the price of the house. Following is the python code for it. " }, { "code": null, "e": 2709, "s": 2701, "text": "Python3" }, { "code": "# Python code to illustrate # regression using data setimport matplotlibmatplotlib.use('GTKAgg') import matplotlib.pyplot as pltimport numpy as npfrom sklearn import datasets, linear_modelimport pandas as pd # Load CSV and columnsdf = pd.read_csv(\"Housing.csv\") Y = df['price']X = df['lotsize'] X=X.values.reshape(len(X),1)Y=Y.values.reshape(len(Y),1) # Split the data into training/testing setsX_train = X[:-250]X_test = X[-250:] # Split the targets into training/testing setsY_train = Y[:-250]Y_test = Y[-250:] # Plot outputsplt.scatter(X_test, Y_test, color='black')plt.title('Test Data')plt.xlabel('Size')plt.ylabel('Price')plt.xticks(())plt.yticks(()) # Create linear regression objectregr = linear_model.LinearRegression() # Train the model using the training setsregr.fit(X_train, Y_train) # Plot outputsplt.plot(X_test, regr.predict(X_test), color='red',linewidth=3)plt.show()", "e": 3617, "s": 2709, "text": null }, { "code": null, "e": 3657, "s": 3617, "text": "The output of the above code will be: " }, { "code": null, "e": 3837, "s": 3657, "text": "Here in this graph, we plot the test data. The red line indicates the best fit line for predicting the price. To make an individual prediction using the linear regression model: " }, { "code": null, "e": 3877, "s": 3837, "text": "print( str(round(regr.predict(5000))) )" }, { "code": null, "e": 3894, "s": 3879, "text": "Classification" }, { "code": null, "e": 4817, "s": 3894, "text": "A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease”. A classification model attempts to draw some conclusion from observed values. Given one or more inputs a classification model will try to predict the value of one or more outcomes. For example, when filtering emails “spam” or “not spam”, when looking at transaction data, “fraudulent”, or “authorized”. In short Classification either predicts categorical class labels or classifies data (construct a model) based on the training set and the values (class labels) in classifying attributes and uses it in classifying new data. There are a number of classification models. Classification models include logistic regression, decision tree, random forest, gradient-boosted tree, multilayer perceptron, one-vs-rest, and Naive Bayes.For example : Which of the following is/are classification problem(s)? " }, { "code": null, "e": 4880, "s": 4817, "text": "Predicting the gender of a person by his/her handwriting style" }, { "code": null, "e": 4917, "s": 4880, "text": "Predicting house price based on area" }, { "code": null, "e": 4969, "s": 4917, "text": "Predicting whether monsoon will be normal next year" }, { "code": null, "e": 5036, "s": 4969, "text": "Predict the number of copies a music album will be sold next month" }, { "code": null, "e": 5420, "s": 5036, "text": "Solution : Predicting the gender of a person Predicting whether monsoon will be normal next year. The other two are regression. As we discussed classification with some examples. Now there is an example of classification in which we are performing classification on the iris dataset using RandomForestClassifier in python. You can download the dataset from Here Dataset Description " }, { "code": null, "e": 5752, "s": 5420, "text": "Title: Iris Plants Database\nAttribute Information:\n 1. sepal length in cm\n 2. sepal width in cm\n 3. petal length in cm\n 4. petal width in cm\n 5. class: \n -- Iris Setosa\n -- Iris Versicolour\n -- Iris Virginica\n Missing Attribute Values: None\nClass Distribution: 33.3% for each of 3 classes" }, { "code": null, "e": 5762, "s": 5754, "text": "Python3" }, { "code": "# Python code to illustrate # classification using data set#Importing the required libraryimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.preprocessing import LabelEncoderfrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report #Importing the datasetdataset = pd.read_csv( 'https://archive.ics.uci.edu/ml/machine-learning-'+ 'databases/iris/iris.data',sep= ',', header= None)data = dataset.iloc[:, :] #checking for null valuesprint(\"Sum of NULL values in each column. \")print(data.isnull().sum()) #separating the predicting column from the whole datasetX = data.iloc[:, :-1].valuesy = dataset.iloc[:, 4].values #Encoding the predicting variablelabelencoder_y = LabelEncoder()y = labelencoder_y.fit_transform(y) #Splitting the data into test and train datasetX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.3, random_state = 0) #Using the random forest classifier for the predictionclassifier=RandomForestClassifier()classifier=classifier.fit(X_train,y_train)predicted=classifier.predict(X_test) #printing the resultsprint ('Confusion Matrix :')print(confusion_matrix(y_test, predicted))print ('Accuracy Score :',accuracy_score(y_test, predicted))print ('Report : ')print (classification_report(y_test, predicted))", "e": 7205, "s": 5762, "text": null }, { "code": null, "e": 7215, "s": 7205, "text": "Output: " }, { "code": null, "e": 7711, "s": 7215, "text": "Sum of NULL values in each column. \n 0 0\n 1 0\n 2 0\n 3 0\n 4 0\n\nConfusion Matrix :\n [[16 0 0]\n [ 0 17 1]\n [ 0 0 11]]\n\nAccuracy Score : 97.7\n\nReport : \n precision recall f1-score support\n 0 1.00 1.00 1.00 16\n 1 1.00 0.94 0.97 18\n 2 0.92 1.00 0.96 11\navg/total 0.98 0.98 0.98 45" }, { "code": null, "e": 7725, "s": 7711, "text": "References: " }, { "code": null, "e": 7802, "s": 7725, "text": "https://machinelearningmastery.com/logistic-regression-for-machine-learning/" }, { "code": null, "e": 7877, "s": 7802, "text": "https://machinelearningmastery.com/linear-regression-for-machine-learning/" }, { "code": null, "e": 7887, "s": 7879, "text": "The_one" }, { "code": null, "e": 7901, "s": 7887, "text": "shubham_singh" }, { "code": null, "e": 7920, "s": 7901, "text": "kowerjani_aakansha" }, { "code": null, "e": 7936, "s": 7920, "text": "saurabh1990aror" }, { "code": null, "e": 7953, "s": 7936, "text": "Machine Learning" }, { "code": null, "e": 7972, "s": 7953, "text": "Technical Scripter" }, { "code": null, "e": 7989, "s": 7972, "text": "Machine Learning" }, { "code": null, "e": 8087, "s": 7989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8125, "s": 8087, "text": "Getting started with Machine Learning" }, { "code": null, "e": 8158, "s": 8125, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 8199, "s": 8158, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 8234, "s": 8199, "text": "Random Forest Regression in Python" }, { "code": null, "e": 8268, "s": 8234, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 8298, "s": 8268, "text": "Running Python script on GPU." }, { "code": null, "e": 8315, "s": 8298, "text": "Association Rule" }, { "code": null, "e": 8346, "s": 8315, "text": "Clustering in Machine Learning" }, { "code": null, "e": 8392, "s": 8346, "text": "Elbow Method for optimal value of k in KMeans" } ]
GATE | GATE-CS-2005 | Question 55
11 Sep, 2017 Consider the languages: L1 = {anbncm | n, m > 0} L2 = {anbmcm | n, m > 0} Which one of the following statements is FALSE?(A) L1 ∩ L2 is a context-free language(B) L1 U L2 is a context-free language(C) L1 and L2 are context-free language(D) L1 ∩ L2 is a context sensitive languageAnswer: (A)Explanation: We can recognize strings of given language using one Stack. These given languages are context free, so also context sensitive.Because CFLs are closed under Union property, so union of given languages will also be Context free.But CFLs are not closed under Intersection property, so Intersection of two CFLs may not be CFL.Given L1 and If L2 are two context free languages, their intersection L1 ∩ L2 is not context free because we cannot identify strings of resultant language with help of one Stack: L1 = { anbncm | n > 0 and m > 0 } and L2 = { ambncn | n > 0 and m > 0 } L3 = L1 ∩ L2 = { anbncn | n > 0 } is not context free. So, option (a) is false. See wikipedia page for closure properties.Quiz of this Question GATE-CS-2005 GATE-GATE-CS-2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 63 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2015 (Set 2) | Question 55
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Sep, 2017" }, { "code": null, "e": 78, "s": 54, "text": "Consider the languages:" }, { "code": null, "e": 130, "s": 78, "text": "L1 = {anbncm | n, m > 0} \nL2 = {anbmcm | n, m > 0} " }, { "code": null, "e": 860, "s": 130, "text": "Which one of the following statements is FALSE?(A) L1 ∩ L2 is a context-free language(B) L1 U L2 is a context-free language(C) L1 and L2 are context-free language(D) L1 ∩ L2 is a context sensitive languageAnswer: (A)Explanation: We can recognize strings of given language using one Stack. These given languages are context free, so also context sensitive.Because CFLs are closed under Union property, so union of given languages will also be Context free.But CFLs are not closed under Intersection property, so Intersection of two CFLs may not be CFL.Given L1 and If L2 are two context free languages, their intersection L1 ∩ L2 is not context free because we cannot identify strings of resultant language with help of one Stack:" }, { "code": null, "e": 932, "s": 860, "text": "L1 = { anbncm | n > 0 and m > 0 } and L2 = { ambncn | n > 0 and m > 0 }" }, { "code": null, "e": 987, "s": 932, "text": "L3 = L1 ∩ L2 = { anbncn | n > 0 } is not context free." }, { "code": null, "e": 1012, "s": 987, "text": "So, option (a) is false." }, { "code": null, "e": 1076, "s": 1012, "text": "See wikipedia page for closure properties.Quiz of this Question" }, { "code": null, "e": 1089, "s": 1076, "text": "GATE-CS-2005" }, { "code": null, "e": 1107, "s": 1089, "text": "GATE-GATE-CS-2005" }, { "code": null, "e": 1112, "s": 1107, "text": "GATE" }, { "code": null, "e": 1210, "s": 1112, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1252, "s": 1210, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1314, "s": 1252, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1356, "s": 1314, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1390, "s": 1356, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1432, "s": 1390, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1474, "s": 1432, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1516, "s": 1474, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 1550, "s": 1516, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1584, "s": 1550, "text": "GATE | GATE CS 2008 | Question 40" } ]
Xv6 Operating System -add a user program
14 Aug, 2020 Xv6 is a re-implementation of the Unix sixth edition in order to use as a learning tool. xv6 was developed by MIT as a teaching operating system for their “6.828” course. A vital fact about xv6 is that it contains all the core Unix concepts and has a similar structure to Unix even though it lacks some functionality that you would expect from a modern operating system. This is a lightweight operating system where the time to compile is very low and it also allow remote debugging. The source code of xv6 can be cloned to your machine as follows :https://github.com/mit-pdos/xv6-public Adding user program to xv6 :After completing xv6 setup on your machine, you could have a look at how to add a new user program to xv6. A user program could be a simple C program. However, just adding a file to the xv6 folder would not be sufficient as we need to make it available to the user at the shell prompt. Step-1: A simple C programFirst of all, let’s create a C program like the following. We save it inside the source code directory of xv6 operating system with the name first.c or whatever the name you prefer. C //A Simple C programinclude "types.h"include "stat.h"include "user.h" //passing command line arguments int main(int argc, char *argv[]){ printf(1, "My first xv6 program learnt at GFG\n"); exit();} // This code is contributed by sambhav228 Step-2: Edit the MakefileThe Makefile needs to be edited to make our program available for the xv6 source code for compilation. gedit Makefile This line of code would open the Makefile in the gedit text editor. Next, the following sections of the Makefile needs to be edited to add your program first.c UPROGS=\ _cat\ _crash\ _echo\ _factor\ _forktest\ _grep\ _hello\ _init\ _kill\ _ln\ _ls\ _mkdir\ _null\ _rm\ _sh\ _share\ _stressfs\ _usertests\ _wc\ _zombie\ _first\ EXTRA=\ mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\ ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\ first.c\ printf.c umalloc.c\ README dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\ .gdbinit.tmpl gdbutil\ Now, our Makefile and our user program is ready to be tested. Enter the following commands to compile the whole system. make clean make Now, start xv6 system on QEMU and when it booted up, run ls command to check whether our program is available for the user. If yes, give the name of that executable program, which is in my case is first to see the program output on the terminal. Output :“My first xv6 program learnt at GFG” shows this output on the QEMU emulator window. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Introduction of Operating System - Set 1 Introduction of Deadlock in Operating System Inter Process Communication (IPC) Paging in Operating System File Allocation Methods Semaphores in Process Synchronization Difference between Process and Thread Deadlock Prevention And Avoidance Introduction of Process Synchronization
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Aug, 2020" }, { "code": null, "e": 538, "s": 54, "text": "Xv6 is a re-implementation of the Unix sixth edition in order to use as a learning tool. xv6 was developed by MIT as a teaching operating system for their “6.828” course. A vital fact about xv6 is that it contains all the core Unix concepts and has a similar structure to Unix even though it lacks some functionality that you would expect from a modern operating system. This is a lightweight operating system where the time to compile is very low and it also allow remote debugging." }, { "code": null, "e": 642, "s": 538, "text": "The source code of xv6 can be cloned to your machine as follows :https://github.com/mit-pdos/xv6-public" }, { "code": null, "e": 956, "s": 642, "text": "Adding user program to xv6 :After completing xv6 setup on your machine, you could have a look at how to add a new user program to xv6. A user program could be a simple C program. However, just adding a file to the xv6 folder would not be sufficient as we need to make it available to the user at the shell prompt." }, { "code": null, "e": 1164, "s": 956, "text": "Step-1: A simple C programFirst of all, let’s create a C program like the following. We save it inside the source code directory of xv6 operating system with the name first.c or whatever the name you prefer." }, { "code": null, "e": 1166, "s": 1164, "text": "C" }, { "code": "//A Simple C programinclude \"types.h\"include \"stat.h\"include \"user.h\" //passing command line arguments int main(int argc, char *argv[]){ printf(1, \"My first xv6 program learnt at GFG\\n\"); exit();} // This code is contributed by sambhav228", "e": 1415, "s": 1166, "text": null }, { "code": null, "e": 1543, "s": 1415, "text": "Step-2: Edit the MakefileThe Makefile needs to be edited to make our program available for the xv6 source code for compilation." }, { "code": null, "e": 1559, "s": 1543, "text": "gedit Makefile " }, { "code": null, "e": 1719, "s": 1559, "text": "This line of code would open the Makefile in the gedit text editor. Next, the following sections of the Makefile needs to be edited to add your program first.c" }, { "code": null, "e": 2134, "s": 1719, "text": "UPROGS=\\\n_cat\\\n_crash\\\n_echo\\\n_factor\\\n_forktest\\\n_grep\\\n_hello\\\n_init\\\n_kill\\\n_ln\\\n_ls\\\n_mkdir\\\n_null\\\n_rm\\\n_sh\\\n_share\\\n_stressfs\\\n_usertests\\\n_wc\\\n_zombie\\\n_first\\\nEXTRA=\\\n\n mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\\\n ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\\\n first.c\\\n printf.c umalloc.c\\\n README dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\\\n .gdbinit.tmpl gdbutil\\ " }, { "code": null, "e": 2254, "s": 2134, "text": "Now, our Makefile and our user program is ready to be tested. Enter the following commands to compile the whole system." }, { "code": null, "e": 2271, "s": 2254, "text": "make clean\nmake " }, { "code": null, "e": 2517, "s": 2271, "text": "Now, start xv6 system on QEMU and when it booted up, run ls command to check whether our program is available for the user. If yes, give the name of that executable program, which is in my case is first to see the program output on the terminal." }, { "code": null, "e": 2609, "s": 2517, "text": "Output :“My first xv6 program learnt at GFG” shows this output on the QEMU emulator window." }, { "code": null, "e": 2627, "s": 2609, "text": "Operating Systems" }, { "code": null, "e": 2645, "s": 2627, "text": "Operating Systems" }, { "code": null, "e": 2743, "s": 2645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2792, "s": 2743, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 2833, "s": 2792, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 2878, "s": 2833, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 2912, "s": 2878, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 2939, "s": 2912, "text": "Paging in Operating System" }, { "code": null, "e": 2963, "s": 2939, "text": "File Allocation Methods" }, { "code": null, "e": 3001, "s": 2963, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 3039, "s": 3001, "text": "Difference between Process and Thread" }, { "code": null, "e": 3073, "s": 3039, "text": "Deadlock Prevention And Avoidance" } ]
How to Remove Salt and Pepper Noise from Image Using MATLAB?
22 Nov, 2021 Impulse noise is a unique form of noise that can have many different origins. Images are frequently corrupted through impulse noise due to transmission errors, defective memory places, or timing mistakes in analog-to-digital conversion. Salt-and-pepper noise is one form of impulse noise that can corrupt the image, in which the noisy pixels can take only the most and minimal values withinside the dynamic range. Since linear filtering strategies are not powerful in removing impulse noise, non-linear filtering strategies are widely used in the recovery method. The standard median filter (SMF) is one of the most popular non-linear filters used to remove salt-and-pepper noise due to its good denoising power and computational efficiency. However, the major drawback of the SMF is that the filter is effective only for low noise densities, and additionally, exhibits blurring if the window size is large and leads to insufficient noise suppression if the window size is small. When the noise level is over 50%, the edge details of the original image will not be preserved by the median filter. Nevertheless, it is important that during the process the edge details have to be preserved without losing the high-frequency components of the image edges. The ideal approach is to apply the filtering technique only to noisy pixels, without changing the uncorrupted pixel values. Non-linear filters such as Adaptive Median Filter (AMF), decision–based or switching median filters can be used for discriminating corrupted and uncorrupted pixels, and then apply the filtering technique. Noisy pixels will be replaced by the median value and uncorrupted pixels will be left unchanged. AMF performs well at low noise densities since the corrupted pixels which are replaced by the median values are very few. At higher noise densities, window size has to be increased to get better noise removal which will lead to less correlation between corrupted pixel values and replaced median pixel values. As the name suggests, the color of pixels either becomes black or white completely. White is called salt and black is called pepper, thus the name comes for it. This is a result of the random creation of pure white or black (high/low) pixels into the image. This is much less common in cutting-edge image sensors, even though can maximum usually be visible withinside the form of camera sensor faults (hot pixels which might be usually at most depth, or dead pixels which can be usually black). This kind of noise is also called impulse noise. This noise is removed effectively by the median filter. White or black pixels behave as outliers. A neighborhood window of size [m n] is selected and slides over the image. The pixels of images hovered by the window are sorted in increasing order then white and dark pixels go on the right and left side of the sorted list respectively thus does not affect the selection of output pixel. We select the median pixel from the sorted list thus salt and pepper get reduced 100% effectively though some blurriness occurs which is fine. imread( ) inbuilt function is used to read the image. imtool( ) inbuilt function is used to display the image. size( ) inbuilt function is used to get size of the image. rgb2gray( ) inbuilt function is used to convert RGB into grayscale image. imnoise( ) inbuilt function is used to add noise to the image. medfilt2( ) inbuilt function is used to perform median filter on noisy image. pause( ) inbuilt function is used to stop execution for specified seconds. Matlab % MATLAB Code for removal of Salt and % Pepper noise from image.k=imread("gfglogo.png");RemoveSaltAndPepperNoise(k); function RemoveSaltAndPepperNoise(k)% Convert to grayscale if not.[M,N,D]=size(k);if(D==3) k=rgb2gray(k);end % Add noise to image.kn=imnoise(k,'salt & pepper',0.03); % Display original and noisy image.imtool(k,[]);imtool(kn,[]); % Denoising.dn=medfilt2(kn,[5,5]); % Display denoised image.imtool(dn,[]); % Pause and close img windows.pause(10);imtool close all;end Output: Figure 1: Original image Figure 2: Noised image Figure 3: Denoised image Figure 4: Original image Figure 5: Noised image Figure 6: Denoised image Code Explanation: [M,N,D]=size(k); This line gets the size of input image. kn=imnoise(k,’salt & pepper’,0.03); This line adds 3% noise in the image. dn=medfilt2(kn,[5,5]); This line applies the median filter on noised image. k=imread(“cameraman.png”); This line reads the input image. RemoveSaltAndPepperNoise(k); This line calls the user-defined function by passing input image to it. A median filter is the best for the removal of Salt and Pepper noise, though it introduces some blurriness in the image in that area where the non-homogenous region is captured below the sliding neighborhood window. In that case, the median of the sorted list does not exactly come out of the actual underlying pixel value. This method reduces the noise by 100%. MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Double Integral in MATLAB Classes and Object in MATLAB How to remove space in a string in MATLAB? How to Normalize a Histogram in MATLAB? Forward and Inverse Fourier Transform of an Image in MATLAB
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 771, "s": 28, "text": "Impulse noise is a unique form of noise that can have many different origins. Images are frequently corrupted through impulse noise due to transmission errors, defective memory places, or timing mistakes in analog-to-digital conversion. Salt-and-pepper noise is one form of impulse noise that can corrupt the image, in which the noisy pixels can take only the most and minimal values withinside the dynamic range. Since linear filtering strategies are not powerful in removing impulse noise, non-linear filtering strategies are widely used in the recovery method. The standard median filter (SMF) is one of the most popular non-linear filters used to remove salt-and-pepper noise due to its good denoising power and computational efficiency. " }, { "code": null, "e": 1283, "s": 771, "text": "However, the major drawback of the SMF is that the filter is effective only for low noise densities, and additionally, exhibits blurring if the window size is large and leads to insufficient noise suppression if the window size is small. When the noise level is over 50%, the edge details of the original image will not be preserved by the median filter. Nevertheless, it is important that during the process the edge details have to be preserved without losing the high-frequency components of the image edges." }, { "code": null, "e": 2019, "s": 1283, "text": "The ideal approach is to apply the filtering technique only to noisy pixels, without changing the uncorrupted pixel values. Non-linear filters such as Adaptive Median Filter (AMF), decision–based or switching median filters can be used for discriminating corrupted and uncorrupted pixels, and then apply the filtering technique. Noisy pixels will be replaced by the median value and uncorrupted pixels will be left unchanged. AMF performs well at low noise densities since the corrupted pixels which are replaced by the median values are very few. At higher noise densities, window size has to be increased to get better noise removal which will lead to less correlation between corrupted pixel values and replaced median pixel values." }, { "code": null, "e": 2180, "s": 2019, "text": "As the name suggests, the color of pixels either becomes black or white completely. White is called salt and black is called pepper, thus the name comes for it." }, { "code": null, "e": 2563, "s": 2180, "text": "This is a result of the random creation of pure white or black (high/low) pixels into the image. This is much less common in cutting-edge image sensors, even though can maximum usually be visible withinside the form of camera sensor faults (hot pixels which might be usually at most depth, or dead pixels which can be usually black). This kind of noise is also called impulse noise." }, { "code": null, "e": 3094, "s": 2563, "text": "This noise is removed effectively by the median filter. White or black pixels behave as outliers. A neighborhood window of size [m n] is selected and slides over the image. The pixels of images hovered by the window are sorted in increasing order then white and dark pixels go on the right and left side of the sorted list respectively thus does not affect the selection of output pixel. We select the median pixel from the sorted list thus salt and pepper get reduced 100% effectively though some blurriness occurs which is fine." }, { "code": null, "e": 3148, "s": 3094, "text": "imread( ) inbuilt function is used to read the image." }, { "code": null, "e": 3205, "s": 3148, "text": "imtool( ) inbuilt function is used to display the image." }, { "code": null, "e": 3264, "s": 3205, "text": "size( ) inbuilt function is used to get size of the image." }, { "code": null, "e": 3338, "s": 3264, "text": "rgb2gray( ) inbuilt function is used to convert RGB into grayscale image." }, { "code": null, "e": 3401, "s": 3338, "text": "imnoise( ) inbuilt function is used to add noise to the image." }, { "code": null, "e": 3479, "s": 3401, "text": "medfilt2( ) inbuilt function is used to perform median filter on noisy image." }, { "code": null, "e": 3554, "s": 3479, "text": "pause( ) inbuilt function is used to stop execution for specified seconds." }, { "code": null, "e": 3561, "s": 3554, "text": "Matlab" }, { "code": "% MATLAB Code for removal of Salt and % Pepper noise from image.k=imread(\"gfglogo.png\");RemoveSaltAndPepperNoise(k); function RemoveSaltAndPepperNoise(k)% Convert to grayscale if not.[M,N,D]=size(k);if(D==3) k=rgb2gray(k);end % Add noise to image.kn=imnoise(k,'salt & pepper',0.03); % Display original and noisy image.imtool(k,[]);imtool(kn,[]); % Denoising.dn=medfilt2(kn,[5,5]); % Display denoised image.imtool(dn,[]); % Pause and close img windows.pause(10);imtool close all;end", "e": 4052, "s": 3561, "text": null }, { "code": null, "e": 4061, "s": 4052, "text": "Output: " }, { "code": null, "e": 4086, "s": 4061, "text": "Figure 1: Original image" }, { "code": null, "e": 4109, "s": 4086, "text": "Figure 2: Noised image" }, { "code": null, "e": 4134, "s": 4109, "text": "Figure 3: Denoised image" }, { "code": null, "e": 4159, "s": 4134, "text": "Figure 4: Original image" }, { "code": null, "e": 4182, "s": 4159, "text": "Figure 5: Noised image" }, { "code": null, "e": 4207, "s": 4182, "text": "Figure 6: Denoised image" }, { "code": null, "e": 4225, "s": 4207, "text": "Code Explanation:" }, { "code": null, "e": 4282, "s": 4225, "text": "[M,N,D]=size(k); This line gets the size of input image." }, { "code": null, "e": 4356, "s": 4282, "text": "kn=imnoise(k,’salt & pepper’,0.03); This line adds 3% noise in the image." }, { "code": null, "e": 4432, "s": 4356, "text": "dn=medfilt2(kn,[5,5]); This line applies the median filter on noised image." }, { "code": null, "e": 4492, "s": 4432, "text": "k=imread(“cameraman.png”); This line reads the input image." }, { "code": null, "e": 4593, "s": 4492, "text": "RemoveSaltAndPepperNoise(k); This line calls the user-defined function by passing input image to it." }, { "code": null, "e": 4956, "s": 4593, "text": "A median filter is the best for the removal of Salt and Pepper noise, though it introduces some blurriness in the image in that area where the non-homogenous region is captured below the sliding neighborhood window. In that case, the median of the sorted list does not exactly come out of the actual underlying pixel value. This method reduces the noise by 100%." }, { "code": null, "e": 4980, "s": 4956, "text": "MATLAB image-processing" }, { "code": null, "e": 4987, "s": 4980, "text": "MATLAB" }, { "code": null, "e": 5085, "s": 4987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5164, "s": 5085, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 5229, "s": 5164, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 5294, "s": 5229, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 5327, "s": 5294, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 5401, "s": 5327, "text": "How to detect duplicate values and its indices within an array in MATLAB?" }, { "code": null, "e": 5427, "s": 5401, "text": "Double Integral in MATLAB" }, { "code": null, "e": 5456, "s": 5427, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 5499, "s": 5456, "text": "How to remove space in a string in MATLAB?" }, { "code": null, "e": 5539, "s": 5499, "text": "How to Normalize a Histogram in MATLAB?" } ]
Scala Constructors
11 Aug, 2021 Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Scala supports two types of constructors: When our Scala program contains only one constructor, then that constructor is known as a primary constructor. The primary constructor and the class share the same body, means we need not to create a constructor explicitly. Syntax: class class_name(Parameter_list){ // Statements... } Important points: In the above syntax, the primary constructor and the class share the same body so, anything defined in the body of the class except method declaration is the part of the primary constructor. Example: Scala // Scala program to illustrate the// concept of primary constructor // Creating a primary constructor// with parameter-listclass GFG(Aname: String, Cname: String, Particle: Int){ def display() { println("Author name: " + Aname); println("Chapter name: " + Cname); println("Total published articles:" + Particle); }} object Main{ def main(args: Array[String]) { // Creating and initializing // object of GFG class var obj = new GFG("Ankita", "Constructors", 145); obj.display(); }} Output: Author name: Ankita Chapter name: Constructors Total published articles:145 The primary constructor may contain zero or more parameters. If we do not create a constructor in our Scala program, then the compiler will automatically create a primary constructor when we create an object of your class, this constructor is known as a default primary constructor. It does not contain any parameters. Example: Scala // Scala program to illustrate the// concept of default primary constructor class GFG{ def display() { println("Welcome to Geeksforgeeks"); }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.display(); }} Output: Welcome to Geeksforgeeks If the parameters in the constructor parameter-list are declared using var, then the value of the fields may change. And Scala also generates getter and setter methods for that field. If the parameters in the constructor parameter-list are declared using val, then the value of the fields cannot change. And Scala also generates a getter method for that field. If the parameters in the constructor parameter-list are declared without using val or var, then the visibility of the field is very restricted. And Scala does not generate any getter and setter methods for that field. If the parameters in the constructor parameter-list are declared using private val or var, then it prevents from generating any getter and setter methods for that field. So, these fields can be accessed by the members of that class. In Scala, only a primary constructor is allowed to invoke a superclass constructor. In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list. Syntax: // private constructor with two argument class GFG private(name: String, class:Int){ // code.. } // private constructor without argument class GFG private{ // code... } In Scala, we are allowed to give default values in the constructor declaration. Example: Scala // Scala program to illustrate the// concept of primary constructor // Creating primary constructor with default valuesclass GFG(val Aname: String = "Ankita", val Cname: String = "Constructors"){ def display() { println("Author name: " + Aname); println("Chapter name: " + Cname); }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.display(); }} Output: Author name: Ankita Chapter name: Constructors In a Scala program, the constructors other than the primary constructor are known as auxiliary constructors. we are allowed to create any number of auxiliary constructors in our program, but a program contains only one primary constructor. Syntax: def this(......) Important points: In a single program, we are allowed to create multiple auxiliary constructors, but they have different signatures or parameter-lists. Every auxiliary constructor must call one of the previously defined constructors. The invoke constructor may be a primary or another auxiliary constructor that comes textually before the calling constructor. The first statement of the auxiliary constructor must contain the constructor call using this. Example: Scala // Scala program to illustrate the// concept of Auxiliary Constructor // Primary constructorclass GFG( Aname: String, Cname: String){ var no: Int = 0;; def display() { println("Author name: " + Aname); println("Chapter name: " + Cname); println("Total number of articles: " + no); } // Auxiliary Constructor def this(Aname: String, Cname: String, no:Int) { // Invoking primary constructor this(Aname, Cname) this.no=no }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG("Anya", "Constructor", 34); obj.display(); }} Output: Author name: Anya Chapter name: Constructor Total number of articles: 34 simmytarika5 gabaa406 Scala Scala-Constructor Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Aug, 2021" }, { "code": null, "e": 293, "s": 54, "text": "Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Scala supports two types of constructors: " }, { "code": null, "e": 518, "s": 293, "text": "When our Scala program contains only one constructor, then that constructor is known as a primary constructor. The primary constructor and the class share the same body, means we need not to create a constructor explicitly. " }, { "code": null, "e": 528, "s": 518, "text": "Syntax: " }, { "code": null, "e": 581, "s": 528, "text": "class class_name(Parameter_list){\n// Statements...\n}" }, { "code": null, "e": 601, "s": 581, "text": "Important points: " }, { "code": null, "e": 802, "s": 601, "text": "In the above syntax, the primary constructor and the class share the same body so, anything defined in the body of the class except method declaration is the part of the primary constructor. Example: " }, { "code": null, "e": 808, "s": 802, "text": "Scala" }, { "code": "// Scala program to illustrate the// concept of primary constructor // Creating a primary constructor// with parameter-listclass GFG(Aname: String, Cname: String, Particle: Int){ def display() { println(\"Author name: \" + Aname); println(\"Chapter name: \" + Cname); println(\"Total published articles:\" + Particle); }} object Main{ def main(args: Array[String]) { // Creating and initializing // object of GFG class var obj = new GFG(\"Ankita\", \"Constructors\", 145); obj.display(); }}", "e": 1365, "s": 808, "text": null }, { "code": null, "e": 1374, "s": 1365, "text": "Output: " }, { "code": null, "e": 1450, "s": 1374, "text": "Author name: Ankita\nChapter name: Constructors\nTotal published articles:145" }, { "code": null, "e": 1511, "s": 1450, "text": "The primary constructor may contain zero or more parameters." }, { "code": null, "e": 1779, "s": 1511, "text": "If we do not create a constructor in our Scala program, then the compiler will automatically create a primary constructor when we create an object of your class, this constructor is known as a default primary constructor. It does not contain any parameters. Example: " }, { "code": null, "e": 1785, "s": 1779, "text": "Scala" }, { "code": "// Scala program to illustrate the// concept of default primary constructor class GFG{ def display() { println(\"Welcome to Geeksforgeeks\"); }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.display(); }}", "e": 2099, "s": 1785, "text": null }, { "code": null, "e": 2108, "s": 2099, "text": "Output: " }, { "code": null, "e": 2133, "s": 2108, "text": "Welcome to Geeksforgeeks" }, { "code": null, "e": 2319, "s": 2133, "text": "If the parameters in the constructor parameter-list are declared using var, then the value of the fields may change. And Scala also generates getter and setter methods for that field. " }, { "code": null, "e": 2497, "s": 2319, "text": "If the parameters in the constructor parameter-list are declared using val, then the value of the fields cannot change. And Scala also generates a getter method for that field. " }, { "code": null, "e": 2716, "s": 2497, "text": "If the parameters in the constructor parameter-list are declared without using val or var, then the visibility of the field is very restricted. And Scala does not generate any getter and setter methods for that field. " }, { "code": null, "e": 2951, "s": 2716, "text": "If the parameters in the constructor parameter-list are declared using private val or var, then it prevents from generating any getter and setter methods for that field. So, these fields can be accessed by the members of that class. " }, { "code": null, "e": 3035, "s": 2951, "text": "In Scala, only a primary constructor is allowed to invoke a superclass constructor." }, { "code": null, "e": 3196, "s": 3035, "text": "In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list. Syntax: " }, { "code": null, "e": 3366, "s": 3196, "text": "// private constructor with two argument\nclass GFG private(name: String, class:Int){\n// code..\n}\n\n// private constructor without argument\nclass GFG private{\n// code...\n}" }, { "code": null, "e": 3456, "s": 3366, "text": "In Scala, we are allowed to give default values in the constructor declaration. Example: " }, { "code": null, "e": 3462, "s": 3456, "text": "Scala" }, { "code": "// Scala program to illustrate the// concept of primary constructor // Creating primary constructor with default valuesclass GFG(val Aname: String = \"Ankita\", val Cname: String = \"Constructors\"){ def display() { println(\"Author name: \" + Aname); println(\"Chapter name: \" + Cname); }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.display(); }}", "e": 3933, "s": 3462, "text": null }, { "code": null, "e": 3942, "s": 3933, "text": "Output: " }, { "code": null, "e": 3990, "s": 3942, "text": "Author name: Ankita\nChapter name: Constructors " }, { "code": null, "e": 4231, "s": 3990, "text": "In a Scala program, the constructors other than the primary constructor are known as auxiliary constructors. we are allowed to create any number of auxiliary constructors in our program, but a program contains only one primary constructor. " }, { "code": null, "e": 4241, "s": 4231, "text": "Syntax: " }, { "code": null, "e": 4258, "s": 4241, "text": "def this(......)" }, { "code": null, "e": 4278, "s": 4258, "text": "Important points: " }, { "code": null, "e": 4412, "s": 4278, "text": "In a single program, we are allowed to create multiple auxiliary constructors, but they have different signatures or parameter-lists." }, { "code": null, "e": 4494, "s": 4412, "text": "Every auxiliary constructor must call one of the previously defined constructors." }, { "code": null, "e": 4620, "s": 4494, "text": "The invoke constructor may be a primary or another auxiliary constructor that comes textually before the calling constructor." }, { "code": null, "e": 4715, "s": 4620, "text": "The first statement of the auxiliary constructor must contain the constructor call using this." }, { "code": null, "e": 4726, "s": 4715, "text": "Example: " }, { "code": null, "e": 4732, "s": 4726, "text": "Scala" }, { "code": "// Scala program to illustrate the// concept of Auxiliary Constructor // Primary constructorclass GFG( Aname: String, Cname: String){ var no: Int = 0;; def display() { println(\"Author name: \" + Aname); println(\"Chapter name: \" + Cname); println(\"Total number of articles: \" + no); } // Auxiliary Constructor def this(Aname: String, Cname: String, no:Int) { // Invoking primary constructor this(Aname, Cname) this.no=no }} object Main{ def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(\"Anya\", \"Constructor\", 34); obj.display(); }}", "e": 5423, "s": 4732, "text": null }, { "code": null, "e": 5432, "s": 5423, "text": "Output: " }, { "code": null, "e": 5505, "s": 5432, "text": "Author name: Anya\nChapter name: Constructor\nTotal number of articles: 34" }, { "code": null, "e": 5520, "s": 5507, "text": "simmytarika5" }, { "code": null, "e": 5529, "s": 5520, "text": "gabaa406" }, { "code": null, "e": 5535, "s": 5529, "text": "Scala" }, { "code": null, "e": 5553, "s": 5535, "text": "Scala-Constructor" }, { "code": null, "e": 5559, "s": 5553, "text": "Scala" } ]
Check duplicates in a stream of strings - GeeksforGeeks
25 May, 2021 Given an array arr[] of strings containing the names of employees in a company. Assuming that the names are being entered in a system one after another, the task is to check whether the current name is entered for the first time or not.Examples: Input: arr[] = {“geeks”, “for”, “geeks”} Output: No No YesInput: arr[] = {“abc”, “aaa”, “cba”} Output: No No No Approach: Create an unordered_set to store the names of the employees and start traversing the array, if the current name is already present in the set then print Yes else print No and insert it into the set.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to insert the names// and check whether they appear// for the first timevoid insertNames(string arr[], int n){ // To store the names // of the employees unordered_set<string> set; for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (set.find(arr[i]) == set.end()) { cout << "No\n"; set.insert(arr[i]); } else { cout << "Yes\n"; } }} // Driver codeint main(){ string arr[] = { "geeks", "for", "geeks" }; int n = sizeof(arr) / sizeof(string); insertNames(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to insert the names// and check whether they appear// for the first timestatic void insertNames(String arr[], int n){ // To store the names // of the employees HashSet<String> set = new HashSet<String>(); for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.contains(arr[i])) { System.out.print("No\n"); set.add(arr[i]); } else { System.out.print("Yes\n"); } }} // Driver codepublic static void main(String[] args){ String arr[] = { "geeks", "for", "geeks" }; int n = arr.length; insertNames(arr, n);}} // This code contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to insert the names# and check whether they appear# for the first timedef insertNames(arr, n) : # To store the names # of the employees string = set(); for i in range(n) : # If current name is appearing # for the first time if arr[i] not in string : print("No"); string.add(arr[i]); else : print("Yes"); # Driver codeif __name__ == "__main__" : arr = [ "geeks", "for", "geeks" ]; n = len(arr); insertNames(arr, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to insert the names// and check whether they appear// for the first timestatic void insertNames(String []arr, int n){ // To store the names // of the employees HashSet<String> set = new HashSet<String>(); for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.Contains(arr[i])) { Console.Write("No\n"); set.Add(arr[i]); } else { Console.Write("Yes\n"); } }} // Driver codepublic static void Main(String[] args){ String []arr = { "geeks", "for", "geeks" }; int n = arr.Length; insertNames(arr, n);}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to insert the names// and check whether they appear// for the first timefunction insertNames(arr, n){ // To store the names // of the employees let set = new Set(); for (let i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.has(arr[i])) { document.write("No" + "<br/>"); set.add(arr[i]); } else { document.write("Yes" + "<br/>"); } }} // Driver code let arr = [ "geeks", "for", "geeks" ]; let n = arr.length; insertNames(arr, n); // This code is contributed by susmitakundugoaldanga.</script> No No Yes ankthon princiraj1992 Rajput-Ji susmitakundugoaldanga Hash Searching Strings Searching Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rearrange an array such that arr[i] = i Quadratic Probing in Hashing Hashing in Java Non-Repeating Element What are Hash Functions and How to choose a good Hash Function? Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25156, "s": 25128, "text": "\n25 May, 2021" }, { "code": null, "e": 25404, "s": 25156, "text": "Given an array arr[] of strings containing the names of employees in a company. Assuming that the names are being entered in a system one after another, the task is to check whether the current name is entered for the first time or not.Examples: " }, { "code": null, "e": 25518, "s": 25404, "text": "Input: arr[] = {“geeks”, “for”, “geeks”} Output: No No YesInput: arr[] = {“abc”, “aaa”, “cba”} Output: No No No " }, { "code": null, "e": 25781, "s": 25520, "text": "Approach: Create an unordered_set to store the names of the employees and start traversing the array, if the current name is already present in the set then print Yes else print No and insert it into the set.Below is the implementation of the above approach: " }, { "code": null, "e": 25785, "s": 25781, "text": "C++" }, { "code": null, "e": 25790, "s": 25785, "text": "Java" }, { "code": null, "e": 25798, "s": 25790, "text": "Python3" }, { "code": null, "e": 25801, "s": 25798, "text": "C#" }, { "code": null, "e": 25812, "s": 25801, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to insert the names// and check whether they appear// for the first timevoid insertNames(string arr[], int n){ // To store the names // of the employees unordered_set<string> set; for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (set.find(arr[i]) == set.end()) { cout << \"No\\n\"; set.insert(arr[i]); } else { cout << \"Yes\\n\"; } }} // Driver codeint main(){ string arr[] = { \"geeks\", \"for\", \"geeks\" }; int n = sizeof(arr) / sizeof(string); insertNames(arr, n); return 0;}", "e": 26520, "s": 25812, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to insert the names// and check whether they appear// for the first timestatic void insertNames(String arr[], int n){ // To store the names // of the employees HashSet<String> set = new HashSet<String>(); for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.contains(arr[i])) { System.out.print(\"No\\n\"); set.add(arr[i]); } else { System.out.print(\"Yes\\n\"); } }} // Driver codepublic static void main(String[] args){ String arr[] = { \"geeks\", \"for\", \"geeks\" }; int n = arr.length; insertNames(arr, n);}} // This code contributed by PrinciRaj1992", "e": 27305, "s": 26520, "text": null }, { "code": "# Python3 implementation of the approach # Function to insert the names# and check whether they appear# for the first timedef insertNames(arr, n) : # To store the names # of the employees string = set(); for i in range(n) : # If current name is appearing # for the first time if arr[i] not in string : print(\"No\"); string.add(arr[i]); else : print(\"Yes\"); # Driver codeif __name__ == \"__main__\" : arr = [ \"geeks\", \"for\", \"geeks\" ]; n = len(arr); insertNames(arr, n); # This code is contributed by AnkitRai01", "e": 27913, "s": 27305, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to insert the names// and check whether they appear// for the first timestatic void insertNames(String []arr, int n){ // To store the names // of the employees HashSet<String> set = new HashSet<String>(); for (int i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.Contains(arr[i])) { Console.Write(\"No\\n\"); set.Add(arr[i]); } else { Console.Write(\"Yes\\n\"); } }} // Driver codepublic static void Main(String[] args){ String []arr = { \"geeks\", \"for\", \"geeks\" }; int n = arr.Length; insertNames(arr, n);}} // This code is contributed by Rajput-Ji", "e": 28716, "s": 27913, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to insert the names// and check whether they appear// for the first timefunction insertNames(arr, n){ // To store the names // of the employees let set = new Set(); for (let i = 0; i < n; i++) { // If current name is appearing // for the first time if (!set.has(arr[i])) { document.write(\"No\" + \"<br/>\"); set.add(arr[i]); } else { document.write(\"Yes\" + \"<br/>\"); } }} // Driver code let arr = [ \"geeks\", \"for\", \"geeks\" ]; let n = arr.length; insertNames(arr, n); // This code is contributed by susmitakundugoaldanga.</script>", "e": 29458, "s": 28716, "text": null }, { "code": null, "e": 29468, "s": 29458, "text": "No\nNo\nYes" }, { "code": null, "e": 29478, "s": 29470, "text": "ankthon" }, { "code": null, "e": 29492, "s": 29478, "text": "princiraj1992" }, { "code": null, "e": 29502, "s": 29492, "text": "Rajput-Ji" }, { "code": null, "e": 29524, "s": 29502, "text": "susmitakundugoaldanga" }, { "code": null, "e": 29529, "s": 29524, "text": "Hash" }, { "code": null, "e": 29539, "s": 29529, "text": "Searching" }, { "code": null, "e": 29547, "s": 29539, "text": "Strings" }, { "code": null, "e": 29557, "s": 29547, "text": "Searching" }, { "code": null, "e": 29562, "s": 29557, "text": "Hash" }, { "code": null, "e": 29570, "s": 29562, "text": "Strings" }, { "code": null, "e": 29668, "s": 29570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29708, "s": 29668, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 29737, "s": 29708, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 29753, "s": 29737, "text": "Hashing in Java" }, { "code": null, "e": 29775, "s": 29753, "text": "Non-Repeating Element" }, { "code": null, "e": 29839, "s": 29775, "text": "What are Hash Functions and How to choose a good Hash Function?" }, { "code": null, "e": 29853, "s": 29839, "text": "Binary Search" }, { "code": null, "e": 29921, "s": 29853, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 29935, "s": 29921, "text": "Linear Search" }, { "code": null, "e": 29959, "s": 29935, "text": "Find the Missing Number" } ]
Pedestrian Detection using OpenCV-Python - GeeksforGeeks
26 Mar, 2020 OpenCV is an open-source library, which is aimed at real-time computer vision. This library is developed by Intel and is cross-platform – it can support Python, C++, Java, etc. Computer Vision is a cutting edge field of Computer Science that aims to enable computers to understand what is being seen in an image. OpenCV is one of the most widely used libraries for Computer Vision tasks like face recognition, motion detection, object detection, etc. In this tutorial, we are going to build a basic Pedestrian Detector for images and videos using OpenCV. Pedestrian detection is a very important area of research because it can enhance the functionality of a pedestrian protection system in Self Driving Cars. We can extract features like head, two arms, two legs, etc, from an image of a human body and pass them to train a machine learning model. After training, the model can be used to detect and track humans in images and video streams. However, OpenCV has a built-in method to detect pedestrians. It has a pre-trained HOG(Histogram of Oriented Gradients) + Linear SVM model to detect pedestrians in images and video streams. Histogram of Oriented Gradients This algorithm checks directly surrounding pixels of every single pixel. The goal is to check how darker is the current pixel compared to the surrounding pixels. The algorithm draws and arrows showing the direction of the image getting darker. It repeats the process for each and every pixel in the image. At last, every pixel would be replaced by an arrow, these arrows are called Gradients. These gradients show the flow of light from light to dark. By using these gradients algorithms perform further analysis. To learn more about HOG, read Navneet Dalal and Bill Triggs research paper on HOG for Human Detection.. opencv-python 3.4.2 imutils 0.5.3 To install the above modules type the below command in the terminal. pip install moudle_name Example 1: Lets make the program to detect pedestrians in an Image: Image Used: import cv2import imutils # Initializing the HOG person# detectorhog = cv2.HOGDescriptor()hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # Reading the Imageimage = cv2.imread('img.png') # Resizing the Imageimage = imutils.resize(image, width=min(400, image.shape[1])) # Detecting all the regions in the # Image that has a pedestrians inside it(regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(4, 4), scale=1.05) # Drawing the regions in the Imagefor (x, y, w, h) in regions: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # Showing the output Imagecv2.imshow("Image", image)cv2.waitKey(0) cv2.destroyAllWindows() Output: Example 2: Lets make the program to detect pedestrians in a video: import cv2import imutils # Initializing the HOG person# detectorhog = cv2.HOGDescriptor()hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) cap = cv2.VideoCapture('vid.mp4') while cap.isOpened(): # Reading the video stream ret, image = cap.read() if ret: image = imutils.resize(image, width=min(400, image.shape[1])) # Detecting all the regions # in the Image that has a # pedestrians inside it (regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(4, 4), scale=1.05) # Drawing the regions in the # Image for (x, y, w, h) in regions: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # Showing the output Image cv2.imshow("Image", image) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break cap.release()cv2.destroyAllWindows() Output: Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24243, "s": 24215, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24694, "s": 24243, "text": "OpenCV is an open-source library, which is aimed at real-time computer vision. This library is developed by Intel and is cross-platform – it can support Python, C++, Java, etc. Computer Vision is a cutting edge field of Computer Science that aims to enable computers to understand what is being seen in an image. OpenCV is one of the most widely used libraries for Computer Vision tasks like face recognition, motion detection, object detection, etc." }, { "code": null, "e": 24953, "s": 24694, "text": "In this tutorial, we are going to build a basic Pedestrian Detector for images and videos using OpenCV. Pedestrian detection is a very important area of research because it can enhance the functionality of a pedestrian protection system in Self Driving Cars." }, { "code": null, "e": 25375, "s": 24953, "text": "We can extract features like head, two arms, two legs, etc, from an image of a human body and pass them to train a machine learning model. After training, the model can be used to detect and track humans in images and video streams. However, OpenCV has a built-in method to detect pedestrians. It has a pre-trained HOG(Histogram of Oriented Gradients) + Linear SVM model to detect pedestrians in images and video streams." }, { "code": null, "e": 25407, "s": 25375, "text": "Histogram of Oriented Gradients" }, { "code": null, "e": 26025, "s": 25407, "text": "This algorithm checks directly surrounding pixels of every single pixel. The goal is to check how darker is the current pixel compared to the surrounding pixels. The algorithm draws and arrows showing the direction of the image getting darker. It repeats the process for each and every pixel in the image. At last, every pixel would be replaced by an arrow, these arrows are called Gradients. These gradients show the flow of light from light to dark. By using these gradients algorithms perform further analysis. To learn more about HOG, read Navneet Dalal and Bill Triggs research paper on HOG for Human Detection.." }, { "code": null, "e": 26060, "s": 26025, "text": "opencv-python 3.4.2\nimutils 0.5.3\n" }, { "code": null, "e": 26129, "s": 26060, "text": "To install the above modules type the below command in the terminal." }, { "code": null, "e": 26153, "s": 26129, "text": "pip install moudle_name" }, { "code": null, "e": 26164, "s": 26153, "text": "Example 1:" }, { "code": null, "e": 26221, "s": 26164, "text": "Lets make the program to detect pedestrians in an Image:" }, { "code": null, "e": 26233, "s": 26221, "text": "Image Used:" }, { "code": "import cv2import imutils # Initializing the HOG person# detectorhog = cv2.HOGDescriptor()hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # Reading the Imageimage = cv2.imread('img.png') # Resizing the Imageimage = imutils.resize(image, width=min(400, image.shape[1])) # Detecting all the regions in the # Image that has a pedestrians inside it(regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(4, 4), scale=1.05) # Drawing the regions in the Imagefor (x, y, w, h) in regions: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # Showing the output Imagecv2.imshow(\"Image\", image)cv2.waitKey(0) cv2.destroyAllWindows()", "e": 27077, "s": 26233, "text": null }, { "code": null, "e": 27085, "s": 27077, "text": "Output:" }, { "code": null, "e": 27152, "s": 27085, "text": "Example 2: Lets make the program to detect pedestrians in a video:" }, { "code": "import cv2import imutils # Initializing the HOG person# detectorhog = cv2.HOGDescriptor()hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) cap = cv2.VideoCapture('vid.mp4') while cap.isOpened(): # Reading the video stream ret, image = cap.read() if ret: image = imutils.resize(image, width=min(400, image.shape[1])) # Detecting all the regions # in the Image that has a # pedestrians inside it (regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(4, 4), scale=1.05) # Drawing the regions in the # Image for (x, y, w, h) in regions: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # Showing the output Image cv2.imshow(\"Image\", image) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break cap.release()cv2.destroyAllWindows()", "e": 28273, "s": 27152, "text": null }, { "code": null, "e": 28281, "s": 28273, "text": "Output:" }, { "code": null, "e": 28295, "s": 28281, "text": "Python-OpenCV" }, { "code": null, "e": 28302, "s": 28295, "text": "Python" }, { "code": null, "e": 28400, "s": 28302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28409, "s": 28400, "text": "Comments" }, { "code": null, "e": 28422, "s": 28409, "text": "Old Comments" }, { "code": null, "e": 28440, "s": 28422, "text": "Python Dictionary" }, { "code": null, "e": 28475, "s": 28440, "text": "Read a file line by line in Python" }, { "code": null, "e": 28497, "s": 28475, "text": "Enumerate() in Python" }, { "code": null, "e": 28529, "s": 28497, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28559, "s": 28529, "text": "Iterate over a list in Python" }, { "code": null, "e": 28601, "s": 28559, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28627, "s": 28601, "text": "Python String | replace()" }, { "code": null, "e": 28670, "s": 28627, "text": "Python program to convert a list to string" }, { "code": null, "e": 28714, "s": 28670, "text": "Reading and Writing to text files in Python" } ]
How to perform mouseover action on an element in Selenium?
We can perform mouseover action on elements in Selenium with the help of Actions class. In order to perform the mouse movement we will use moveToElement () method of the Actions class. Finally use build().perform() to execute all the steps. import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import java.util.concurrent.TimeUnit; public class MouseOver{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/questions/index.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // actions class with moveToElement() method for mouse hover to element Actions a = new Actions(driver); a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))). build().perform(); driver.quit(); } }
[ { "code": null, "e": 1303, "s": 1062, "text": "We can perform mouseover action on elements in Selenium with the help of Actions class. In order to perform the mouse movement we will use moveToElement () method of the Actions class. Finally use build().perform() to execute all the steps." }, { "code": null, "e": 2260, "s": 1303, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.interactions.Action;\nimport org.openqa.selenium.interactions.Actions;\nimport java.util.concurrent.TimeUnit;\npublic class MouseOver{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/questions/index.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // actions class with moveToElement() method for mouse hover to element\n Actions a = new Actions(driver);\n a.moveToElement(driver.findElement(By.xpath(“input[@type=’text’]))).\n build().perform();\n driver.quit();\n }\n}" } ]
Tryit Editor v3.7
Tryit: HTML comment to hide content
[]
C# | Union of two HashSet - GeeksforGeeks
01 Feb, 2019 A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. For the Union of two HashSet, HashSet.UnionWith(IEnumerable) Method is used. Syntax: firstSet.UnionWith(secondSet) Exception: If the Set is null then this method give ArgumentNullException. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to find Union of two HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting even numbers less than // equal to 10 in HashSet mySet1 for (int i = 0; i < 5; i++) { mySet1.Add(i * 2); } // Inserting odd numbers less than // equal to 10 in HashSet mySet2 for (int i = 0; i < 5; i++) { mySet1.Add(i * 2 + 1); } // Creating a new HashSet that contains // the union of both the HashSet mySet1 & mySet2 HashSet<int> ans = new HashSet<int>(mySet1); ans.UnionWith(mySet2); // Printing the union of both the HashSet foreach(int i in ans) { Console.WriteLine(i); } }} 0 2 4 6 8 1 3 5 7 9 Example 2: // C# code to find Union of two HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements in mySet1 mySet1.Add("Hello"); mySet1.Add("GeeksforGeeks"); mySet1.Add("GeeksforGeeks"); // Inserting elements in mySet2 mySet2.Add("You"); mySet2.Add("are"); mySet2.Add("the"); mySet2.Add("best"); // Creating a new HashSet that contains // the union of both the HashSet mySet1 & mySet2 HashSet<string> ans = new HashSet<string>(mySet1); ans.UnionWith(mySet2); // Printing the union of both the HashSet foreach(string i in ans) { Console.WriteLine(i); } }} Hello GeeksforGeeks You are the best Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.unionwith?view=netframework-4.7.2 CSharp-Generic-HashSet CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | Class and Object Different ways to sort an array in descending order in C# Common Language Runtime (CLR) in C#
[ { "code": null, "e": 23999, "s": 23971, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24371, "s": 23999, "text": "A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. For the Union of two HashSet, HashSet.UnionWith(IEnumerable) Method is used." }, { "code": null, "e": 24379, "s": 24371, "text": "Syntax:" }, { "code": null, "e": 24409, "s": 24379, "text": "firstSet.UnionWith(secondSet)" }, { "code": null, "e": 24484, "s": 24409, "text": "Exception: If the Set is null then this method give ArgumentNullException." }, { "code": null, "e": 24564, "s": 24484, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 24575, "s": 24564, "text": "Example 1:" }, { "code": "// C# code to find Union of two HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting even numbers less than // equal to 10 in HashSet mySet1 for (int i = 0; i < 5; i++) { mySet1.Add(i * 2); } // Inserting odd numbers less than // equal to 10 in HashSet mySet2 for (int i = 0; i < 5; i++) { mySet1.Add(i * 2 + 1); } // Creating a new HashSet that contains // the union of both the HashSet mySet1 & mySet2 HashSet<int> ans = new HashSet<int>(mySet1); ans.UnionWith(mySet2); // Printing the union of both the HashSet foreach(int i in ans) { Console.WriteLine(i); } }}", "e": 25563, "s": 24575, "text": null }, { "code": null, "e": 25584, "s": 25563, "text": "0\n2\n4\n6\n8\n1\n3\n5\n7\n9\n" }, { "code": null, "e": 25595, "s": 25584, "text": "Example 2:" }, { "code": "// C# code to find Union of two HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements in mySet1 mySet1.Add(\"Hello\"); mySet1.Add(\"GeeksforGeeks\"); mySet1.Add(\"GeeksforGeeks\"); // Inserting elements in mySet2 mySet2.Add(\"You\"); mySet2.Add(\"are\"); mySet2.Add(\"the\"); mySet2.Add(\"best\"); // Creating a new HashSet that contains // the union of both the HashSet mySet1 & mySet2 HashSet<string> ans = new HashSet<string>(mySet1); ans.UnionWith(mySet2); // Printing the union of both the HashSet foreach(string i in ans) { Console.WriteLine(i); } }}", "e": 26573, "s": 25595, "text": null }, { "code": null, "e": 26611, "s": 26573, "text": "Hello\nGeeksforGeeks\nYou\nare\nthe\nbest\n" }, { "code": null, "e": 26622, "s": 26611, "text": "Reference:" }, { "code": null, "e": 26737, "s": 26622, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.unionwith?view=netframework-4.7.2" }, { "code": null, "e": 26760, "s": 26737, "text": "CSharp-Generic-HashSet" }, { "code": null, "e": 26785, "s": 26760, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 26799, "s": 26785, "text": "CSharp-method" }, { "code": null, "e": 26802, "s": 26799, "text": "C#" }, { "code": null, "e": 26900, "s": 26802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26909, "s": 26900, "text": "Comments" }, { "code": null, "e": 26922, "s": 26909, "text": "Old Comments" }, { "code": null, "e": 26968, "s": 26922, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26983, "s": 26968, "text": "C# | Delegates" }, { "code": null, "e": 27023, "s": 26983, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27041, "s": 27023, "text": "C# | Constructors" }, { "code": null, "e": 27064, "s": 27041, "text": "Extension Method in C#" }, { "code": null, "e": 27095, "s": 27064, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27117, "s": 27095, "text": "C# | Abstract Classes" }, { "code": null, "e": 27139, "s": 27117, "text": "C# | Class and Object" }, { "code": null, "e": 27197, "s": 27139, "text": "Different ways to sort an array in descending order in C#" } ]
Convert String to Integer in R Programming - strtoi() Function - GeeksforGeeks
01 Jun, 2020 strtoi() function in R Language is used to convert the specified string to integers. Syntax: strtoi(x, base=0L) Parameters:x: character vectorbase: integer between 2 and 36 inclusive, default is 0 Example 1: # R program to illustrate# strtoi function # Initializing some string vectorx <- c("A", "B", "C")y <- c("1", "2", "3") # Calling strtoi() functionstrtoi(x, 16L)strtoi(y) Output : [1] 10 11 12 [1] 1 2 3 Example 2: # R program to illustrate# strtoi function # Calling strtoi() function over# some specified stringsstrtoi(c("0xff", "023", "567"))strtoi(c("ffff", "FFFF"), 16L)strtoi(c("246", "135"), 8L) Output: [1] 255 19 567 [1] 65535 65535 [1] 166 93 R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ?
[ { "code": null, "e": 24622, "s": 24594, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24707, "s": 24622, "text": "strtoi() function in R Language is used to convert the specified string to integers." }, { "code": null, "e": 24734, "s": 24707, "text": "Syntax: strtoi(x, base=0L)" }, { "code": null, "e": 24819, "s": 24734, "text": "Parameters:x: character vectorbase: integer between 2 and 36 inclusive, default is 0" }, { "code": null, "e": 24830, "s": 24819, "text": "Example 1:" }, { "code": "# R program to illustrate# strtoi function # Initializing some string vectorx <- c(\"A\", \"B\", \"C\")y <- c(\"1\", \"2\", \"3\") # Calling strtoi() functionstrtoi(x, 16L)strtoi(y)", "e": 25002, "s": 24830, "text": null }, { "code": null, "e": 25011, "s": 25002, "text": "Output :" }, { "code": null, "e": 25035, "s": 25011, "text": "[1] 10 11 12\n[1] 1 2 3\n" }, { "code": null, "e": 25046, "s": 25035, "text": "Example 2:" }, { "code": "# R program to illustrate# strtoi function # Calling strtoi() function over# some specified stringsstrtoi(c(\"0xff\", \"023\", \"567\"))strtoi(c(\"ffff\", \"FFFF\"), 16L)strtoi(c(\"246\", \"135\"), 8L)", "e": 25235, "s": 25046, "text": null }, { "code": null, "e": 25243, "s": 25235, "text": "Output:" }, { "code": null, "e": 25288, "s": 25243, "text": "[1] 255 19 567\n[1] 65535 65535\n[1] 166 93\n" }, { "code": null, "e": 25307, "s": 25288, "text": "R String-Functions" }, { "code": null, "e": 25318, "s": 25307, "text": "R Language" }, { "code": null, "e": 25416, "s": 25318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25468, "s": 25416, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25520, "s": 25468, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25564, "s": 25520, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25602, "s": 25564, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25637, "s": 25602, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25673, "s": 25637, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 25722, "s": 25673, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 25780, "s": 25722, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25829, "s": 25780, "text": "How to filter R DataFrame by values in a column?" } ]
How to get the diagonal length of the device screen using JavaScript ? - GeeksforGeeks
27 Apr, 2020 Knowing the width and height of a browser window helps a web developer to enhancing the user experience. It can help in improving browser animations and the relative positioning of divisions and containers. Javascript provides a window object that represent an open browser window. It provides the various properties which define the dimensions of your browser window. They are as follows: innerWidth: It returns the width of the window’s content area. innerHeight: It returns the height of the window’s content area. outerWidth: It returns the width of the browser window. outerHeight: It returns the height of the browser window. Note: These dimensions are in pixels. Since pixels are a dimensionally square unit. You cannot tell accurately how many pixels lie on the diagonal. You can approximate the diagonal by using the browser height and width and applying the Pythagoras theorem. Pythagoras Theorem: For a right-angled triangle, hypotenuse squared is the sum of base squared and height squared. Analogous to the above formula, Diagonal = Squared_root(Width^2 + Height^2). Code Snippet: <script>function myFunction() { var w = window.outerWidth; var h = window.outerHeight; var d = Math.sqrt(w*w + h*h); console.log('Width: ' + w); console.log('Height: ' + h); console.log('Diagonal: ' + Math.ceil(d));}</script> The above code will print the browser height and width in the console window. The console window can be opened using the developer tools in your browser.Note: To get the complete screen dimensions, switch your browser to fullscreen mode. Most browsers switch the fullscreen mode using the F11 key. The below code displays the results on the browser window using the innerHTML property of Javascript. <!DOCTYPE html><html> <body> <p> Switch to Fullscreen Mode using the F11 key. <br>Click the button to display the dimensions of this browser window.<br> All dimensions are in pixel units. </p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var i_w = window.innerWidth; var i_h = window.innerHeight; var o_w = window.outerWidth; var o_h = window.outerHeight; var d = Math.sqrt(o_w * o_w + o_h * o_h); document.getElementById("demo").innerHTML = "Inner Width: " + i_w + "<br>Inner Height " + i_h + "<br>Outer Width: " + o_w + "<br>Outer Height: " + o_h + "<br>Diagonal: " + Math.ceil(d); } </script></body> </html> Output: Before pressing ‘Try It’ button: After pressing ‘Try It’ button: Note: If you know the linear pixel density of your monitor screen, you can divide the dimensions obtained from the above code with the density to get the dimensions in centimeters or inches. HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js
[ { "code": null, "e": 24503, "s": 24475, "text": "\n27 Apr, 2020" }, { "code": null, "e": 24893, "s": 24503, "text": "Knowing the width and height of a browser window helps a web developer to enhancing the user experience. It can help in improving browser animations and the relative positioning of divisions and containers. Javascript provides a window object that represent an open browser window. It provides the various properties which define the dimensions of your browser window. They are as follows:" }, { "code": null, "e": 24956, "s": 24893, "text": "innerWidth: It returns the width of the window’s content area." }, { "code": null, "e": 25021, "s": 24956, "text": "innerHeight: It returns the height of the window’s content area." }, { "code": null, "e": 25077, "s": 25021, "text": "outerWidth: It returns the width of the browser window." }, { "code": null, "e": 25135, "s": 25077, "text": "outerHeight: It returns the height of the browser window." }, { "code": null, "e": 25173, "s": 25135, "text": "Note: These dimensions are in pixels." }, { "code": null, "e": 25391, "s": 25173, "text": "Since pixels are a dimensionally square unit. You cannot tell accurately how many pixels lie on the diagonal. You can approximate the diagonal by using the browser height and width and applying the Pythagoras theorem." }, { "code": null, "e": 25506, "s": 25391, "text": "Pythagoras Theorem: For a right-angled triangle, hypotenuse squared is the sum of base squared and height squared." }, { "code": null, "e": 25583, "s": 25506, "text": "Analogous to the above formula, Diagonal = Squared_root(Width^2 + Height^2)." }, { "code": null, "e": 25597, "s": 25583, "text": "Code Snippet:" }, { "code": "<script>function myFunction() { var w = window.outerWidth; var h = window.outerHeight; var d = Math.sqrt(w*w + h*h); console.log('Width: ' + w); console.log('Height: ' + h); console.log('Diagonal: ' + Math.ceil(d));}</script>", "e": 25829, "s": 25597, "text": null }, { "code": null, "e": 26127, "s": 25829, "text": "The above code will print the browser height and width in the console window. The console window can be opened using the developer tools in your browser.Note: To get the complete screen dimensions, switch your browser to fullscreen mode. Most browsers switch the fullscreen mode using the F11 key." }, { "code": null, "e": 26229, "s": 26127, "text": "The below code displays the results on the browser window using the innerHTML property of Javascript." }, { "code": "<!DOCTYPE html><html> <body> <p> Switch to Fullscreen Mode using the F11 key. <br>Click the button to display the dimensions of this browser window.<br> All dimensions are in pixel units. </p> <button onclick=\"myFunction()\">Try it</button> <p id=\"demo\"></p> <script> function myFunction() { var i_w = window.innerWidth; var i_h = window.innerHeight; var o_w = window.outerWidth; var o_h = window.outerHeight; var d = Math.sqrt(o_w * o_w + o_h * o_h); document.getElementById(\"demo\").innerHTML = \"Inner Width: \" + i_w + \"<br>Inner Height \" + i_h + \"<br>Outer Width: \" + o_w + \"<br>Outer Height: \" + o_h + \"<br>Diagonal: \" + Math.ceil(d); } </script></body> </html>", "e": 27093, "s": 26229, "text": null }, { "code": null, "e": 27101, "s": 27093, "text": "Output:" }, { "code": null, "e": 27134, "s": 27101, "text": "Before pressing ‘Try It’ button:" }, { "code": null, "e": 27166, "s": 27134, "text": "After pressing ‘Try It’ button:" }, { "code": null, "e": 27357, "s": 27166, "text": "Note: If you know the linear pixel density of your monitor screen, you can divide the dimensions obtained from the above code with the density to get the dimensions in centimeters or inches." }, { "code": null, "e": 27367, "s": 27357, "text": "HTML-Misc" }, { "code": null, "e": 27383, "s": 27367, "text": "JavaScript-Misc" }, { "code": null, "e": 27390, "s": 27383, "text": "Picked" }, { "code": null, "e": 27395, "s": 27390, "text": "HTML" }, { "code": null, "e": 27406, "s": 27395, "text": "JavaScript" }, { "code": null, "e": 27423, "s": 27406, "text": "Web Technologies" }, { "code": null, "e": 27450, "s": 27423, "text": "Web technologies Questions" }, { "code": null, "e": 27455, "s": 27450, "text": "HTML" }, { "code": null, "e": 27553, "s": 27455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27562, "s": 27553, "text": "Comments" }, { "code": null, "e": 27575, "s": 27562, "text": "Old Comments" }, { "code": null, "e": 27599, "s": 27575, "text": "REST API (Introduction)" }, { "code": null, "e": 27636, "s": 27599, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27665, "s": 27636, "text": "Form validation using jQuery" }, { "code": null, "e": 27712, "s": 27665, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 27774, "s": 27712, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 27835, "s": 27774, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27880, "s": 27835, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27952, "s": 27880, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28021, "s": 27952, "text": "How to calculate the number of days between two dates in javascript?" } ]
Putting semicolons after while and if statements in C++
When you have a statement like − while (expression); the while loop runs no matter if the expression is true or not. However, if you put − if (expression); the statement runs no matter if the expression is true or not. This is because the syntax for if and while is − if (<expr>) <statement> // or while (<expr>) <statement> So the <statement> is only executed if the <expr> evaluates to true. In while, it will enter an infinite loop. So the question what <statement> it executes. If there are not braces {} then the next statement is terminated by; even if that statement is EMPTY. Note that an empty statement is valid. if (<expr>) /* Empty Statement */; while (<expr>) /* Empty Statement */; In both cases, there is nothing being executed (after the expression is evaluated). Though while may enter an infinite loop. Note: '{}' is a statement-Block (a type of statement (that contains a list of other statements).
[ { "code": null, "e": 1095, "s": 1062, "text": "When you have a statement like −" }, { "code": null, "e": 1115, "s": 1095, "text": "while (expression);" }, { "code": null, "e": 1201, "s": 1115, "text": "the while loop runs no matter if the expression is true or not. However, if you put −" }, { "code": null, "e": 1218, "s": 1201, "text": "if (expression);" }, { "code": null, "e": 1330, "s": 1218, "text": "the statement runs no matter if the expression is true or not. This is because the syntax for if and while is −" }, { "code": null, "e": 1387, "s": 1330, "text": "if (<expr>) <statement>\n// or\nwhile (<expr>) <statement>" }, { "code": null, "e": 1498, "s": 1387, "text": "So the <statement> is only executed if the <expr> evaluates to true. In while, it will enter an infinite loop." }, { "code": null, "e": 1685, "s": 1498, "text": "So the question what <statement> it executes. If there are not braces {} then the next statement is terminated by; even if that statement is EMPTY. Note that an empty statement is valid." }, { "code": null, "e": 1761, "s": 1685, "text": "if (<expr>) /* Empty Statement */;\nwhile (<expr>) /* Empty Statement */;" }, { "code": null, "e": 1983, "s": 1761, "text": "In both cases, there is nothing being executed (after the expression is evaluated). Though while may enter an infinite loop. Note: '{}' is a statement-Block (a type of statement (that contains a list of other statements)." } ]
Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K | Set 2 - GeeksforGeeks
24 Feb, 2022 Given two positive integers N and K, the task is to construct a permutation of the first N natural numbers such that all possible absolute differences between adjacent elements are K. Examples: Input: N = 3, K = 1Output: 1 2 3Explanation: Considering the permutation {1, 2, 3}, all possible unique absolute difference of adjacent elements is {1}. Since the count is 1(= K), print the sequence {1, 2, 3} as the resultant permutation. Input: N = 3, K = 2Output: 1 3 2 The naive approach and the two-pointer approach of this problem are already discussed here. This article discusses a different approach deque. Approach: It is easy to see that, answers for all values of K between [1, N-1] can be generated. For any K outside this range, there exists no answer. To solve the problem maintain a double-ended queue for all the current elements and a vector to store the sequence. Also, maintain a boolean value that will help to determine to pop the front or back element. Iterate the remaining element and if K is greater than 1 then push the element according to the boolean value and decrease K by 1. Flip the boolean value so that all remaining differences will have value 1. Follow the steps below to solve the problem: If K is greater than equal to N or less than 1, then print -1 and return as no such sequence exists. Initialize a deque dq[] to maintain the order of elements. Iterate over the range [2, N] using the variable i and push i into the back of deque dq[]. Initialize a boolean variable front as true. Initialize a vector ans[] to store the answer and push 1 into the vector ans[]. If K is greater than 1, then subtract 1 from K and xor the value of front with 1. Iterate over the range [2, N] using the variable i and check:If the front is 1, then pop the front of the deque dq[] and push it in the vector ans[] otherwise, pop the back of the deque dq[] and push it in the vector ans[]. Also, if K is greater then, then subtract 1 from K and xor the value of front with 1. If the front is 1, then pop the front of the deque dq[] and push it in the vector ans[] otherwise, pop the back of the deque dq[] and push it in the vector ans[]. Also, if K is greater then, then subtract 1 from K and xor the value of front with 1. Traverse the array ans[] and print its elements. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ Program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the required arrayvoid K_ValuesArray(int N, int K){ // Check for base cases if (K < 1 || K >= N) { cout << -1; return; } // Maintain a deque to store the // elements from [1, N]; deque<int> dq; for (int i = 2; i <= N; i++) { dq.push_back(i); } // Maintain a boolean value which will // tell from where to pop the element bool front = true; // Create a vector to store the answer vector<int> ans; // Push 1 in the answer initially ans.push_back(1); // Push the remaining elements if (K > 1) { front ^= 1; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.front(); dq.pop_front(); // Push this value in // the ans vector ans.push_back(val); if (K > 1) { K--; // Flip the boolean // value front ^= 1; } } else { int val = dq.back(); dq.pop_back(); // Push value in ans vector ans.push_back(val); if (K > 1) { K--; // Flip boolean value front ^= 1; } } } // Print Answer for (int i = 0; i < N; i++) { cout << ans[i] << " "; }} // Driver Codeint main(){ int N = 7, K = 1; K_ValuesArray(N, K); return 0;} // Java Program for the above approachimport java.util.*;class GFG{ // Function to calculate the required arraystatic void K_ValuesArray(int N, int K){ // Check for base cases if (K < 1 || K >= N) { System.out.print(-1); return; } // Maintain a deque to store the // elements from [1, N]; Deque<Integer> dq = new LinkedList<Integer>(); for (int i = 2; i <= N; i++) { dq.add(i); } // Maintain a boolean value which will // tell from where to pop the element boolean front = true; // Create a vector to store the answer Vector<Integer> ans = new Vector<Integer>(); // Push 1 in the answer initially ans.add(1); // Push the remaining elements if (K > 1) { front ^=true; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.peek(); dq.removeFirst(); // Push this value in // the ans vector ans.add(val); if (K > 1) { K--; // Flip the boolean // value front ^=true; } } else { int val = dq.getLast(); dq.removeLast(); // Push value in ans vector ans.add(val); if (K > 1) { K--; // Flip boolean value front ^=true; } } } // Print Answer for (int i = 0; i < N; i++) { System.out.print(ans.get(i)+ " "); }} // Driver Codepublic static void main(String[] args){ int N = 7, K = 1; K_ValuesArray(N, K); }} // This code is contributed by 29AjayKumar # python Program for the above approachfrom collections import deque # Function to calculate the required arraydef K_ValuesArray(N, K): # Check for base cases if (K < 1 or K >= N): print("-1") return # Maintain a deque to store the # elements from [1, N]; dq = deque() for i in range(2, N + 1): dq.append(i) # Maintain a boolean value which will # tell from where to pop the element front = True # Create a vector to store the answer ans = [] # Push 1 in the answer initially ans.append(1) # Push the remaining elements if (K > 1): front ^= 1 K -= 1 # Iterate over the range for i in range(2, N+1): if (front): val = dq.popleft() # Push this value in # the ans vector ans.append(val) if (K > 1): K -= 1 # Flip the boolean # value front ^= 1 else: val = dq.pop() # Push value in ans vector ans.append(val) if (K > 1): K -= 1 # Flip boolean value front ^= 1 # Print Answer for i in range(0, N): print(ans[i], end=" ") # Driver Codeif __name__ == "__main__": N = 7 K = 1 K_ValuesArray(N, K) # This code is contributed by rakeshsahni // C# Program for the above approach using System;using System.Collections.Generic;class GFG{ // Function to calculate the required array static void K_ValuesArray(int N, int K) { // Check for base cases if (K < 1 || K >= N) { Console.Write(-1); return; } // Maintain a deque to store the // elements from [1, N]; LinkedList<int> dq = new LinkedList<int>(); for (int i = 2; i <= N; i++) { dq.AddLast(i); } // Maintain a boolean value which will // tell from where to pop the element bool front = true; // Create a vector to store the answer List<int> ans = new List<int>(); // Push 1 in the answer initially ans.Add(1); // Push the remaining elements if (K > 1) { front ^= true; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.First.Value; dq.RemoveFirst(); // Push this value in // the ans vector ans.Add(val); if (K > 1) { K--; // Flip the boolean // value front ^= true; } } else { int val = dq.Last.Value; dq.RemoveLast(); // Push value in ans vector ans.Add(val); if (K > 1) { K--; // Flip boolean value front ^= true; } } } // Print Answer for (int i = 0; i < N; i++) { Console.Write(ans[i] + " "); } } // Driver Code public static void Main() { int N = 7, K = 1; K_ValuesArray(N, K); }} // This code is contributed by Saurabh Jaiswal <script>// Javascript Program for the above approach // Function to calculate the required arrayfunction K_ValuesArray(N, K) { // Check for base cases if (K < 1 || K >= N) { document.write(-1); return; } // Maintain a deque to store the // elements from [1, N]; let dq = new Array(); for (let i = 2; i <= N; i++) { dq.push(i); } // Maintain a boolean value which will // tell from where to pop the element let front = true; // Create a vector to store the answer let ans = new Array(); // Push 1 in the answer initially ans.push(1); // Push the remaining elements if (K > 1) { front ^= true; K--; } // Iterate over the range for (let i = 2; i <= N; i++) { if (front) { let val = dq[0]; dq.shift(); // Push this value in // the ans vector ans.push(val); if (K > 1) { K--; // Flip the boolean // value front ^= true; } } else { let val = dq.Last.Value; dq.pop(); // Push value in ans vector ans.push(val); if (K > 1) { K--; // Flip boolean value front ^= true; } } } // Print Answer for (let i = 0; i < N; i++) { document.write(ans[i] + " "); }} // Driver Codelet N = 7, K = 1;K_ValuesArray(N, K); // This code is contributed by Saurabh Jaiswal</script> 1 2 3 4 5 6 7 Time Complexity: O(N)Auxiliary Space: O(N) rakeshsahni 29AjayKumar _saurabh_jaiswal simranarora5sos deque Arrays Greedy Mathematical Pattern Searching Arrays Greedy Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Building Heap from Array Window Sliding Technique 1's and 2's complement of a Binary Number Reversal algorithm for array rotation Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24405, "s": 24377, "text": "\n24 Feb, 2022" }, { "code": null, "e": 24589, "s": 24405, "text": "Given two positive integers N and K, the task is to construct a permutation of the first N natural numbers such that all possible absolute differences between adjacent elements are K." }, { "code": null, "e": 24599, "s": 24589, "text": "Examples:" }, { "code": null, "e": 24838, "s": 24599, "text": "Input: N = 3, K = 1Output: 1 2 3Explanation: Considering the permutation {1, 2, 3}, all possible unique absolute difference of adjacent elements is {1}. Since the count is 1(= K), print the sequence {1, 2, 3} as the resultant permutation." }, { "code": null, "e": 24871, "s": 24838, "text": "Input: N = 3, K = 2Output: 1 3 2" }, { "code": null, "e": 25014, "s": 24871, "text": "The naive approach and the two-pointer approach of this problem are already discussed here. This article discusses a different approach deque." }, { "code": null, "e": 25626, "s": 25014, "text": "Approach: It is easy to see that, answers for all values of K between [1, N-1] can be generated. For any K outside this range, there exists no answer. To solve the problem maintain a double-ended queue for all the current elements and a vector to store the sequence. Also, maintain a boolean value that will help to determine to pop the front or back element. Iterate the remaining element and if K is greater than 1 then push the element according to the boolean value and decrease K by 1. Flip the boolean value so that all remaining differences will have value 1. Follow the steps below to solve the problem:" }, { "code": null, "e": 25727, "s": 25626, "text": "If K is greater than equal to N or less than 1, then print -1 and return as no such sequence exists." }, { "code": null, "e": 25786, "s": 25727, "text": "Initialize a deque dq[] to maintain the order of elements." }, { "code": null, "e": 25877, "s": 25786, "text": "Iterate over the range [2, N] using the variable i and push i into the back of deque dq[]." }, { "code": null, "e": 25922, "s": 25877, "text": "Initialize a boolean variable front as true." }, { "code": null, "e": 26002, "s": 25922, "text": "Initialize a vector ans[] to store the answer and push 1 into the vector ans[]." }, { "code": null, "e": 26084, "s": 26002, "text": "If K is greater than 1, then subtract 1 from K and xor the value of front with 1." }, { "code": null, "e": 26394, "s": 26084, "text": "Iterate over the range [2, N] using the variable i and check:If the front is 1, then pop the front of the deque dq[] and push it in the vector ans[] otherwise, pop the back of the deque dq[] and push it in the vector ans[]. Also, if K is greater then, then subtract 1 from K and xor the value of front with 1." }, { "code": null, "e": 26643, "s": 26394, "text": "If the front is 1, then pop the front of the deque dq[] and push it in the vector ans[] otherwise, pop the back of the deque dq[] and push it in the vector ans[]. Also, if K is greater then, then subtract 1 from K and xor the value of front with 1." }, { "code": null, "e": 26692, "s": 26643, "text": "Traverse the array ans[] and print its elements." }, { "code": null, "e": 26743, "s": 26692, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 26747, "s": 26743, "text": "C++" }, { "code": null, "e": 26752, "s": 26747, "text": "Java" }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": null, "e": 26763, "s": 26760, "text": "C#" }, { "code": null, "e": 26774, "s": 26763, "text": "Javascript" }, { "code": "// C++ Program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the required arrayvoid K_ValuesArray(int N, int K){ // Check for base cases if (K < 1 || K >= N) { cout << -1; return; } // Maintain a deque to store the // elements from [1, N]; deque<int> dq; for (int i = 2; i <= N; i++) { dq.push_back(i); } // Maintain a boolean value which will // tell from where to pop the element bool front = true; // Create a vector to store the answer vector<int> ans; // Push 1 in the answer initially ans.push_back(1); // Push the remaining elements if (K > 1) { front ^= 1; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.front(); dq.pop_front(); // Push this value in // the ans vector ans.push_back(val); if (K > 1) { K--; // Flip the boolean // value front ^= 1; } } else { int val = dq.back(); dq.pop_back(); // Push value in ans vector ans.push_back(val); if (K > 1) { K--; // Flip boolean value front ^= 1; } } } // Print Answer for (int i = 0; i < N; i++) { cout << ans[i] << \" \"; }} // Driver Codeint main(){ int N = 7, K = 1; K_ValuesArray(N, K); return 0;}", "e": 28332, "s": 26774, "text": null }, { "code": "// Java Program for the above approachimport java.util.*;class GFG{ // Function to calculate the required arraystatic void K_ValuesArray(int N, int K){ // Check for base cases if (K < 1 || K >= N) { System.out.print(-1); return; } // Maintain a deque to store the // elements from [1, N]; Deque<Integer> dq = new LinkedList<Integer>(); for (int i = 2; i <= N; i++) { dq.add(i); } // Maintain a boolean value which will // tell from where to pop the element boolean front = true; // Create a vector to store the answer Vector<Integer> ans = new Vector<Integer>(); // Push 1 in the answer initially ans.add(1); // Push the remaining elements if (K > 1) { front ^=true; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.peek(); dq.removeFirst(); // Push this value in // the ans vector ans.add(val); if (K > 1) { K--; // Flip the boolean // value front ^=true; } } else { int val = dq.getLast(); dq.removeLast(); // Push value in ans vector ans.add(val); if (K > 1) { K--; // Flip boolean value front ^=true; } } } // Print Answer for (int i = 0; i < N; i++) { System.out.print(ans.get(i)+ \" \"); }} // Driver Codepublic static void main(String[] args){ int N = 7, K = 1; K_ValuesArray(N, K); }} // This code is contributed by 29AjayKumar", "e": 30015, "s": 28332, "text": null }, { "code": "# python Program for the above approachfrom collections import deque # Function to calculate the required arraydef K_ValuesArray(N, K): # Check for base cases if (K < 1 or K >= N): print(\"-1\") return # Maintain a deque to store the # elements from [1, N]; dq = deque() for i in range(2, N + 1): dq.append(i) # Maintain a boolean value which will # tell from where to pop the element front = True # Create a vector to store the answer ans = [] # Push 1 in the answer initially ans.append(1) # Push the remaining elements if (K > 1): front ^= 1 K -= 1 # Iterate over the range for i in range(2, N+1): if (front): val = dq.popleft() # Push this value in # the ans vector ans.append(val) if (K > 1): K -= 1 # Flip the boolean # value front ^= 1 else: val = dq.pop() # Push value in ans vector ans.append(val) if (K > 1): K -= 1 # Flip boolean value front ^= 1 # Print Answer for i in range(0, N): print(ans[i], end=\" \") # Driver Codeif __name__ == \"__main__\": N = 7 K = 1 K_ValuesArray(N, K) # This code is contributed by rakeshsahni", "e": 31389, "s": 30015, "text": null }, { "code": "// C# Program for the above approach using System;using System.Collections.Generic;class GFG{ // Function to calculate the required array static void K_ValuesArray(int N, int K) { // Check for base cases if (K < 1 || K >= N) { Console.Write(-1); return; } // Maintain a deque to store the // elements from [1, N]; LinkedList<int> dq = new LinkedList<int>(); for (int i = 2; i <= N; i++) { dq.AddLast(i); } // Maintain a boolean value which will // tell from where to pop the element bool front = true; // Create a vector to store the answer List<int> ans = new List<int>(); // Push 1 in the answer initially ans.Add(1); // Push the remaining elements if (K > 1) { front ^= true; K--; } // Iterate over the range for (int i = 2; i <= N; i++) { if (front) { int val = dq.First.Value; dq.RemoveFirst(); // Push this value in // the ans vector ans.Add(val); if (K > 1) { K--; // Flip the boolean // value front ^= true; } } else { int val = dq.Last.Value; dq.RemoveLast(); // Push value in ans vector ans.Add(val); if (K > 1) { K--; // Flip boolean value front ^= true; } } } // Print Answer for (int i = 0; i < N; i++) { Console.Write(ans[i] + \" \"); } } // Driver Code public static void Main() { int N = 7, K = 1; K_ValuesArray(N, K); }} // This code is contributed by Saurabh Jaiswal", "e": 33418, "s": 31389, "text": null }, { "code": "<script>// Javascript Program for the above approach // Function to calculate the required arrayfunction K_ValuesArray(N, K) { // Check for base cases if (K < 1 || K >= N) { document.write(-1); return; } // Maintain a deque to store the // elements from [1, N]; let dq = new Array(); for (let i = 2; i <= N; i++) { dq.push(i); } // Maintain a boolean value which will // tell from where to pop the element let front = true; // Create a vector to store the answer let ans = new Array(); // Push 1 in the answer initially ans.push(1); // Push the remaining elements if (K > 1) { front ^= true; K--; } // Iterate over the range for (let i = 2; i <= N; i++) { if (front) { let val = dq[0]; dq.shift(); // Push this value in // the ans vector ans.push(val); if (K > 1) { K--; // Flip the boolean // value front ^= true; } } else { let val = dq.Last.Value; dq.pop(); // Push value in ans vector ans.push(val); if (K > 1) { K--; // Flip boolean value front ^= true; } } } // Print Answer for (let i = 0; i < N; i++) { document.write(ans[i] + \" \"); }} // Driver Codelet N = 7, K = 1;K_ValuesArray(N, K); // This code is contributed by Saurabh Jaiswal</script>", "e": 34972, "s": 33418, "text": null }, { "code": null, "e": 34987, "s": 34972, "text": "1 2 3 4 5 6 7 " }, { "code": null, "e": 35030, "s": 34987, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35042, "s": 35030, "text": "rakeshsahni" }, { "code": null, "e": 35054, "s": 35042, "text": "29AjayKumar" }, { "code": null, "e": 35071, "s": 35054, "text": "_saurabh_jaiswal" }, { "code": null, "e": 35087, "s": 35071, "text": "simranarora5sos" }, { "code": null, "e": 35093, "s": 35087, "text": "deque" }, { "code": null, "e": 35100, "s": 35093, "text": "Arrays" }, { "code": null, "e": 35107, "s": 35100, "text": "Greedy" }, { "code": null, "e": 35120, "s": 35107, "text": "Mathematical" }, { "code": null, "e": 35138, "s": 35120, "text": "Pattern Searching" }, { "code": null, "e": 35145, "s": 35138, "text": "Arrays" }, { "code": null, "e": 35152, "s": 35145, "text": "Greedy" }, { "code": null, "e": 35165, "s": 35152, "text": "Mathematical" }, { "code": null, "e": 35183, "s": 35165, "text": "Pattern Searching" }, { "code": null, "e": 35281, "s": 35183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35290, "s": 35281, "text": "Comments" }, { "code": null, "e": 35303, "s": 35290, "text": "Old Comments" }, { "code": null, "e": 35352, "s": 35303, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35377, "s": 35352, "text": "Building Heap from Array" }, { "code": null, "e": 35402, "s": 35377, "text": "Window Sliding Technique" }, { "code": null, "e": 35444, "s": 35402, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 35482, "s": 35444, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35533, "s": 35482, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 35584, "s": 35533, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 35642, "s": 35584, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 35673, "s": 35642, "text": "Huffman Coding | Greedy Algo-3" } ]
Lua - Operating System Facilities
In any application, it is often required for to access Operating System level functions and it is made available with Operating System library. The list of functions available are listed in the following table. os.clock () Returns an approximation of the amount in seconds of CPU time used by the program. os.date ([format [, time]]) Returns a string or a table containing date and time, formatted according to the given string format. os.difftime (t2, t1) Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1. os.execute ([command]) This function is equivalent to the ANSI C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or nil otherwise. os.exit ([code [, close]) Calls the ANSI C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number. os.getenv (varname) Returns the value of the process environment variable varname, or nil if the variable is not defined. os.remove (filename) Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns nil, plus a string describing the error and the error code. os.rename (oldname, newname) Renames file or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error and the error code. os.setlocale (locale [, category]) Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored. os.time ([table]) Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). For a description of these fields, see the os.date function. os.tmpname () Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. A simple example using common math functions is shown below. -- Date with format io.write("The date is ", os.date("%m/%d/%Y"),"\n") -- Date and time io.write("The date and time is ", os.date(),"\n") -- Time io.write("The OS time is ", os.time(),"\n") -- Wait for some time for i=1,1000000 do end -- Time since Lua started io.write("Lua started before ", os.clock(),"\n") When we run the above program, we will get similar output to the following. The date is 01/25/2014 The date and time is 01/25/14 07:38:40 The OS time is 1390615720 Lua started before 0.013 The above examples are just a few of the common examples, we can use OS library based on our need, so try using all the functions to be more familiar. There are functions like remove which helps in removing file, execute that helps us executing OS commands as explained above. 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2314, "s": 2103, "text": "In any application, it is often required for to access Operating System level functions and it is made available with Operating System library. The list of functions available are listed in the following table." }, { "code": null, "e": 2326, "s": 2314, "text": "os.clock ()" }, { "code": null, "e": 2409, "s": 2326, "text": "Returns an approximation of the amount in seconds of CPU time used by the program." }, { "code": null, "e": 2437, "s": 2409, "text": "os.date ([format [, time]])" }, { "code": null, "e": 2539, "s": 2437, "text": "Returns a string or a table containing date and time, formatted according to the given string format." }, { "code": null, "e": 2560, "s": 2539, "text": "os.difftime (t2, t1)" }, { "code": null, "e": 2687, "s": 2560, "text": "Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1." }, { "code": null, "e": 2710, "s": 2687, "text": "os.execute ([command])" }, { "code": null, "e": 2915, "s": 2710, "text": "This function is equivalent to the ANSI C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or nil otherwise." }, { "code": null, "e": 2941, "s": 2915, "text": "os.exit ([code [, close])" }, { "code": null, "e": 3169, "s": 2941, "text": "Calls the ANSI C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number." }, { "code": null, "e": 3189, "s": 3169, "text": "os.getenv (varname)" }, { "code": null, "e": 3291, "s": 3189, "text": "Returns the value of the process environment variable varname, or nil if the variable is not defined." }, { "code": null, "e": 3312, "s": 3291, "text": "os.remove (filename)" }, { "code": null, "e": 3484, "s": 3312, "text": "Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns nil, plus a string describing the error and the error code." }, { "code": null, "e": 3513, "s": 3484, "text": "os.rename (oldname, newname)" }, { "code": null, "e": 3661, "s": 3513, "text": " Renames file or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error and the error code." }, { "code": null, "e": 3696, "s": 3661, "text": "os.setlocale (locale [, category])" }, { "code": null, "e": 4043, "s": 3696, "text": "Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: \"all\", \"collate\", \"ctype\", \"monetary\", \"numeric\", or \"time\"; the default category is \"all\". The function returns the name of the new locale, or nil if the request cannot be honored." }, { "code": null, "e": 4061, "s": 4043, "text": "os.time ([table])" }, { "code": null, "e": 4409, "s": 4061, "text": "Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). For a description of these fields, see the os.date function." }, { "code": null, "e": 4423, "s": 4409, "text": "os.tmpname ()" }, { "code": null, "e": 4592, "s": 4423, "text": "Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed." }, { "code": null, "e": 4653, "s": 4592, "text": "A simple example using common math functions is shown below." }, { "code": null, "e": 4967, "s": 4653, "text": "-- Date with format\nio.write(\"The date is \", os.date(\"%m/%d/%Y\"),\"\\n\")\n\n-- Date and time\nio.write(\"The date and time is \", os.date(),\"\\n\")\n\n-- Time\nio.write(\"The OS time is \", os.time(),\"\\n\")\n\n-- Wait for some time\nfor i=1,1000000 do\nend\n\n-- Time since Lua started\nio.write(\"Lua started before \", os.clock(),\"\\n\")" }, { "code": null, "e": 5043, "s": 4967, "text": "When we run the above program, we will get similar output to the following." }, { "code": null, "e": 5157, "s": 5043, "text": "The date is 01/25/2014\nThe date and time is 01/25/14 07:38:40\nThe OS time is 1390615720\nLua started before 0.013\n" }, { "code": null, "e": 5434, "s": 5157, "text": "The above examples are just a few of the common examples, we can use OS library based on our need, so try using all the functions to be more familiar. There are functions like remove which helps in removing file, execute that helps us executing OS commands as explained above." }, { "code": null, "e": 5467, "s": 5434, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 5481, "s": 5467, "text": " Manish Gupta" }, { "code": null, "e": 5514, "s": 5481, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 5530, "s": 5514, "text": " Sanjeev Mittal" }, { "code": null, "e": 5565, "s": 5530, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5581, "s": 5565, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 5588, "s": 5581, "text": " Print" }, { "code": null, "e": 5599, "s": 5588, "text": " Add Notes" } ]
How to implement the search functionality of a JTable in Java?
A JTable is a subclass of JComponent for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can implement the search functionality of a JTable by input a string in the JTextField, it can search for a string available in a JTable. If the string matches it can only display the corresponding value in a JTable. We can use the DocumentListener interface of a JTextField to implement it. import java.awt.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class JTableSearchTest extends JFrame { private JTextField jtf; private JLabel searchLbl; private TableModel model; private JTable table; private TableRowSorter sorter; private JScrollPane jsp; public JTableSearchTest() { setTitle("JTableSearch Test"); jtf = new JTextField(15); searchLbl = new JLabel("Search"); String[] columnNames = {"Name", "Technology"}; Object[][] rowData = {{"Raja", "Java"},{"Vineet", "Java Script"},{"Archana", "Python"},{"Krishna", "Scala"},{"Adithya", "AWS"},{"Jai", ".Net"}}; model = new DefaultTableModel(rowData, columnNames); sorter = new TableRowSorter<>(model); table = new JTable(model); table.setRowSorter(sorter); setLayout(new FlowLayout(FlowLayout.CENTER)); jsp = new JScrollPane(table); add(searchLbl); add(jtf); add(jsp); jtf.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { search(jtf.getText()); } @Override public void removeUpdate(DocumentEvent e) { search(jtf.getText()); } @Override public void changedUpdate(DocumentEvent e) { search(jtf.getText()); } public void search(String str) { if (str.length() == 0) { sorter.setRowFilter(null); } else { sorter.setRowFilter(RowFilter.regexFilter(str)); } } }); setSize(475, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); setVisible(true); } public static void main(String[] args) { new JTableSearchTest(); } }
[ { "code": null, "e": 1697, "s": 1062, "text": "A JTable is a subclass of JComponent for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can implement the search functionality of a JTable by input a string in the JTextField, it can search for a string available in a JTable. If the string matches it can only display the corresponding value in a JTable. We can use the DocumentListener interface of a JTextField to implement it." }, { "code": null, "e": 3578, "s": 1697, "text": "import java.awt.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\nimport javax.swing.table.*;\npublic class JTableSearchTest extends JFrame {\n private JTextField jtf;\n private JLabel searchLbl;\n private TableModel model;\n private JTable table;\n private TableRowSorter sorter;\n private JScrollPane jsp;\n public JTableSearchTest() {\n setTitle(\"JTableSearch Test\");\n jtf = new JTextField(15);\n searchLbl = new JLabel(\"Search\");\n String[] columnNames = {\"Name\", \"Technology\"};\n Object[][] rowData = {{\"Raja\", \"Java\"},{\"Vineet\", \"Java Script\"},{\"Archana\", \"Python\"},{\"Krishna\", \"Scala\"},{\"Adithya\", \"AWS\"},{\"Jai\", \".Net\"}};\n model = new DefaultTableModel(rowData, columnNames);\n sorter = new TableRowSorter<>(model);\n table = new JTable(model);\n table.setRowSorter(sorter);\n setLayout(new FlowLayout(FlowLayout.CENTER));\n jsp = new JScrollPane(table);\n add(searchLbl);\n add(jtf);\n add(jsp);\n jtf.getDocument().addDocumentListener(new DocumentListener() {\n @Override\n public void insertUpdate(DocumentEvent e) {\n search(jtf.getText());\n }\n @Override\n public void removeUpdate(DocumentEvent e) {\n search(jtf.getText());\n }\n @Override\n public void changedUpdate(DocumentEvent e) {\n search(jtf.getText());\n }\n public void search(String str) {\n if (str.length() == 0) {\n sorter.setRowFilter(null);\n } else {\n sorter.setRowFilter(RowFilter.regexFilter(str));\n }\n }\n });\n setSize(475, 300);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setResizable(false);\n setVisible(true);\n }\n public static void main(String[] args) {\n new JTableSearchTest();\n }\n}" } ]
Java Packages
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories: Built-in Packages (packages from the Java API) User-defined Packages (create your own packages) The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/. The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, you need to use the import keyword: import package.name.Class; // Import a single class import package.name.*; // Import the whole package If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code: import java.util.Scanner; In the example above, java.util is a package, while Scanner is a class of the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line: Using the Scanner class to get user input: import java.util.Scanner; class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); } } Run Example » There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package: import java.util.*; Run Example » To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer: └── root └── mypack └── MyPackageClass.java To create a package, use the package keyword: package mypack; class MyPackageClass { public static void main(String[] args) { System.out.println("This is my package!"); } } Run Example » Save the file as MyPackageClass.java, and compile it: Then compile the package: This forces the compiler to create the "mypack" package. The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above. Note: The package name should be written in lower case to avoid conflict with class names. When we compiled the package in the example above, a new folder was created, called "mypack". To run the MyPackageClass.java file, write the following: The output will be: We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 222, "s": 0, "text": "A package in Java is used to group related classes. Think of it as\na folder in a file directory. We use packages to avoid name conflicts, and \nto write a better maintainable code. Packages are divided into two categories:" }, { "code": null, "e": 269, "s": 222, "text": "Built-in Packages (packages from the Java API)" }, { "code": null, "e": 318, "s": 269, "text": "User-defined Packages (create your own packages)" }, { "code": null, "e": 435, "s": 318, "text": "The Java API is a library of prewritten classes, that are free to use, included in the\nJava Development Environment." }, { "code": null, "e": 625, "s": 435, "text": "The library contains components for managing input, database programming, and much much \nmore. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/." }, { "code": null, "e": 850, "s": 625, "text": "The library is divided into packages and classes. \nMeaning you can either import a single class (along with its methods and \nattributes), or a whole package that contain \nall the classes that belong to the specified package." }, { "code": null, "e": 933, "s": 850, "text": "To use a class or a package from the library, you need to use the import \nkeyword:" }, { "code": null, "e": 1041, "s": 933, "text": "import package.name.Class; // Import a single class\nimport package.name.*; // Import the whole package\n" }, { "code": null, "e": 1170, "s": 1041, "text": "If you find a class you want to use, for example, the Scanner class, which is used to get \nuser input, write the following code:" }, { "code": null, "e": 1197, "s": 1170, "text": "import java.util.Scanner;\n" }, { "code": null, "e": 1295, "s": 1197, "text": "In the example above, java.util is a package, while Scanner is a class of \nthe java.util package." }, { "code": null, "e": 1522, "s": 1295, "text": "To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. \nIn our example, we will use the nextLine() method, which is used to read a \ncomplete line:" }, { "code": null, "e": 1565, "s": 1522, "text": "Using the Scanner class to get user input:" }, { "code": null, "e": 1837, "s": 1565, "text": "import java.util.Scanner;\n\nclass MyClass {\n public static void main(String[] args) {\n Scanner myObj = new Scanner(System.in);\n System.out.println(\"Enter username\");\n\n String userName = myObj.nextLine();\n System.out.println(\"Username is: \" + userName);\n }\n}\n" }, { "code": null, "e": 1853, "s": 1837, "text": "\nRun Example »\n" }, { "code": null, "e": 2077, "s": 1853, "text": "There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time \nfacilities, random-number generator and other utility classes." }, { "code": null, "e": 2226, "s": 2077, "text": "To import a whole package, end the sentence with an asterisk sign (*). \nThe following example \nwill import ALL the classes in the java.util package:" }, { "code": null, "e": 2247, "s": 2226, "text": "import java.util.*;\n" }, { "code": null, "e": 2263, "s": 2247, "text": "\nRun Example »\n" }, { "code": null, "e": 2404, "s": 2263, "text": "To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:" }, { "code": null, "e": 2455, "s": 2404, "text": "└── root\n └── mypack\n └── MyPackageClass.java\n" }, { "code": null, "e": 2501, "s": 2455, "text": "To create a package, use the package keyword:" }, { "code": null, "e": 2637, "s": 2501, "text": "package mypack;\nclass MyPackageClass {\n public static void main(String[] args) {\n System.out.println(\"This is my package!\");\n }\n}\n" }, { "code": null, "e": 2653, "s": 2637, "text": "\nRun Example »\n" }, { "code": null, "e": 2707, "s": 2653, "text": "Save the file as MyPackageClass.java, and compile it:" }, { "code": null, "e": 2733, "s": 2707, "text": "Then compile the package:" }, { "code": null, "e": 2790, "s": 2733, "text": "This forces the compiler to create the \"mypack\" package." }, { "code": null, "e": 3050, "s": 2790, "text": "The -d keyword specifies the destination for where to save the class file. You \n can use any directory name, like c:/user (windows), or, if you want to keep \n the package within the same directory, you can use the dot sign \".\", like in \n the example above." }, { "code": null, "e": 3141, "s": 3050, "text": "Note: The package name should be written in lower case to avoid conflict with class names." }, { "code": null, "e": 3235, "s": 3141, "text": "When we compiled the package in the example above, a new folder was created, called \"mypack\"." }, { "code": null, "e": 3293, "s": 3235, "text": "To run the MyPackageClass.java file, write the following:" }, { "code": null, "e": 3313, "s": 3293, "text": "The output will be:" }, { "code": null, "e": 3346, "s": 3313, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3388, "s": 3346, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3495, "s": 3388, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3514, "s": 3495, "text": "[email protected]" } ]
ReactJS MDBootstrap Switch Component - GeeksforGeeks
07 Jan, 2022 MDBootstrap is a Material Design and bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component. In this article, we will know how to use Switch Component in ReactJS MDBootstrap.The switch component is used to indicate the on/off state of the component. Properties: className: It is used to add a custom class to the component. disabled: It is used to make the component disabled. name: It is used to specify the name for the component. id: It is used to define an id for the component. label: It is used to define a label text for the component. labeled: It is used to define an id for the label. labelClass: It is used to add custom classes to the label. Syntax: <MDBSwitch /> Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: Install ReactJS MDBootstrap in your given directory. npm i mdb-ui-kit npm i mdb-react-ui-kit Step 4: Import the element to be used in the project. import { MDBSwitch } from 'mdb-react-ui-kit' Project Structure: It will look like the following. Step to Run Application: Run the application from the root directory of the project, using the following command. npm start Example 1: this is the basic example that shows how to use Switch Component. App.js import React from "react";import { MDBSwitch } from 'mdb-react-ui-kit'; export default function App() { return ( <div id="gfg"> <h2>GeeksforGeeks</h2> <h4>ReactJS MDBootstrap Switch component</h4> <MDBSwitch label='Switch 1' /> <br /> <MDBSwitch defaultChecked label='Switch 2' /> <br /> </div> );} Output: Example 2: In this example, we will know how to use disabled property in a Switch component. App.js import React from "react";import { MDBSwitch } from 'mdb-react-ui-kit'; export default function App() { return ( <div id="gfg"> <h2>GeeksforGeeks</h2> <h4>ReactJS MDBootstrap Switch component</h4> <MDBSwitch disabled label='Switch 1' /> <br /> <MDBSwitch disabled defaultChecked label='Switch 2' /> <br /> </div> );} Output: Reference: https://mdbootstrap.com/docs/b5/react/forms/switch/ MDBootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to navigate on path by button click in react router ? How to create a table in ReactJS ? How to check the version of ReactJS ? Explain the purpose of render() in ReactJS How to set background images in ReactJS ? Express.js express.Router() Function How to set input type date in dd-mm-yyyy format using HTML ? Installation of Node.js on Linux Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24397, "s": 24369, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24712, "s": 24397, "text": "MDBootstrap is a Material Design and bootstrap-based react UI library that is used to make good-looking webpages with its seamless and easy-to-use component. In this article, we will know how to use Switch Component in ReactJS MDBootstrap.The switch component is used to indicate the on/off state of the component." }, { "code": null, "e": 24727, "s": 24714, "text": "Properties: " }, { "code": null, "e": 24789, "s": 24727, "text": "className: It is used to add a custom class to the component." }, { "code": null, "e": 24842, "s": 24789, "text": "disabled: It is used to make the component disabled." }, { "code": null, "e": 24898, "s": 24842, "text": "name: It is used to specify the name for the component." }, { "code": null, "e": 24948, "s": 24898, "text": "id: It is used to define an id for the component." }, { "code": null, "e": 25008, "s": 24948, "text": "label: It is used to define a label text for the component." }, { "code": null, "e": 25059, "s": 25008, "text": "labeled: It is used to define an id for the label." }, { "code": null, "e": 25118, "s": 25059, "text": "labelClass: It is used to add custom classes to the label." }, { "code": null, "e": 25128, "s": 25120, "text": "Syntax:" }, { "code": null, "e": 25142, "s": 25128, "text": "<MDBSwitch />" }, { "code": null, "e": 25192, "s": 25142, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25256, "s": 25192, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 25288, "s": 25256, "text": "npx create-react-app foldername" }, { "code": null, "e": 25388, "s": 25288, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 25402, "s": 25388, "text": "cd foldername" }, { "code": null, "e": 25463, "s": 25402, "text": "Step 3: Install ReactJS MDBootstrap in your given directory." }, { "code": null, "e": 25503, "s": 25463, "text": "npm i mdb-ui-kit\nnpm i mdb-react-ui-kit" }, { "code": null, "e": 25557, "s": 25503, "text": "Step 4: Import the element to be used in the project." }, { "code": null, "e": 25602, "s": 25557, "text": "import { MDBSwitch } from 'mdb-react-ui-kit'" }, { "code": null, "e": 25654, "s": 25602, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25768, "s": 25654, "text": "Step to Run Application: Run the application from the root directory of the project, using the following command." }, { "code": null, "e": 25778, "s": 25768, "text": "npm start" }, { "code": null, "e": 25855, "s": 25778, "text": "Example 1: this is the basic example that shows how to use Switch Component." }, { "code": null, "e": 25862, "s": 25855, "text": "App.js" }, { "code": "import React from \"react\";import { MDBSwitch } from 'mdb-react-ui-kit'; export default function App() { return ( <div id=\"gfg\"> <h2>GeeksforGeeks</h2> <h4>ReactJS MDBootstrap Switch component</h4> <MDBSwitch label='Switch 1' /> <br /> <MDBSwitch defaultChecked label='Switch 2' /> <br /> </div> );}", "e": 26250, "s": 25862, "text": null }, { "code": null, "e": 26258, "s": 26250, "text": "Output:" }, { "code": null, "e": 26351, "s": 26258, "text": "Example 2: In this example, we will know how to use disabled property in a Switch component." }, { "code": null, "e": 26358, "s": 26351, "text": "App.js" }, { "code": "import React from \"react\";import { MDBSwitch } from 'mdb-react-ui-kit'; export default function App() { return ( <div id=\"gfg\"> <h2>GeeksforGeeks</h2> <h4>ReactJS MDBootstrap Switch component</h4> <MDBSwitch disabled label='Switch 1' /> <br /> <MDBSwitch disabled defaultChecked label='Switch 2' /> <br /> </div> );}", "e": 26780, "s": 26358, "text": null }, { "code": null, "e": 26788, "s": 26780, "text": "Output:" }, { "code": null, "e": 26851, "s": 26788, "text": "Reference: https://mdbootstrap.com/docs/b5/react/forms/switch/" }, { "code": null, "e": 26863, "s": 26851, "text": "MDBootstrap" }, { "code": null, "e": 26871, "s": 26863, "text": "ReactJS" }, { "code": null, "e": 26888, "s": 26871, "text": "Web Technologies" }, { "code": null, "e": 26986, "s": 26888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26995, "s": 26986, "text": "Comments" }, { "code": null, "e": 27008, "s": 26995, "text": "Old Comments" }, { "code": null, "e": 27066, "s": 27008, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27101, "s": 27066, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27139, "s": 27101, "text": "How to check the version of ReactJS ?" }, { "code": null, "e": 27182, "s": 27139, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 27224, "s": 27182, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27261, "s": 27224, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27322, "s": 27261, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27355, "s": 27322, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27427, "s": 27355, "text": "Differences between Functional Components and Class Components in React" } ]
How to sort a list alphabetically using jQuery ? - GeeksforGeeks
29 May, 2019 Given a list of elements, The task is to sort them alphabetically and put each element in the list with the help of jQuery. jQuery text() Method: This method set/return the text content of the selected elements. If this method is used to return content, it provides the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it replace the content of all matched elements.Syntax:Return the text content:$(selector).text()Set the text content:$(selector).text(content)Set text content using a function:$(selector).text(function(index, curContent))Parameters:content: It is required parameter. It specifies the new text content for the selected elements.function(index, curContent): It is optional parameter. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements. Syntax: Return the text content:$(selector).text() $(selector).text() Set the text content:$(selector).text(content) $(selector).text(content) Set text content using a function:$(selector).text(function(index, curContent)) $(selector).text(function(index, curContent)) Parameters: content: It is required parameter. It specifies the new text content for the selected elements. function(index, curContent): It is optional parameter. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements. index: It returns the index position of the element in the set. curContent: It returns current content of selected elements. JavaScript String toUpperCase() Method: This method converts a string to uppercase letters.Syntax:string.toUpperCase()Return Value: It returns a string, representing the value of a string converted to uppercase. Syntax: string.toUpperCase() Return Value: It returns a string, representing the value of a string converted to uppercase. jQuery appendTo() Method: This method adds HTML elements at the end of the selected elements.Syntax:$(content).appendTo(selector)Parameters:content: It is required parameter. It specifies the content to insert (must contain HTML tags).selector: It is required parameter. It specifies on which elements to append the content. Syntax: $(content).appendTo(selector) Parameters: content: It is required parameter. It specifies the content to insert (must contain HTML tags). selector: It is required parameter. It specifies on which elements to append the content. Example 1: In this example, first the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using appendTo() method in sorted manner. <!DOCTYPE HTML> <html> <head> <title> Sort a list alphabetically </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body> <h1 style = "text-align:center; color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "text-align:center; font-size: 15px; font-weight: bold;"> click on the button to sort the list </p> <ul> <li>Geeks</li> <li>For</li> <li>GFG</li> <li>GeeksForGeeks</li> </ul> <br> <center> <button> click here </button> </center> <p id = "GFG_DOWN" style = "text-align:center; color:green; font-size:20px; font-weight:bold;"> </p> <script> function Ascending_sort(a, b) { return ($(b).text().toUpperCase()) < ($(a).text().toUpperCase()) ? 1 : -1; } $('button').on('click', function() { $("ul li").sort(Ascending_sort).appendTo('ul'); $("#GFG_DOWN").text("sorted"); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, First the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using appendTo() method in sorted manner. This example uses the same method as in the first example but with a different approach. <!DOCTYPE HTML> <html> <head> <title> Sort a list alphabetically </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body> <h1 style = "text-align:center; color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "text-align:center; font-size: 15px; font-weight: bold;"> click on the button to sort the list </p> <ul class="mylist"> <li>a</li> <li>c</li> <li>b</li> <li>B</li> </ul> <br> <center> <button> click here </button> </center> <p id = "GFG_DOWN" style = "text-align:center; color:green; font-size:20px; font-weight:bold;"> </p> <script> function sort(selector) { $(selector).children("li").sort(function(a, b) { var A = $(a).text().toUpperCase(); var B = $(b).text().toUpperCase(); return (A < B) ? -1 : (A > B) ? 1 : 0; }).appendTo(selector); } $('button').on('click', function() { sort("ul.mylist"); $("#GFG_DOWN").text("sorted"); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25067, "s": 25039, "text": "\n29 May, 2019" }, { "code": null, "e": 25191, "s": 25067, "text": "Given a list of elements, The task is to sort them alphabetically and put each element in the list with the help of jQuery." }, { "code": null, "e": 26032, "s": 25191, "text": "jQuery text() Method: This method set/return the text content of the selected elements. If this method is used to return content, it provides the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it replace the content of all matched elements.Syntax:Return the text content:$(selector).text()Set the text content:$(selector).text(content)Set text content using a function:$(selector).text(function(index, curContent))Parameters:content: It is required parameter. It specifies the new text content for the selected elements.function(index, curContent): It is optional parameter. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements." }, { "code": null, "e": 26040, "s": 26032, "text": "Syntax:" }, { "code": null, "e": 26083, "s": 26040, "text": "Return the text content:$(selector).text()" }, { "code": null, "e": 26102, "s": 26083, "text": "$(selector).text()" }, { "code": null, "e": 26149, "s": 26102, "text": "Set the text content:$(selector).text(content)" }, { "code": null, "e": 26175, "s": 26149, "text": "$(selector).text(content)" }, { "code": null, "e": 26255, "s": 26175, "text": "Set text content using a function:$(selector).text(function(index, curContent))" }, { "code": null, "e": 26301, "s": 26255, "text": "$(selector).text(function(index, curContent))" }, { "code": null, "e": 26313, "s": 26301, "text": "Parameters:" }, { "code": null, "e": 26409, "s": 26313, "text": "content: It is required parameter. It specifies the new text content for the selected elements." }, { "code": null, "e": 26672, "s": 26409, "text": "function(index, curContent): It is optional parameter. It specifies a function that returns the new text content for the selected elements.index: It returns the index position of the element in the set.curContent: It returns current content of selected elements." }, { "code": null, "e": 26736, "s": 26672, "text": "index: It returns the index position of the element in the set." }, { "code": null, "e": 26797, "s": 26736, "text": "curContent: It returns current content of selected elements." }, { "code": null, "e": 27009, "s": 26797, "text": "JavaScript String toUpperCase() Method: This method converts a string to uppercase letters.Syntax:string.toUpperCase()Return Value: It returns a string, representing the value of a string converted to uppercase." }, { "code": null, "e": 27017, "s": 27009, "text": "Syntax:" }, { "code": null, "e": 27038, "s": 27017, "text": "string.toUpperCase()" }, { "code": null, "e": 27132, "s": 27038, "text": "Return Value: It returns a string, representing the value of a string converted to uppercase." }, { "code": null, "e": 27457, "s": 27132, "text": "jQuery appendTo() Method: This method adds HTML elements at the end of the selected elements.Syntax:$(content).appendTo(selector)Parameters:content: It is required parameter. It specifies the content to insert (must contain HTML tags).selector: It is required parameter. It specifies on which elements to append the content." }, { "code": null, "e": 27465, "s": 27457, "text": "Syntax:" }, { "code": null, "e": 27495, "s": 27465, "text": "$(content).appendTo(selector)" }, { "code": null, "e": 27507, "s": 27495, "text": "Parameters:" }, { "code": null, "e": 27603, "s": 27507, "text": "content: It is required parameter. It specifies the content to insert (must contain HTML tags)." }, { "code": null, "e": 27693, "s": 27603, "text": "selector: It is required parameter. It specifies on which elements to append the content." }, { "code": null, "e": 27897, "s": 27693, "text": "Example 1: In this example, first the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using appendTo() method in sorted manner." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Sort a list alphabetically </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body> <h1 style = \"text-align:center; color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"text-align:center; font-size: 15px; font-weight: bold;\"> click on the button to sort the list </p> <ul> <li>Geeks</li> <li>For</li> <li>GFG</li> <li>GeeksForGeeks</li> </ul> <br> <center> <button> click here </button> </center> <p id = \"GFG_DOWN\" style = \"text-align:center; color:green; font-size:20px; font-weight:bold;\"> </p> <script> function Ascending_sort(a, b) { return ($(b).text().toUpperCase()) < ($(a).text().toUpperCase()) ? 1 : -1; } $('button').on('click', function() { $(\"ul li\").sort(Ascending_sort).appendTo('ul'); $(\"#GFG_DOWN\").text(\"sorted\"); }); </script> </body> </html> ", "e": 29254, "s": 27897, "text": null }, { "code": null, "e": 29262, "s": 29254, "text": "Output:" }, { "code": null, "e": 29293, "s": 29262, "text": "Before clicking on the button:" }, { "code": null, "e": 29323, "s": 29293, "text": "After clicking on the button:" }, { "code": null, "e": 29616, "s": 29323, "text": "Example 2: In this example, First the list elements are selected and then passed to a function for sorting. After sorting they are appended to the Parent element using appendTo() method in sorted manner. This example uses the same method as in the first example but with a different approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Sort a list alphabetically </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body> <h1 style = \"text-align:center; color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"text-align:center; font-size: 15px; font-weight: bold;\"> click on the button to sort the list </p> <ul class=\"mylist\"> <li>a</li> <li>c</li> <li>b</li> <li>B</li> </ul> <br> <center> <button> click here </button> </center> <p id = \"GFG_DOWN\" style = \"text-align:center; color:green; font-size:20px; font-weight:bold;\"> </p> <script> function sort(selector) { $(selector).children(\"li\").sort(function(a, b) { var A = $(a).text().toUpperCase(); var B = $(b).text().toUpperCase(); return (A < B) ? -1 : (A > B) ? 1 : 0; }).appendTo(selector); } $('button').on('click', function() { sort(\"ul.mylist\"); $(\"#GFG_DOWN\").text(\"sorted\"); }); </script> </body> </html> ", "e": 31103, "s": 29616, "text": null }, { "code": null, "e": 31111, "s": 31103, "text": "Output:" }, { "code": null, "e": 31142, "s": 31111, "text": "Before clicking on the button:" }, { "code": null, "e": 31172, "s": 31142, "text": "After clicking on the button:" }, { "code": null, "e": 31183, "s": 31172, "text": "JavaScript" }, { "code": null, "e": 31200, "s": 31183, "text": "Web Technologies" }, { "code": null, "e": 31227, "s": 31200, "text": "Web technologies Questions" }, { "code": null, "e": 31325, "s": 31227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31334, "s": 31325, "text": "Comments" }, { "code": null, "e": 31347, "s": 31334, "text": "Old Comments" }, { "code": null, "e": 31408, "s": 31347, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31453, "s": 31408, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31525, "s": 31453, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31577, "s": 31525, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31623, "s": 31577, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31679, "s": 31623, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31712, "s": 31679, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31774, "s": 31712, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31817, "s": 31774, "text": "How to fetch data from an API in ReactJS ?" } ]
How to change the target of a link in HTML?
To change the target of a link in HTML, use the target attribute of the <a>...</a> tag. The target attribute can be used to open any link in a new tab, or the same tab, etc. Here are the values of the target attribute: You can try to run the following code to change the target of a link in HTML. We will set it to open in a new tab Live Demo <!DOCTYPE html> <html> <head> <title>HTML link target</title> </head> <body> <h2>References</h2> <p> Refer the following <a href="https://www.qries.com/questions.php" target="_blank">website</a>. The above link will open in a new tab. </p> </body> </html>
[ { "code": null, "e": 1236, "s": 1062, "text": "To change the target of a link in HTML, use the target attribute of the <a>...</a> tag. The target attribute can be used to open any link in a new tab, or the same tab, etc." }, { "code": null, "e": 1281, "s": 1236, "text": "Here are the values of the target attribute:" }, { "code": null, "e": 1395, "s": 1281, "text": "You can try to run the following code to change the target of a link in HTML. We will set it to open in a new tab" }, { "code": null, "e": 1405, "s": 1395, "text": "Live Demo" }, { "code": null, "e": 1727, "s": 1405, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML link target</title>\n </head>\n <body>\n <h2>References</h2>\n <p>\n Refer the following <a href=\"https://www.qries.com/questions.php\"\n target=\"_blank\">website</a>.\n The above link will open in a new tab.\n </p>\n </body>\n</html>" } ]
How to convert a string to a Python class object?
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. class Foobar: pass print eval("Foobar") print type(Foobar) __main__.Foobar <type 'classobj'> Another way to convert a string to class object is as follows import sys class Foobar: pass def str_to_class(str): return getattr(sys.modules[__name__], str) print str_to_class("Foobar") print type(Foobar) __main__.Foobar <type 'classobj'>
[ { "code": null, "e": 1224, "s": 1062, "text": "Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace." }, { "code": null, "e": 1287, "s": 1224, "text": "class Foobar:\n pass\nprint eval(\"Foobar\")\nprint type(Foobar)" }, { "code": null, "e": 1324, "s": 1287, "text": " __main__.Foobar\n<type 'classobj'>\n\n" }, { "code": null, "e": 1386, "s": 1324, "text": "Another way to convert a string to class object is as follows" }, { "code": null, "e": 1538, "s": 1386, "text": "import sys\nclass Foobar:\n pass\ndef str_to_class(str):\n return getattr(sys.modules[__name__], str)\nprint str_to_class(\"Foobar\")\nprint type(Foobar)" }, { "code": null, "e": 1574, "s": 1538, "text": "__main__.Foobar\n<type 'classobj'>\n\n" } ]
Test if a function throws an exception in Python - GeeksforGeeks
20 Aug, 2020 The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: test fixture test case test suite test runner A deeper insight for the above terms can be gained from https://www.geeksforgeeks.org/unit-testing-python-unittest/ assertRaises() – It allows an exception to be encapsulated, meaning that the test can throw an exception without exiting the execution, as is normally the case for unhandled exceptions. The test passes if exception is raised, gives an error if another exception is raised, or fails if no exception is raised. There are two ways you can use assertRaises: using keyword arguments.assertRaises(exception, function, *args, **keywords) Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception.using context manager assertRaises(exception) Make a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised. using keyword arguments.assertRaises(exception, function, *args, **keywords) Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. assertRaises(exception, function, *args, **keywords) Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. using context manager assertRaises(exception) Make a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised. assertRaises(exception) Make a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised. We write a unittest that fails if no exception is raised by a function or when an exception raised by assert statement is different from expected exception. Thus, by this method we can check if an exception is raised by a function or not. Example 1 : Python3 import unittest class MyTestCase(unittest.TestCase): # Returns true if 1 + '1' raises a TypeError def test_1(self): with self.assertRaises(Exception): 1 + '1' if __name__ == '__main__': unittest.main() Output : . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Here, in the output the “.” on the first line of output means that test has passed and the function has thrown an exception of TypeError while adding an integer value and a string value. Example 2 : Python3 import unittest class MyTestCase(unittest.TestCase): # Returns false if 1 + 1 raises no Exception def test_1(self): with self.assertRaises(Exception): 1 + 1 if __name__ == '__main__': unittest.main() Output : F ====================================================================== FAIL: test_1 (__main__.MyTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/5bc65171e57a3294596f5333f4b7ed53.py", line 6, in test_1 1 + 1 AssertionError: Exception not raised ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) Since adding an integer to an integer (in this case 1 + 1) does not raise any exception, results in the unittest to fail. Example 3 : Python3 import unittest class MyTestCase(unittest.TestCase): # Returns true if 100 / 0 raises an Exception def test_1(self): with self.assertRaises(ZeroDivisionError): 100 / 0 if __name__ == '__main__': unittest.main() Output : . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Any number divided by 0 gives ZeroDivisionError exception. Therefore, in example 3, when 100 is divided by 0 it raises an Exception of type ZeroDivisionError resulting in unittest to pass. Thus “.” in output signifies that the test has been passed. Example 4 : Python3 import unittest class MyTestCase(unittest.TestCase): # Returns true if GeeksforGeeks.txt file is not present and raises an EnvironmentError # Exception # In this example expected exception is RuntimeError while generated exception is # EnvironmentError, thus returns false def test_1(self): with self.assertRaises(RuntimeError): file = open("GeeksforGeeks.txt", 'r') if __name__ == '__main__': unittest.main() Output : E ====================================================================== ERROR: test_1 (__main__.MyTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/8520c06939bb0023b4f76f381b2c8cf2.py", line 11, in test_1 file = open("GeeksforGeeks.txt", 'r') FileNotFoundError: [Errno 2] No such file or directory: 'GeeksforGeeks.txt' ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) When we try to open a file that does not exists, it raises an IOError which is sub class of EnvironmentError. In the above example, the unittest failed because the type of exception to be raised by function was expected to be of type RuntimeError, instead it raised an exception of EnvironmentError. Since the exception raised and exception expected are different, it produces an error. Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24173, "s": 24145, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24352, "s": 24173, "text": "The unittest unit testing framework is used to validate that the code performs as designed. To achieve this, unittest supports some important methods in an object-oriented way: " }, { "code": null, "e": 24365, "s": 24352, "text": "test fixture" }, { "code": null, "e": 24375, "s": 24365, "text": "test case" }, { "code": null, "e": 24386, "s": 24375, "text": "test suite" }, { "code": null, "e": 24398, "s": 24386, "text": "test runner" }, { "code": null, "e": 24514, "s": 24398, "text": "A deeper insight for the above terms can be gained from https://www.geeksforgeeks.org/unit-testing-python-unittest/" }, { "code": null, "e": 24823, "s": 24514, "text": "assertRaises() – It allows an exception to be encapsulated, meaning that the test can throw an exception without exiting the execution, as is normally the case for unhandled exceptions. The test passes if exception is raised, gives an error if another exception is raised, or fails if no exception is raised." }, { "code": null, "e": 24868, "s": 24823, "text": "There are two ways you can use assertRaises:" }, { "code": null, "e": 25385, "s": 24868, "text": "using keyword arguments.assertRaises(exception, function, *args, **keywords)\nJust pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception.using context manager assertRaises(exception)\nMake a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised." }, { "code": null, "e": 25606, "s": 25385, "text": "using keyword arguments.assertRaises(exception, function, *args, **keywords)\nJust pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception." }, { "code": null, "e": 25660, "s": 25606, "text": "assertRaises(exception, function, *args, **keywords)\n" }, { "code": null, "e": 25804, "s": 25660, "text": "Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception." }, { "code": null, "e": 26101, "s": 25804, "text": "using context manager assertRaises(exception)\nMake a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised." }, { "code": null, "e": 26126, "s": 26101, "text": "assertRaises(exception)\n" }, { "code": null, "e": 26377, "s": 26126, "text": "Make a function call that should raise the exception with a context. The context manager will caught an exception and store it in the object in its exception attribute. This is useful when we have to perform additional checks on the exception raised." }, { "code": null, "e": 26616, "s": 26377, "text": "We write a unittest that fails if no exception is raised by a function or when an exception raised by assert statement is different from expected exception. Thus, by this method we can check if an exception is raised by a function or not." }, { "code": null, "e": 26628, "s": 26616, "text": "Example 1 :" }, { "code": null, "e": 26636, "s": 26628, "text": "Python3" }, { "code": "import unittest class MyTestCase(unittest.TestCase): # Returns true if 1 + '1' raises a TypeError def test_1(self): with self.assertRaises(Exception): 1 + '1' if __name__ == '__main__': unittest.main()", "e": 26863, "s": 26636, "text": null }, { "code": null, "e": 26873, "s": 26863, "text": "Output : " }, { "code": null, "e": 26971, "s": 26873, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK" }, { "code": null, "e": 27159, "s": 26971, "text": "Here, in the output the “.” on the first line of output means that test has passed and the function has thrown an exception of TypeError while adding an integer value and a string value." }, { "code": null, "e": 27171, "s": 27159, "text": "Example 2 :" }, { "code": null, "e": 27179, "s": 27171, "text": "Python3" }, { "code": "import unittest class MyTestCase(unittest.TestCase): # Returns false if 1 + 1 raises no Exception def test_1(self): with self.assertRaises(Exception): 1 + 1 if __name__ == '__main__': unittest.main()", "e": 27404, "s": 27179, "text": null }, { "code": null, "e": 27414, "s": 27404, "text": "Output : " }, { "code": null, "e": 27859, "s": 27414, "text": "F\n======================================================================\nFAIL: test_1 (__main__.MyTestCase)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/5bc65171e57a3294596f5333f4b7ed53.py\", line 6, in test_1\n 1 + 1\nAssertionError: Exception not raised\n\n----------------------------------------------------------------------\nRan 1 test in 0.001s\n\nFAILED (failures=1)" }, { "code": null, "e": 27982, "s": 27859, "text": "Since adding an integer to an integer (in this case 1 + 1) does not raise any exception, results in the unittest to fail." }, { "code": null, "e": 27994, "s": 27982, "text": "Example 3 :" }, { "code": null, "e": 28002, "s": 27994, "text": "Python3" }, { "code": "import unittest class MyTestCase(unittest.TestCase): # Returns true if 100 / 0 raises an Exception def test_1(self): with self.assertRaises(ZeroDivisionError): 100 / 0 if __name__ == '__main__': unittest.main()", "e": 28237, "s": 28002, "text": null }, { "code": null, "e": 28246, "s": 28237, "text": "Output :" }, { "code": null, "e": 28344, "s": 28246, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK" }, { "code": null, "e": 28593, "s": 28344, "text": "Any number divided by 0 gives ZeroDivisionError exception. Therefore, in example 3, when 100 is divided by 0 it raises an Exception of type ZeroDivisionError resulting in unittest to pass. Thus “.” in output signifies that the test has been passed." }, { "code": null, "e": 28605, "s": 28593, "text": "Example 4 :" }, { "code": null, "e": 28613, "s": 28605, "text": "Python3" }, { "code": "import unittest class MyTestCase(unittest.TestCase): # Returns true if GeeksforGeeks.txt file is not present and raises an EnvironmentError # Exception # In this example expected exception is RuntimeError while generated exception is # EnvironmentError, thus returns false def test_1(self): with self.assertRaises(RuntimeError): file = open(\"GeeksforGeeks.txt\", 'r') if __name__ == '__main__': unittest.main()", "e": 29055, "s": 28613, "text": null }, { "code": null, "e": 29064, "s": 29055, "text": "Output :" }, { "code": null, "e": 29580, "s": 29064, "text": "E\n======================================================================\nERROR: test_1 (__main__.MyTestCase)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/8520c06939bb0023b4f76f381b2c8cf2.py\", line 11, in test_1\n file = open(\"GeeksforGeeks.txt\", 'r')\nFileNotFoundError: [Errno 2] No such file or directory: 'GeeksforGeeks.txt'\n\n----------------------------------------------------------------------\nRan 1 test in 0.001s\n\nFAILED (errors=1)" }, { "code": null, "e": 29967, "s": 29580, "text": "When we try to open a file that does not exists, it raises an IOError which is sub class of EnvironmentError. In the above example, the unittest failed because the type of exception to be raised by function was expected to be of type RuntimeError, instead it raised an exception of EnvironmentError. Since the exception raised and exception expected are different, it produces an error." }, { "code": null, "e": 29985, "s": 29967, "text": "Python-exceptions" }, { "code": null, "e": 29992, "s": 29985, "text": "Python" }, { "code": null, "e": 30090, "s": 29992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30099, "s": 30090, "text": "Comments" }, { "code": null, "e": 30112, "s": 30099, "text": "Old Comments" }, { "code": null, "e": 30130, "s": 30112, "text": "Python Dictionary" }, { "code": null, "e": 30165, "s": 30130, "text": "Read a file line by line in Python" }, { "code": null, "e": 30187, "s": 30165, "text": "Enumerate() in Python" }, { "code": null, "e": 30219, "s": 30187, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30249, "s": 30219, "text": "Iterate over a list in Python" }, { "code": null, "e": 30291, "s": 30249, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30334, "s": 30291, "text": "Python program to convert a list to string" }, { "code": null, "e": 30360, "s": 30334, "text": "Python String | replace()" }, { "code": null, "e": 30404, "s": 30360, "text": "Reading and Writing to text files in Python" } ]
What are union, intersect and except operators in Linq C#?
Union combines multiple collections into a single collection and returns a resultant collection with unique elements Intersect returns sequence elements which are common in both the input sequences Except returns sequence elements from the first input sequence that are not present in the second input sequence class Program{ static void Main(){ int[] count1 = { 1, 2, 3, 4 }; int[] count2 = { 2, 4, 7 }; var resultUnion = count1.Union(count2); var resultIntersect = count1.Intersect(count2); var resultExcept = count1.Except(count2); System.Console.WriteLine("Union"); foreach (var item in resultUnion){ Console.WriteLine(item); } System.Console.WriteLine("Intersect"); foreach (var item in resultIntersect){ Console.WriteLine(item); } System.Console.WriteLine("Except"); foreach (var item in resultExcept){ Console.WriteLine(item); } Console.ReadKey(); } } Union 1 2 3 4 7 Intersect 2 4 Except 1 3
[ { "code": null, "e": 1179, "s": 1062, "text": "Union combines multiple collections into a single collection and returns a resultant collection with unique elements" }, { "code": null, "e": 1260, "s": 1179, "text": "Intersect returns sequence elements which are common in both the input sequences" }, { "code": null, "e": 1373, "s": 1260, "text": "Except returns sequence elements from the first input sequence that are not present in the second input sequence" }, { "code": null, "e": 2044, "s": 1373, "text": "class Program{\n static void Main(){\n int[] count1 = { 1, 2, 3, 4 };\n int[] count2 = { 2, 4, 7 };\n var resultUnion = count1.Union(count2);\n var resultIntersect = count1.Intersect(count2);\n var resultExcept = count1.Except(count2);\n System.Console.WriteLine(\"Union\");\n foreach (var item in resultUnion){\n Console.WriteLine(item);\n }\n System.Console.WriteLine(\"Intersect\");\n foreach (var item in resultIntersect){\n Console.WriteLine(item);\n }\n System.Console.WriteLine(\"Except\");\n foreach (var item in resultExcept){\n Console.WriteLine(item);\n }\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2085, "s": 2044, "text": "Union\n1\n2\n3\n4\n7\nIntersect\n2\n4\nExcept\n1\n3" } ]
C# - Nested Loops
C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. The syntax for a nested for loop statement in C# is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement in C# is as follows − while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do...while loop statement in C# is as follows − do { statement(s); do { statement(s); } while( condition ); } while( condition ); A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa. The following program uses a nested for loop to find the prime numbers from 2 to 100 − using System; namespace Loops { class Program { static void Main(string[] args) { /* local variable definition */ int i, j; for (i = 2; i < 100; i++) { for (j = 2; j <= (i / j); j++) if ((i % j) == 0) break; // if factor found, not prime if (j > (i / j)) Console.WriteLine("{0} is prime", i); } Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2270, "text": "C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept." }, { "code": null, "e": 2446, "s": 2381, "text": "The syntax for a nested for loop statement in C# is as follows −" }, { "code": null, "e": 2568, "s": 2446, "text": "for ( init; condition; increment ) {\n for ( init; condition; increment ) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2635, "s": 2568, "text": "The syntax for a nested while loop statement in C# is as follows −" }, { "code": null, "e": 2721, "s": 2635, "text": "while(condition) {\n while(condition) {\n statement(s);\n }\n statement(s);\n}\n" }, { "code": null, "e": 2793, "s": 2721, "text": "The syntax for a nested do...while loop statement in C# is as follows −" }, { "code": null, "e": 2894, "s": 2793, "text": "do {\n statement(s);\n do {\n statement(s);\n }\n while( condition );\n}\nwhile( condition );\n" }, { "code": null, "e": 3059, "s": 2894, "text": "A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa." }, { "code": null, "e": 3146, "s": 3059, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 100 −" }, { "code": null, "e": 3578, "s": 3146, "text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int i, j;\n \n for (i = 2; i < 100; i++) {\n for (j = 2; j <= (i / j); j++)\n if ((i % j) == 0) break; // if factor found, not prime\n if (j > (i / j)) Console.WriteLine(\"{0} is prime\", i);\n }\n Console.ReadLine();\n }\n }\n} " }, { "code": null, "e": 3659, "s": 3578, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3956, "s": 3659, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 3993, "s": 3956, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 4006, "s": 3993, "text": " Raja Biswas" }, { "code": null, "e": 4040, "s": 4006, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 4058, "s": 4040, "text": " Trevoir Williams" }, { "code": null, "e": 4091, "s": 4058, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4105, "s": 4091, "text": " Peter Jepson" }, { "code": null, "e": 4142, "s": 4105, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 4157, "s": 4142, "text": " Ebenezer Ogbu" }, { "code": null, "e": 4192, "s": 4157, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 4207, "s": 4192, "text": " Arnold Higuit" }, { "code": null, "e": 4242, "s": 4207, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4254, "s": 4242, "text": " Eric Frick" }, { "code": null, "e": 4261, "s": 4254, "text": " Print" }, { "code": null, "e": 4272, "s": 4261, "text": " Add Notes" } ]
New '=' Operator in Python3.8 f-string - GeeksforGeeks
03 Jun, 2020 Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in place of expr. Syntax : f'{expr=}'Return : Return the formatted string. Note: For older versions of Python this operator will raise the syntax error. See the below image. Example #1 :In this example we can see that with the help of f'{expr=}' expression, we are able to format strings in python by self documenting expressions by using = operator. length = len('GeeksForGeeks') # Using f'{expr =}' expressiongfg = f'The length of GeeksForGeeks is {length =}.' print(gfg) Output : The length of GeeksForGeeks is length=13. Example #2 : a, b = 5, 10 # Using f'{expr =}' expressiongfg = f'Value of {b = } and {a = }.' print(gfg) Output : Value of b = 10 and a = 5. python-basics Python-Operators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Jun, 2020" }, { "code": null, "e": 24266, "s": 23901, "text": "Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in place of expr." }, { "code": null, "e": 24323, "s": 24266, "text": "Syntax : f'{expr=}'Return : Return the formatted string." }, { "code": null, "e": 24422, "s": 24323, "text": "Note: For older versions of Python this operator will raise the syntax error. See the below image." }, { "code": null, "e": 24599, "s": 24422, "text": "Example #1 :In this example we can see that with the help of f'{expr=}' expression, we are able to format strings in python by self documenting expressions by using = operator." }, { "code": "length = len('GeeksForGeeks') # Using f'{expr =}' expressiongfg = f'The length of GeeksForGeeks is {length =}.' print(gfg)", "e": 24724, "s": 24599, "text": null }, { "code": null, "e": 24733, "s": 24724, "text": "Output :" }, { "code": null, "e": 24775, "s": 24733, "text": "The length of GeeksForGeeks is length=13." }, { "code": null, "e": 24788, "s": 24775, "text": "Example #2 :" }, { "code": "a, b = 5, 10 # Using f'{expr =}' expressiongfg = f'Value of {b = } and {a = }.' print(gfg)", "e": 24881, "s": 24788, "text": null }, { "code": null, "e": 24890, "s": 24881, "text": "Output :" }, { "code": null, "e": 24917, "s": 24890, "text": "Value of b = 10 and a = 5." }, { "code": null, "e": 24931, "s": 24917, "text": "python-basics" }, { "code": null, "e": 24948, "s": 24931, "text": "Python-Operators" }, { "code": null, "e": 24955, "s": 24948, "text": "Python" }, { "code": null, "e": 25053, "s": 24955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25062, "s": 25053, "text": "Comments" }, { "code": null, "e": 25075, "s": 25062, "text": "Old Comments" }, { "code": null, "e": 25111, "s": 25075, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25134, "s": 25111, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25173, "s": 25134, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25206, "s": 25173, "text": "Python | Convert set into a list" }, { "code": null, "e": 25255, "s": 25206, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25296, "s": 25255, "text": "Python - Call function from another file" }, { "code": null, "e": 25312, "s": 25296, "text": "loops in python" }, { "code": null, "e": 25363, "s": 25312, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25395, "s": 25363, "text": "Python Dictionary keys() method" } ]
Data Scraping and Analysis using Python | by Jasmeet Singh | Towards Data Science
Data Scraping is a technique to retrieve large amounts of data from the internet. This technique is highly useful in competitive pricing. To check what our product’s optimal price should be we can compare the similar products that are already in the market. These prices can vary a lot. So, in this blog, I’m going to show how we can scrap data regarding a particular product. The most common technique for Data Scraping is using BeautifulSoup. It extracts the html for the page and stores it as an unstructured data. We’ll have to convert that into structured format. Let’s import all the necessary libraries that we’ll require: import requestsfrom fake_useragent import UserAgentimport pandas as pdimport bs4 The data that we extract is unstructured data. So we’ll create empty lists to store them in a structured form, products=[] #List to store name of the productprices=[] #List to store price of the productratings=[] #List to store rating of the productspecifications = [] #List to store specifications of the productdf=pd.DataFrame() Creating a user agent. Refer to this link https://pypi.org/project/fake-useragent/ user_agent = UserAgent() Taking the product name as an input. The extracted data will be related to that product. product_name = input("Product Name- ") To extract data from multiple pages of the product listing we’re going to use a for loop. The range will specify the number of pages to be extracted. for i in range(1,11): url = "https://www.flipkart.com/search?q={0}&page={1}" url = url.format(product_name,i) ## getting the reponse from the page using get method of requests module page = requests.get(url, headers={"user-agent": user_agent.chrome}) ## storing the content of the page in a variable html = page.content ## creating BeautifulSoup object page_soup = bs4.BeautifulSoup(html, "html.parser") for containers in page_soup.findAll('div',{'class':'_3liAhj'}): name=containers.find('a', attrs={'class':'_2cLu-l'}) price=containers.find('div', attrs={'class':'_1vC4OE'}) rating=containers.find('div', attrs={'class':'hGSR34'}) specification = containers.find('div', attrs {'class':'_1rcHFq'}) products.append(name.text) prices.append(price.text) specifications.append(specification.text) if type(specification) == bs4.element.Tag else specifications.append('NaN') ratings.append(rating.text) if type(rating) == bs4.element.Tag else ratings.append('NaN') df = pd.DataFrame({'Product Name':products,'Price':prices, 'specification':specifications, 'Rating':ratings}) For extracting data form soup you need to specify the html tags you want to retrieve the data from. You could use inspect element on the webpage. The above code will store the data in a structured format. And when you print the df you'll get: df.head() Since all the products are the same we can write them as ‘bottle’. df['Product Name'] = 'bottle'df.head() Similarly, we could find data for different products. Now, we’ll remove the symbols from Price and clean up the specification column. df[‘Price’] = df[‘Price’].str.lstrip(‘₹’)df[‘Price’] = df[‘Price’].replace({‘,’:’’}, regex=True)df.head() df[‘Pack’], df[‘color’] = df[‘specification’].str.split(‘,’, 1).strdel df[‘specification’]df.head() import numpy as npimport seaborn as snsdf[‘Price’] = df[‘Price’].astype(np.float)sns.boxplot(x=df[‘Price’]) As we can see there are a few outliers where the price range is very high. sns.barplot(x=df[‘Price’], y=df[‘color’]) We can observe how the prices for a particular colour changes. The rows with multiple colours are in packs like pack of 4 or pack of 6 etc. df[‘Rating’] = df[‘Rating’].astype(np.float)sns.barplot(x=df[‘Rating’], y=df[‘color’]) We can also observe that the colour has almost no effect on the ratings of the product. sns.barplot(x=df[‘Rating’], y=df[‘Price’]) sns.lineplot(x=df[‘Rating’], y=df[‘Price’]) We can conclude from here that products with lower price have a higher ratings to some extent. Thank you guys, I hope you got some insights on how we can use data scraping for competitive pricing. You could experiment with different EDA techniques other than mentioned in the Blog.
[ { "code": null, "e": 549, "s": 172, "text": "Data Scraping is a technique to retrieve large amounts of data from the internet. This technique is highly useful in competitive pricing. To check what our product’s optimal price should be we can compare the similar products that are already in the market. These prices can vary a lot. So, in this blog, I’m going to show how we can scrap data regarding a particular product." }, { "code": null, "e": 741, "s": 549, "text": "The most common technique for Data Scraping is using BeautifulSoup. It extracts the html for the page and stores it as an unstructured data. We’ll have to convert that into structured format." }, { "code": null, "e": 802, "s": 741, "text": "Let’s import all the necessary libraries that we’ll require:" }, { "code": null, "e": 883, "s": 802, "text": "import requestsfrom fake_useragent import UserAgentimport pandas as pdimport bs4" }, { "code": null, "e": 994, "s": 883, "text": "The data that we extract is unstructured data. So we’ll create empty lists to store them in a structured form," }, { "code": null, "e": 1214, "s": 994, "text": "products=[] #List to store name of the productprices=[] #List to store price of the productratings=[] #List to store rating of the productspecifications = [] #List to store specifications of the productdf=pd.DataFrame()" }, { "code": null, "e": 1297, "s": 1214, "text": "Creating a user agent. Refer to this link https://pypi.org/project/fake-useragent/" }, { "code": null, "e": 1322, "s": 1297, "text": "user_agent = UserAgent()" }, { "code": null, "e": 1411, "s": 1322, "text": "Taking the product name as an input. The extracted data will be related to that product." }, { "code": null, "e": 1450, "s": 1411, "text": "product_name = input(\"Product Name- \")" }, { "code": null, "e": 1600, "s": 1450, "text": "To extract data from multiple pages of the product listing we’re going to use a for loop. The range will specify the number of pages to be extracted." }, { "code": null, "e": 2758, "s": 1600, "text": "for i in range(1,11): url = \"https://www.flipkart.com/search?q={0}&page={1}\" url = url.format(product_name,i) ## getting the reponse from the page using get method of requests module page = requests.get(url, headers={\"user-agent\": user_agent.chrome}) ## storing the content of the page in a variable html = page.content ## creating BeautifulSoup object page_soup = bs4.BeautifulSoup(html, \"html.parser\") for containers in page_soup.findAll('div',{'class':'_3liAhj'}): name=containers.find('a', attrs={'class':'_2cLu-l'}) price=containers.find('div', attrs={'class':'_1vC4OE'}) rating=containers.find('div', attrs={'class':'hGSR34'}) specification = containers.find('div', attrs {'class':'_1rcHFq'}) products.append(name.text) prices.append(price.text) specifications.append(specification.text) if type(specification) == bs4.element.Tag else specifications.append('NaN') ratings.append(rating.text) if type(rating) == bs4.element.Tag else ratings.append('NaN') df = pd.DataFrame({'Product Name':products,'Price':prices, 'specification':specifications, 'Rating':ratings})" }, { "code": null, "e": 2904, "s": 2758, "text": "For extracting data form soup you need to specify the html tags you want to retrieve the data from. You could use inspect element on the webpage." }, { "code": null, "e": 3001, "s": 2904, "text": "The above code will store the data in a structured format. And when you print the df you'll get:" }, { "code": null, "e": 3011, "s": 3001, "text": "df.head()" }, { "code": null, "e": 3078, "s": 3011, "text": "Since all the products are the same we can write them as ‘bottle’." }, { "code": null, "e": 3117, "s": 3078, "text": "df['Product Name'] = 'bottle'df.head()" }, { "code": null, "e": 3171, "s": 3117, "text": "Similarly, we could find data for different products." }, { "code": null, "e": 3251, "s": 3171, "text": "Now, we’ll remove the symbols from Price and clean up the specification column." }, { "code": null, "e": 3357, "s": 3251, "text": "df[‘Price’] = df[‘Price’].str.lstrip(‘₹’)df[‘Price’] = df[‘Price’].replace({‘,’:’’}, regex=True)df.head()" }, { "code": null, "e": 3457, "s": 3357, "text": "df[‘Pack’], df[‘color’] = df[‘specification’].str.split(‘,’, 1).strdel df[‘specification’]df.head()" }, { "code": null, "e": 3565, "s": 3457, "text": "import numpy as npimport seaborn as snsdf[‘Price’] = df[‘Price’].astype(np.float)sns.boxplot(x=df[‘Price’])" }, { "code": null, "e": 3640, "s": 3565, "text": "As we can see there are a few outliers where the price range is very high." }, { "code": null, "e": 3682, "s": 3640, "text": "sns.barplot(x=df[‘Price’], y=df[‘color’])" }, { "code": null, "e": 3822, "s": 3682, "text": "We can observe how the prices for a particular colour changes. The rows with multiple colours are in packs like pack of 4 or pack of 6 etc." }, { "code": null, "e": 3909, "s": 3822, "text": "df[‘Rating’] = df[‘Rating’].astype(np.float)sns.barplot(x=df[‘Rating’], y=df[‘color’])" }, { "code": null, "e": 3997, "s": 3909, "text": "We can also observe that the colour has almost no effect on the ratings of the product." }, { "code": null, "e": 4040, "s": 3997, "text": "sns.barplot(x=df[‘Rating’], y=df[‘Price’])" }, { "code": null, "e": 4084, "s": 4040, "text": "sns.lineplot(x=df[‘Rating’], y=df[‘Price’])" }, { "code": null, "e": 4179, "s": 4084, "text": "We can conclude from here that products with lower price have a higher ratings to some extent." } ]
Restaurant Revenue Prediction. Developing classical models for... | by Allen Kong | Towards Data Science
Restaurants are an essential part of a country’s economy and society. Whether it may be for social gatherings or a quick bite, most of us have experienced at least one visit. With the recent rise in pop up restaurants and food trucks, it’s imperative for the business owner to figure out when and where to open new restaurants since it takes up a lot of time, effort, and capital to do so. This brings up the problem of finding the best optimal time and place to open a new restaurant. TFI which owns many giant restaurant chains has provided demographic, real estate, and commercial data in their restaurant revenue prediction on Kaggle. The challenge here would be to build a robust model that is capable of predicting the revenue of a restaurant. After taking a look at the data, there are 137 samples in the training set and 100,000 samples in the test set. This is very intriguing since the distribution of data is usually the other way around. The goal here would be to model revenue based on 137 samples in the training set and see how well the model performs on the 100,000 samples in the test set. The data fields for each sample consist of the restaurant ID which is unique for each restaurant in the sample, the opening date of the restaurant, the city, city group, restaurant type, several non-arbitrary P-variables, and revenue which is the target variable. Using a complex model for this small training dataset with noise will cause the model to overfit to the dataset. To prevent that from happening, regularization techniques for linear regression will definitely need to be used. After a brief look at the training data, it appears that there are no null values which is a good thing. However, that may not be the case for the P-variables as we will see later in the data exploration. Type The two figures above show the count of types of restaurants in the training set and test set. Looking carefully, there doesn’t seem to be a single occurrence of the ‘MB’ type in the training set. Type ‘MB’ stands for mobile restaurants and type ‘DT’ stands for drive-thru restaurants. Since mobile restaurants are more related to drive-thru than inline and food courts, the ‘MB’ samples in the test set were replaced with the ‘DT’ type. City Group There doesn’t seem to be any changes required for the city group feature. The training set has slightly more ‘Big Cities’ samples than ‘Other’ samples but that shouldn’t be a problem when we create our model. It should also be intuitive that restaurant revenue in the city than other areas. City (df['City'].nunique(), test_df['City'].nunique())Out[10]: (34, 57) For the ‘City’ feature, it appears that there are cities in the test set that aren’t in the training set. It is also worth noting that some of the non-arbitrary P-variables already contain geolocation information so the entire ‘City’ feature was dropped for both datasets. Open Date import datetimedf.drop('Id',axis=1,inplace=True)df['Open Date'] = pd.to_datetime(df['Open Date'])test_df['Open Date'] = pd.to_datetime(test_df['Open Date'])launch_date = datetime.datetime(2015, 3, 23)# scale days opendf['Days Open'] = (launch_date - df['Open Date']).dt.days / 1000test_df['Days Open'] = (launch_date - test_df['Open Date']).dt.days / 1000df.drop('Open Date', axis=1, inplace=True)test_df.drop('Open Date', axis=1, inplace=True) The opening date is the date the restaurant first opened. It won’t be of much use in terms of predicting revenue but it would be useful to know how long the restaurant has been open since the opening date. For that reason, I decided to use March 23, 2015 as the date of comparison to calculate the amount of days the restaurant has been open. Then, I chose to downscale the number of days open by a factor of 1000 to slightly improve model performance. P-Variables The data has 37 p-variables which are all obfuscated data. These features contain demographic data, real estate data, and commercial data based on the data field description on the Kaggle competition page. Initially, I had thought that the p-variables were numerical features but after reading some of the discussions in the competition, it turns out that some of these features were actually categorical data encoded using integers. What’s even more interesting is that a majority of the values for some of these features are zero. Once again, after digging through the discussions, people concluded that these zero values were actually null values as shown in the plots above. Multivariate imputation by chained equations (also known as MICE) was used to replace the missing values in some of these features. The way it works is that is uses the entire set of available data to estimate the missing values. from sklearn.experimental import enable_iterative_imputerfrom sklearn.impute import IterativeImputerimp_train = IterativeImputer(max_iter=30, missing_values=0, sample_posterior=True, min_value=1, random_state=37)imp_test = IterativeImputer(max_iter=30, missing_values=0, sample_posterior=True, min_value=1, random_state=23)p_data = ['P'+str(i) for i in range(1,38)]df[p_data] = np.round(imp_train.fit_transform(df[p_data]))test_df[p_data] = np.round(imp_test.fit_transform(test_df[p_data])) The imputer was used on all p-variables separately for the training set and the test set. The missing values are estimated several times before the imputer takes the average. Before feeding these averages to the model, they need to be rounded to the nearest integer. One Hot Encoding To deal with object types in the data, one hot encoding will be used to transform these features into numerical form which can be provided to the machine learning models. Dummy encoding can also be used to avoid redundancy. The features that will be encoded are ‘Type’ and ‘City Group’ since they are the only object types in the datasets. columnsToEncode = df.select_dtypes(include=[object]).columnsdf = pd.get_dummies(df, columns=columnsToEncode, drop_first=False)test_df = pd.get_dummies(test_df, columns=columnsToEncode, drop_first=False) Target Variable Distribution Based on the distribution, it looks like revenue is right skewed. There also appears to be outliers which will cause issues in model training. Since we will be experimenting with linear models, the target variable will be transformed to make it normally distributed for improved model interpretation. The target variable was log transformed so the final predictions will need to be exponentiated to rescale the results back to normal. The models that I decided on experimenting with were several different linear models, KNN, random forest and gradient boosted models. The goal here is to find the best hyper-tuned models to ensemble for the final model. Before we train any model, we will split the training set into a training and validation set. df['revenue'] = np.log1p(df['revenue'])X, y = df.drop('revenue', axis=1), df['revenue']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=118) Ridge regression is a regularized linear model. As stated earlier, regularization techniques need to be used to prevent overfitting especially since our training set is very small. Before we train a ridge model on the training, we need to find the optimal parameters for the model. To do this, grid search along with k-fold cross validation was used to find the optimal parameters that led to the best score. params_ridge = { 'alpha' : [.01, .1, .5, .7, .9, .95, .99, 1, 5, 10, 20], 'fit_intercept' : [True, False], 'normalize' : [True,False], 'solver' : ['svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga'] } ridge_model = Ridge() ridge_regressor = GridSearchCV(ridge_model, params_ridge, scoring='neg_root_mean_squared_error', cv=5, n_jobs=-1) ridge_regressor.fit(X_train, y_train) print(f'Optimal alpha: {ridge_regressor.best_params_["alpha"]:.2f}') print(f'Optimal fit_intercept: {ridge_regressor.best_params_["fit_intercept"]}') print(f'Optimal normalize: {ridge_regressor.best_params_["normalize"]}') print(f'Optimal solver: {ridge_regressor.best_params_["solver"]}') print(f'Best score: {ridge_regressor.best_score_}') The optimal parameters are then used for model evaluation using both the training and test sets. The RMSE here is actually RMSLE since we’ve taken the log of the target variable. ridge_model = Ridge(alpha=ridge_regressor.best_params_["alpha"], fit_intercept=ridge_regressor.best_params_["fit_intercept"], normalize=ridge_regressor.best_params_["normalize"], solver=ridge_regressor.best_params_["solver"]) ridge_model.fit(X_train, y_train) y_train_pred = ridge_model.predict(X_train) y_pred = ridge_model.predict(X_test) print('Train r2 score: ', r2_score(y_train_pred, y_train)) print('Test r2 score: ', r2_score(y_test, y_pred)) train_rmse = np.sqrt(mean_squared_error(y_train_pred, y_train)) test_rmse = np.sqrt(mean_squared_error(y_test, y_pred)) print(f'Train RMSE: {train_rmse:.4f}') print(f'Test RMSE: {test_rmse:.4f}') # Ridge Model Feature Importance ridge_feature_coef = pd.Series(index = X_train.columns, data = np.abs(ridge_model.coef_)) ridge_feature_coef.sort_values().plot(kind = 'bar', figsize = (13,5)); Now we repeat the same procedure for a lasso model. The lasso model works differently from the ridge model because it shrinks the coefficients of less important features. This can be visualized later in the feature importance plot. We can see that the lasso model is generalizing a lot better than the ridge model using just the ‘Days Open’ feature. It’s able to achieve just about the same test error as the ridge model using all features which shows the true potential of these regularization techniques. ElasticNet is a linear model that combines the regularization techniques of ridge and lasso. We will use ElasticNetCV to select the best hybrid model using cross validation. There is little to no improvement using the elastic net model. We can see that the training scores and test scores between the linear models are about the same. In terms of feature importance, the elastic model reduced features by 72%. Even with this reduction, the model does not seem to give an improved score against the ridge or lasso model. This is probably due to the small dataset and the linear models tendency to overfit. For KNN, we will use the KNeighborsRegressor from sklearn. We apply the same process to find the optimal neighbor parameter. Surprisingly, the KNN model seems to perform a bit better than the linear models on the test set. Random forests are very powerful models which are a bit different from bagged decision trees. Unlike bagged trees, random forests will select a subset of features at random and finds the best feature to split at each node whereas bagged trees considers using all features for splitting at each node. Random forests also provide unique hyperparameters to reduce overfitting as well. We will tune our model based on several of these hyperparameters. We can see the training score has improved significantly compared to the linear models we’ve used above and KNN. The model is also able to achieve this using nearly all of the data as shown below in the feature importance plot. LightGBM provides boosting capabilities for decision trees. It is a good alternative to XGBoost which we will test as well after. Based on the training score, it seems that the model has overfitted to the training set since there is no improvement in the test score. It’s probably not optimal to include this model at all in our ensemble later. XGBoost is yet another boosting algorithm for decision trees. Let’s see how it compares to LightGBM after tuning hyperparameters. The model doesn’t seem to be overfitting as much as LightGBM. The training and test scores seem to be lower than the random forest model too. This explains why the model is heavily used in just about any problem setting. It is very easy to overfit in boosted models so we will add early stopping parameters to reduce overfitting. This gives us a better model that is still able to generalize the test set quite well. Based on the experimentation of the models above, it’s clear that the linear models and KNN are not the best models for this dataset. Therefore, they won’t be used as part of the ensemble. The best models to ensemble would be random forests and XGBoost models as we have seen from the training and test errors above. I decided to use a random forest ensemble since boosting models in this scenario have a tendency to overfit as shown by the LightGBM model. For the ensemble, I decided to use a stacked ensemble. The benefits of this is to create a single model that has the well-performing capabilities of several base models. The base models are different tuned random forest models and the meta model will be a simple model such as a linear regressor. I fitted the stacked model on the entire dataset and tested it against the Kaggle private leaderboard. The model did surprisingly well placing 4th on the private leaderboard with a RMSE score of 1741680.77896. For reference, the 1st place solution on the private leaderboard was an RMSE of 1727811.48553. Initially, I had not planned for a lot of things for this project. Before I read some of the discussions in the Kaggle competition, I had assumed the p-variables were actually numeric values. With this in mind, I log transformed these variables which actually ended up making the linear models better in predicting the target variable. This makes sense since every feature is normalized making it easier for a linear model to predict. After finding out that the p-variables were categorical with many missing values, imputation was a much better approach. This brings up the lesson that it’s very important to understand the data you’re working with especially if it’s a small dataset. I had also played around with many models, manually tweaking hyperparameters until I discovered grid search which did wonders on saving time and effort in finding the best model. These were just some of the few things I learned while working on this dataset. A few things to perhaps try in the future would be to fit models on relevant features and including a more diverse ensemble of models.
[ { "code": null, "e": 796, "s": 46, "text": "Restaurants are an essential part of a country’s economy and society. Whether it may be for social gatherings or a quick bite, most of us have experienced at least one visit. With the recent rise in pop up restaurants and food trucks, it’s imperative for the business owner to figure out when and where to open new restaurants since it takes up a lot of time, effort, and capital to do so. This brings up the problem of finding the best optimal time and place to open a new restaurant. TFI which owns many giant restaurant chains has provided demographic, real estate, and commercial data in their restaurant revenue prediction on Kaggle. The challenge here would be to build a robust model that is capable of predicting the revenue of a restaurant." }, { "code": null, "e": 1643, "s": 796, "text": "After taking a look at the data, there are 137 samples in the training set and 100,000 samples in the test set. This is very intriguing since the distribution of data is usually the other way around. The goal here would be to model revenue based on 137 samples in the training set and see how well the model performs on the 100,000 samples in the test set. The data fields for each sample consist of the restaurant ID which is unique for each restaurant in the sample, the opening date of the restaurant, the city, city group, restaurant type, several non-arbitrary P-variables, and revenue which is the target variable. Using a complex model for this small training dataset with noise will cause the model to overfit to the dataset. To prevent that from happening, regularization techniques for linear regression will definitely need to be used." }, { "code": null, "e": 1848, "s": 1643, "text": "After a brief look at the training data, it appears that there are no null values which is a good thing. However, that may not be the case for the P-variables as we will see later in the data exploration." }, { "code": null, "e": 1853, "s": 1848, "text": "Type" }, { "code": null, "e": 2291, "s": 1853, "text": "The two figures above show the count of types of restaurants in the training set and test set. Looking carefully, there doesn’t seem to be a single occurrence of the ‘MB’ type in the training set. Type ‘MB’ stands for mobile restaurants and type ‘DT’ stands for drive-thru restaurants. Since mobile restaurants are more related to drive-thru than inline and food courts, the ‘MB’ samples in the test set were replaced with the ‘DT’ type." }, { "code": null, "e": 2302, "s": 2291, "text": "City Group" }, { "code": null, "e": 2593, "s": 2302, "text": "There doesn’t seem to be any changes required for the city group feature. The training set has slightly more ‘Big Cities’ samples than ‘Other’ samples but that shouldn’t be a problem when we create our model. It should also be intuitive that restaurant revenue in the city than other areas." }, { "code": null, "e": 2598, "s": 2593, "text": "City" }, { "code": null, "e": 2665, "s": 2598, "text": "(df['City'].nunique(), test_df['City'].nunique())Out[10]: (34, 57)" }, { "code": null, "e": 2938, "s": 2665, "text": "For the ‘City’ feature, it appears that there are cities in the test set that aren’t in the training set. It is also worth noting that some of the non-arbitrary P-variables already contain geolocation information so the entire ‘City’ feature was dropped for both datasets." }, { "code": null, "e": 2948, "s": 2938, "text": "Open Date" }, { "code": null, "e": 3395, "s": 2948, "text": "import datetimedf.drop('Id',axis=1,inplace=True)df['Open Date'] = pd.to_datetime(df['Open Date'])test_df['Open Date'] = pd.to_datetime(test_df['Open Date'])launch_date = datetime.datetime(2015, 3, 23)# scale days opendf['Days Open'] = (launch_date - df['Open Date']).dt.days / 1000test_df['Days Open'] = (launch_date - test_df['Open Date']).dt.days / 1000df.drop('Open Date', axis=1, inplace=True)test_df.drop('Open Date', axis=1, inplace=True)" }, { "code": null, "e": 3848, "s": 3395, "text": "The opening date is the date the restaurant first opened. It won’t be of much use in terms of predicting revenue but it would be useful to know how long the restaurant has been open since the opening date. For that reason, I decided to use March 23, 2015 as the date of comparison to calculate the amount of days the restaurant has been open. Then, I chose to downscale the number of days open by a factor of 1000 to slightly improve model performance." }, { "code": null, "e": 3860, "s": 3848, "text": "P-Variables" }, { "code": null, "e": 4066, "s": 3860, "text": "The data has 37 p-variables which are all obfuscated data. These features contain demographic data, real estate data, and commercial data based on the data field description on the Kaggle competition page." }, { "code": null, "e": 4769, "s": 4066, "text": "Initially, I had thought that the p-variables were numerical features but after reading some of the discussions in the competition, it turns out that some of these features were actually categorical data encoded using integers. What’s even more interesting is that a majority of the values for some of these features are zero. Once again, after digging through the discussions, people concluded that these zero values were actually null values as shown in the plots above. Multivariate imputation by chained equations (also known as MICE) was used to replace the missing values in some of these features. The way it works is that is uses the entire set of available data to estimate the missing values." }, { "code": null, "e": 5260, "s": 4769, "text": "from sklearn.experimental import enable_iterative_imputerfrom sklearn.impute import IterativeImputerimp_train = IterativeImputer(max_iter=30, missing_values=0, sample_posterior=True, min_value=1, random_state=37)imp_test = IterativeImputer(max_iter=30, missing_values=0, sample_posterior=True, min_value=1, random_state=23)p_data = ['P'+str(i) for i in range(1,38)]df[p_data] = np.round(imp_train.fit_transform(df[p_data]))test_df[p_data] = np.round(imp_test.fit_transform(test_df[p_data]))" }, { "code": null, "e": 5527, "s": 5260, "text": "The imputer was used on all p-variables separately for the training set and the test set. The missing values are estimated several times before the imputer takes the average. Before feeding these averages to the model, they need to be rounded to the nearest integer." }, { "code": null, "e": 5544, "s": 5527, "text": "One Hot Encoding" }, { "code": null, "e": 5884, "s": 5544, "text": "To deal with object types in the data, one hot encoding will be used to transform these features into numerical form which can be provided to the machine learning models. Dummy encoding can also be used to avoid redundancy. The features that will be encoded are ‘Type’ and ‘City Group’ since they are the only object types in the datasets." }, { "code": null, "e": 6087, "s": 5884, "text": "columnsToEncode = df.select_dtypes(include=[object]).columnsdf = pd.get_dummies(df, columns=columnsToEncode, drop_first=False)test_df = pd.get_dummies(test_df, columns=columnsToEncode, drop_first=False)" }, { "code": null, "e": 6116, "s": 6087, "text": "Target Variable Distribution" }, { "code": null, "e": 6551, "s": 6116, "text": "Based on the distribution, it looks like revenue is right skewed. There also appears to be outliers which will cause issues in model training. Since we will be experimenting with linear models, the target variable will be transformed to make it normally distributed for improved model interpretation. The target variable was log transformed so the final predictions will need to be exponentiated to rescale the results back to normal." }, { "code": null, "e": 6865, "s": 6551, "text": "The models that I decided on experimenting with were several different linear models, KNN, random forest and gradient boosted models. The goal here is to find the best hyper-tuned models to ensemble for the final model. Before we train any model, we will split the training set into a training and validation set." }, { "code": null, "e": 7044, "s": 6865, "text": "df['revenue'] = np.log1p(df['revenue'])X, y = df.drop('revenue', axis=1), df['revenue']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=118)" }, { "code": null, "e": 7453, "s": 7044, "text": "Ridge regression is a regularized linear model. As stated earlier, regularization techniques need to be used to prevent overfitting especially since our training set is very small. Before we train a ridge model on the training, we need to find the optimal parameters for the model. To do this, grid search along with k-fold cross validation was used to find the optimal parameters that led to the best score." }, { "code": null, "e": 8190, "s": 7453, "text": "params_ridge = {\n 'alpha' : [.01, .1, .5, .7, .9, .95, .99, 1, 5, 10, 20],\n 'fit_intercept' : [True, False],\n 'normalize' : [True,False],\n 'solver' : ['svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag', 'saga']\n}\n\nridge_model = Ridge()\nridge_regressor = GridSearchCV(ridge_model, params_ridge, scoring='neg_root_mean_squared_error', cv=5, n_jobs=-1)\nridge_regressor.fit(X_train, y_train)\nprint(f'Optimal alpha: {ridge_regressor.best_params_[\"alpha\"]:.2f}')\nprint(f'Optimal fit_intercept: {ridge_regressor.best_params_[\"fit_intercept\"]}')\nprint(f'Optimal normalize: {ridge_regressor.best_params_[\"normalize\"]}')\nprint(f'Optimal solver: {ridge_regressor.best_params_[\"solver\"]}')\nprint(f'Best score: {ridge_regressor.best_score_}')" }, { "code": null, "e": 8369, "s": 8190, "text": "The optimal parameters are then used for model evaluation using both the training and test sets. The RMSE here is actually RMSLE since we’ve taken the log of the target variable." }, { "code": null, "e": 9037, "s": 8369, "text": "ridge_model = Ridge(alpha=ridge_regressor.best_params_[\"alpha\"], fit_intercept=ridge_regressor.best_params_[\"fit_intercept\"], \n normalize=ridge_regressor.best_params_[\"normalize\"], solver=ridge_regressor.best_params_[\"solver\"])\nridge_model.fit(X_train, y_train)\ny_train_pred = ridge_model.predict(X_train)\ny_pred = ridge_model.predict(X_test)\nprint('Train r2 score: ', r2_score(y_train_pred, y_train))\nprint('Test r2 score: ', r2_score(y_test, y_pred))\ntrain_rmse = np.sqrt(mean_squared_error(y_train_pred, y_train))\ntest_rmse = np.sqrt(mean_squared_error(y_test, y_pred))\nprint(f'Train RMSE: {train_rmse:.4f}')\nprint(f'Test RMSE: {test_rmse:.4f}')" }, { "code": null, "e": 9231, "s": 9037, "text": "# Ridge Model Feature Importance\nridge_feature_coef = pd.Series(index = X_train.columns, data = np.abs(ridge_model.coef_))\nridge_feature_coef.sort_values().plot(kind = 'bar', figsize = (13,5));" }, { "code": null, "e": 9463, "s": 9231, "text": "Now we repeat the same procedure for a lasso model. The lasso model works differently from the ridge model because it shrinks the coefficients of less important features. This can be visualized later in the feature importance plot." }, { "code": null, "e": 9738, "s": 9463, "text": "We can see that the lasso model is generalizing a lot better than the ridge model using just the ‘Days Open’ feature. It’s able to achieve just about the same test error as the ridge model using all features which shows the true potential of these regularization techniques." }, { "code": null, "e": 9912, "s": 9738, "text": "ElasticNet is a linear model that combines the regularization techniques of ridge and lasso. We will use ElasticNetCV to select the best hybrid model using cross validation." }, { "code": null, "e": 10073, "s": 9912, "text": "There is little to no improvement using the elastic net model. We can see that the training scores and test scores between the linear models are about the same." }, { "code": null, "e": 10343, "s": 10073, "text": "In terms of feature importance, the elastic model reduced features by 72%. Even with this reduction, the model does not seem to give an improved score against the ridge or lasso model. This is probably due to the small dataset and the linear models tendency to overfit." }, { "code": null, "e": 10468, "s": 10343, "text": "For KNN, we will use the KNeighborsRegressor from sklearn. We apply the same process to find the optimal neighbor parameter." }, { "code": null, "e": 10566, "s": 10468, "text": "Surprisingly, the KNN model seems to perform a bit better than the linear models on the test set." }, { "code": null, "e": 11014, "s": 10566, "text": "Random forests are very powerful models which are a bit different from bagged decision trees. Unlike bagged trees, random forests will select a subset of features at random and finds the best feature to split at each node whereas bagged trees considers using all features for splitting at each node. Random forests also provide unique hyperparameters to reduce overfitting as well. We will tune our model based on several of these hyperparameters." }, { "code": null, "e": 11242, "s": 11014, "text": "We can see the training score has improved significantly compared to the linear models we’ve used above and KNN. The model is also able to achieve this using nearly all of the data as shown below in the feature importance plot." }, { "code": null, "e": 11372, "s": 11242, "text": "LightGBM provides boosting capabilities for decision trees. It is a good alternative to XGBoost which we will test as well after." }, { "code": null, "e": 11587, "s": 11372, "text": "Based on the training score, it seems that the model has overfitted to the training set since there is no improvement in the test score. It’s probably not optimal to include this model at all in our ensemble later." }, { "code": null, "e": 11717, "s": 11587, "text": "XGBoost is yet another boosting algorithm for decision trees. Let’s see how it compares to LightGBM after tuning hyperparameters." }, { "code": null, "e": 11938, "s": 11717, "text": "The model doesn’t seem to be overfitting as much as LightGBM. The training and test scores seem to be lower than the random forest model too. This explains why the model is heavily used in just about any problem setting." }, { "code": null, "e": 12134, "s": 11938, "text": "It is very easy to overfit in boosted models so we will add early stopping parameters to reduce overfitting. This gives us a better model that is still able to generalize the test set quite well." }, { "code": null, "e": 12888, "s": 12134, "text": "Based on the experimentation of the models above, it’s clear that the linear models and KNN are not the best models for this dataset. Therefore, they won’t be used as part of the ensemble. The best models to ensemble would be random forests and XGBoost models as we have seen from the training and test errors above. I decided to use a random forest ensemble since boosting models in this scenario have a tendency to overfit as shown by the LightGBM model. For the ensemble, I decided to use a stacked ensemble. The benefits of this is to create a single model that has the well-performing capabilities of several base models. The base models are different tuned random forest models and the meta model will be a simple model such as a linear regressor." }, { "code": null, "e": 13193, "s": 12888, "text": "I fitted the stacked model on the entire dataset and tested it against the Kaggle private leaderboard. The model did surprisingly well placing 4th on the private leaderboard with a RMSE score of 1741680.77896. For reference, the 1st place solution on the private leaderboard was an RMSE of 1727811.48553." } ]
Foreign key in MS SQL Server - GeeksforGeeks
31 Jul, 2020 Prerequisite – Primary key in MS SQL ServerSQL Server has different keys which serve a different purpose. In this article, the foreign key will be discussed in brief. The foreign key has a similar purpose as the primary key yet, the foreign key is used for two tables. In a few cases, the foreign key is used for self-referencing a single table. Foreign key :A singular column or a set of columns of one table that uniquely identified by a singular column or a set of columns of another table is referred to as a foreign key. Syntax – constraint fk_constraint-name foreign key(col1, col2) references parent_table-name(col1, col2) (OR) foreign key(col1, col2) references parent_table-name(col1, col2) A foreign key has two tables – parent table and child table. If a user wants to insert a column in a child table, the column has to be a part of the parent table otherwise, an error is displayed. In the syntax, the constraint term is not mandatory to use. When a foreign key is mentioned in the query, the key automatically creates a referential constraint meaning a column can be inserted in the child table only if it is a part of the parent table. Two tables named student (parent table) and marks (child table) are considered from the university database. If a user wants to insert a new column, the query is given as – foreign key('rollno') references student('rollno') insert into marks ('name', 'rollno', 'marks') values('Naina, '111', '7.5') An error is displayed as the roll number is already taken by a student. (Foreign key constraint). The foreign key does not allow the value to reoccur. To avoid such errors, the values must neither be repeated nor a different column must be considered. DBMS-SQL SQL-Server DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS KDD Process in Data Mining Conflict Serializability in DBMS What is Temporary Table in SQL? SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 25549, "s": 25521, "text": "\n31 Jul, 2020" }, { "code": null, "e": 25716, "s": 25549, "text": "Prerequisite – Primary key in MS SQL ServerSQL Server has different keys which serve a different purpose. In this article, the foreign key will be discussed in brief." }, { "code": null, "e": 25895, "s": 25716, "text": "The foreign key has a similar purpose as the primary key yet, the foreign key is used for two tables. In a few cases, the foreign key is used for self-referencing a single table." }, { "code": null, "e": 26075, "s": 25895, "text": "Foreign key :A singular column or a set of columns of one table that uniquely identified by a singular column or a set of columns of another table is referred to as a foreign key." }, { "code": null, "e": 26084, "s": 26075, "text": "Syntax –" }, { "code": null, "e": 26291, "s": 26084, "text": "constraint fk_constraint-name foreign key(col1, col2) \nreferences parent_table-name(col1, col2)\n (OR)\nforeign key(col1, col2) \nreferences parent_table-name(col1, col2)" }, { "code": null, "e": 26547, "s": 26291, "text": "A foreign key has two tables – parent table and child table. If a user wants to insert a column in a child table, the column has to be a part of the parent table otherwise, an error is displayed. In the syntax, the constraint term is not mandatory to use." }, { "code": null, "e": 26742, "s": 26547, "text": "When a foreign key is mentioned in the query, the key automatically creates a referential constraint meaning a column can be inserted in the child table only if it is a part of the parent table." }, { "code": null, "e": 26851, "s": 26742, "text": "Two tables named student (parent table) and marks (child table) are considered from the university database." }, { "code": null, "e": 26915, "s": 26851, "text": "If a user wants to insert a new column, the query is given as –" }, { "code": null, "e": 27044, "s": 26915, "text": "foreign key('rollno') \nreferences student('rollno')\n\ninsert into marks ('name', 'rollno', 'marks') \nvalues('Naina, '111', '7.5')" }, { "code": null, "e": 27296, "s": 27044, "text": "An error is displayed as the roll number is already taken by a student. (Foreign key constraint). The foreign key does not allow the value to reoccur. To avoid such errors, the values must neither be repeated nor a different column must be considered." }, { "code": null, "e": 27305, "s": 27296, "text": "DBMS-SQL" }, { "code": null, "e": 27316, "s": 27305, "text": "SQL-Server" }, { "code": null, "e": 27321, "s": 27316, "text": "DBMS" }, { "code": null, "e": 27325, "s": 27321, "text": "SQL" }, { "code": null, "e": 27330, "s": 27325, "text": "DBMS" }, { "code": null, "e": 27334, "s": 27330, "text": "SQL" }, { "code": null, "e": 27432, "s": 27334, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27449, "s": 27432, "text": "Deadlock in DBMS" }, { "code": null, "e": 27490, "s": 27449, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27517, "s": 27490, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27550, "s": 27517, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 27582, "s": 27550, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27624, "s": 27582, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 27668, "s": 27624, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27689, "s": 27668, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27755, "s": 27689, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
C++ Classes Introduction | Practice | GeeksforGeeks
Create class named CollegeCourse with fields courseID, grade, credits, gradePoints and honorPoints. Calculate honorpoints as the product of gradepoints and credits. GradePoints are calculated as (A-10),(B-9),(C-8),(D-7),(E-6) & (F-5). Class CollegeCourse contains following functions: 1. set_CourseID( string CID): sets courseID 2. set_Grade(char g): sets grade equal to g 3. set_Credit(int cr): sets credits equal to cr 4.calculateGradePoints(char g): returns gradePoint(int) 5. calculateHonorPoints(int gp,int cr): return honorPoint (float) 6. display(): prints gradePoint and honorPoint Input: The first line contains an integer T, the number of test cases. For each test case, there is a string CID, denoting Course ID, a character g, denoting the grade and an integer cr, denoting the credits of the course. Output: For each test case, the output is the gradePoints & the honorPoints of that course. Constraints: 1<=T<=100 1<=CID.length()<=100 'A'<=g<='F' 1<=cr<=4 Note: Grades are not case sensitive. Example: Input 2 CSN-206 A 4 ECE-500 d 3 Output 10 40 7 21 0 atulharsh274Premium1 month ago int calculateGradePoints(char g){ char arr[]={'A','B','C','D','E','F'}; char arr2[]={'a','b','c','d','e','f'}; for(int i=0;i<6;i++){ if(arr[i]==g || arr2[i]==g){gradePoints = 10-i; break; }} return gradePoints; } 0 atulharsh274Premium1 month ago class CollegeCourse{ //your code here private: string courseID; char grade; int credits; int gradePoints; float honorPoints; public: void set_CourseId( string CID){ courseID = CID; } void set_Grade(char g){ grade = g; } void set_Credit(int cr){ credits = cr; } int calculateGradePoints(char g){ char arr[]={'A','B','C','D','E','F'}; char arr2[]={'a','b','c','d','e','f'}; for(int i=0;i<6;i++){ if(arr[i]==g || arr2[i]==g){gradePoints = 10-i; break; }} return gradePoints; } float calculateHonorPoints(int gp,int cr){ honorPoints = gp*cr; return honorPoints; } void display(){ cout<<gradePoints<<" "<<honorPoints<<endl; } }; 0 harshithbhat This comment was deleted. +1 9chara92 months ago int calculateGradePoints(char g) { gradePoints = 75 - toupper(g); return gradePoints; } 0 parasparihar613 months ago // { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std; // } Driver Code Ends//User function Template for C++ // CollegeCourse Class class CollegeCourse{string courseID;char grade;int credits;int gradepoints;float honorPoints;public:void set_CourseId(string CID){ courseID=CID;}void set_Grade(char g){ grade=g;}void set_Credit(int cr){ credits=cr;}int calculateGradePoints(char g){ switch(g) { case 'A':gradepoints=10; return 10; break; case 'B': gradepoints=9; return 9; break; case 'C': gradepoints=8; return 8; break; case 'D': gradepoints=7; return 7; break; case 'E': gradepoints=6; return 6; break; case 'F': gradepoints=5; return 5; break; case 'a': gradepoints=10; return 10; break; case 'b': gradepoints=9; return 9; break; case 'c': gradepoints=8; return 8; break; case 'd': gradepoints=7; return 7; break; case 'e': gradepoints=6; return 6; break; case 'f': gradepoints=5; return 5; break; }}float calculateHonorPoints(int gp,int cr){ honorPoints= gp*cr; return honorPoints;}void display(){ cout<<gradepoints<<" "<<honorPoints<<endl;}}; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends 0 parasparihar613 months ago // { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std; // } Driver Code Ends//User function Template for C++ // CollegeCourse Class class CollegeCourse{string courseID;char grade;int credits;int gradepoints;float honorPoints;public:void set_CourseId(string CID){ courseID=CID;}void set_Grade(char g){ grade=g;}void set_Credit(int cr){ credits=cr;}int calculateGradePoints(char g){ switch(g) { case 'A':gradepoints=10; return 10; break; case 'B': gradepoints=9; return 9; break; case 'C': gradepoints=8; return 8; break; case 'D': gradepoints=7; return 7; break; case 'E': gradepoints=6; return 6; break; case 'F': gradepoints=5; return 5; break; case 'a': gradepoints=10; return 10; break; case 'b': gradepoints=9; return 9; break; case 'c': gradepoints=8; return 8; break; case 'd': gradepoints=7; return 7; break; case 'e': gradepoints=6; return 6; break; case 'f': gradepoints=5; return 5; break; }}float calculateHonorPoints(int gp,int cr){ honorPoints= gp*cr; return honorPoints;}void display(){ cout<<gradepoints<<" "<<honorPoints<<endl;}}; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends 0 tushargarg98684 months ago // { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std; // } Driver Code Ends//User function Template for C++ // CollegeCourse Class class CollegeCourse{ //your code here string courseId; char grade; int credits; int gradePoints; float honarPoints; public: void set_CourseId(string CID){ courseId=CID; } void set_Grade(char g){ grade=g; } void set_Credit(int cr){ credits=cr; } int calculateGradePoints(char g){ if(g=='A' || g=='a'){ gradePoints=10; } else if(g=='b' || g=='B'){ gradePoints=9; } else if(g=='c' || g=='C'){ gradePoints=8; } else if(g=='d' || g=='D'){ gradePoints=7; } else if(g=='e' || g=='E'){ gradePoints=6; } else if(g=='f' || g=='F'){ gradePoints=5; } return gradePoints; } float calculateHonorPoints(int gp, int cr){ honarPoints=gradePoints*credits; return honarPoints; } void display(){ cout<<gradePoints<<" "<<honarPoints<<endl; } }; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends 0 bhalgatshreya24 months ago // { Driver Code Starts //Initial Template for C++ #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function Template for C++ // CollegeCourse Class class CollegeCourse { public: string CID; char g; int cr; int gradePoints; float honorPoints; void set_CourseId(string courseId) { CID = courseId ; } void set_Grade(char grade) { g = grade; } void set_Credit(int credits) { cr = credits; } int calculateGradePoints(char g) { if(g == 'A' or g == 'a') { gradePoints = 10; } else if(g == 'B' or g == 'b') { gradePoints = 9; } else if(g == 'C' or g == 'c') { gradePoints = 8; } else if(g == 'D' or g == 'd') { gradePoints = 7; } else if(g == 'E' or g == 'e') { gradePoints = 6; } else if(g == 'F' or g == 'f') { gradePoints = 5; } return gradePoints; } int calculateHonorPoints(int gp,int cr) { honorPoints = gradePoints * cr; return honorPoints; } void display() { cout<<gradePoints<<" "<<honorPoints<<endl; } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0; } // } Driver Code Ends 0 priyam265 months ago class CollegeCourse{ //why does this code is showing error? // prog.cpp: In function int main(): // prog.cpp:70:8: error: class CollegeCourse has no //member named set_CourseId // cc.set_CourseId(courseId); // ^ string courseID; char grade; int credits, gradePoints; float honorPoints; public: void set_CourseID(string CID) { courseID = CID; } void set_Grade(char g) { grade = g; } void set_Credit(int cr) { credits = cr; } int calculateGradePoints(char g) { if(g == 'A' or g == 'a') { gradePoints = 10; } else if(g == 'B' or g == 'b') { gradePoints = 9; } else if(g == 'C' or g == 'c') { gradePoints = 8; } else if(g == 'D' or g == 'd') { gradePoints = 7; } else if(g == 'E' or g == 'e') { gradePoints = 6; } else if(g == 'F' or g == 'f') { gradePoints = 5; } return gradePoints; } float calculateHonorPoints(int gp,int cr) { honorPoints = gradePoints * credits; return honorPoints; } void display() { cout << gradePoints << " " << honorPoints << endl; } }; 0 priyam26 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 817, "s": 226, "text": "Create class named CollegeCourse with fields courseID, grade, credits, gradePoints and honorPoints. Calculate honorpoints as the product of gradepoints and credits. GradePoints are calculated as (A-10),(B-9),(C-8),(D-7),(E-6) & (F-5).\nClass CollegeCourse contains following functions:\n1. set_CourseID( string CID): sets courseID\n2. set_Grade(char g): sets grade equal to g\n3. set_Credit(int cr): sets credits equal to cr \n4.calculateGradePoints(char g): returns gradePoint(int)\n5. calculateHonorPoints(int gp,int cr): return honorPoint (float)\n6. display(): prints gradePoint and honorPoint" }, { "code": null, "e": 1040, "s": 817, "text": "Input:\nThe first line contains an integer T, the number of test cases. For each test case, there is a string CID, denoting Course ID, a character g, denoting the grade and an integer cr, denoting the credits of the course." }, { "code": null, "e": 1132, "s": 1040, "text": "Output:\nFor each test case, the output is the gradePoints & the honorPoints of that course." }, { "code": null, "e": 1234, "s": 1132, "text": "Constraints:\n1<=T<=100\n1<=CID.length()<=100\n'A'<=g<='F'\n1<=cr<=4\nNote: Grades are not case sensitive." }, { "code": null, "e": 1293, "s": 1234, "text": "Example:\nInput\n2\nCSN-206 A 4\nECE-500 d 3\nOutput\n10 40\n7 21" }, { "code": null, "e": 1295, "s": 1293, "text": "0" }, { "code": null, "e": 1326, "s": 1295, "text": "atulharsh274Premium1 month ago" }, { "code": null, "e": 1624, "s": 1326, "text": "int calculateGradePoints(char g){ char arr[]={'A','B','C','D','E','F'}; char arr2[]={'a','b','c','d','e','f'}; for(int i=0;i<6;i++){ if(arr[i]==g || arr2[i]==g){gradePoints = 10-i; break; }} return gradePoints; }" }, { "code": null, "e": 1626, "s": 1624, "text": "0" }, { "code": null, "e": 1657, "s": 1626, "text": "atulharsh274Premium1 month ago" }, { "code": null, "e": 2546, "s": 1657, "text": "class CollegeCourse{ //your code here private: string courseID; char grade; int credits; int gradePoints; float honorPoints; public: void set_CourseId( string CID){ courseID = CID; } void set_Grade(char g){ grade = g; } void set_Credit(int cr){ credits = cr; } int calculateGradePoints(char g){ char arr[]={'A','B','C','D','E','F'}; char arr2[]={'a','b','c','d','e','f'}; for(int i=0;i<6;i++){ if(arr[i]==g || arr2[i]==g){gradePoints = 10-i; break; }} return gradePoints; } float calculateHonorPoints(int gp,int cr){ honorPoints = gp*cr; return honorPoints; } void display(){ cout<<gradePoints<<\" \"<<honorPoints<<endl; } }; " }, { "code": null, "e": 2550, "s": 2548, "text": "0" }, { "code": null, "e": 2563, "s": 2550, "text": "harshithbhat" }, { "code": null, "e": 2589, "s": 2563, "text": "This comment was deleted." }, { "code": null, "e": 2592, "s": 2589, "text": "+1" }, { "code": null, "e": 2612, "s": 2592, "text": "9chara92 months ago" }, { "code": null, "e": 2727, "s": 2612, "text": " int calculateGradePoints(char g) \n {\n gradePoints = 75 - toupper(g); \n return gradePoints; \n }" }, { "code": null, "e": 2729, "s": 2727, "text": "0" }, { "code": null, "e": 2756, "s": 2729, "text": "parasparihar613 months ago" }, { "code": null, "e": 2849, "s": 2756, "text": "// { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 2903, "s": 2849, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 4039, "s": 2903, "text": "// CollegeCourse Class class CollegeCourse{string courseID;char grade;int credits;int gradepoints;float honorPoints;public:void set_CourseId(string CID){ courseID=CID;}void set_Grade(char g){ grade=g;}void set_Credit(int cr){ credits=cr;}int calculateGradePoints(char g){ switch(g) { case 'A':gradepoints=10; return 10; break; case 'B': gradepoints=9; return 9; break; case 'C': gradepoints=8; return 8; break; case 'D': gradepoints=7; return 7; break; case 'E': gradepoints=6; return 6; break; case 'F': gradepoints=5; return 5; break; case 'a': gradepoints=10; return 10; break; case 'b': gradepoints=9; return 9; break; case 'c': gradepoints=8; return 8; break; case 'd': gradepoints=7; return 7; break; case 'e': gradepoints=6; return 6; break; case 'f': gradepoints=5; return 5; break; }}float calculateHonorPoints(int gp,int cr){ honorPoints= gp*cr; return honorPoints;}void display(){ cout<<gradepoints<<\" \"<<honorPoints<<endl;}};" }, { "code": null, "e": 4064, "s": 4039, "text": "// { Driver Code Starts." }, { "code": null, "e": 4432, "s": 4064, "text": "int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 4434, "s": 4432, "text": "0" }, { "code": null, "e": 4461, "s": 4434, "text": "parasparihar613 months ago" }, { "code": null, "e": 4554, "s": 4461, "text": "// { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 4608, "s": 4554, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 5744, "s": 4608, "text": "// CollegeCourse Class class CollegeCourse{string courseID;char grade;int credits;int gradepoints;float honorPoints;public:void set_CourseId(string CID){ courseID=CID;}void set_Grade(char g){ grade=g;}void set_Credit(int cr){ credits=cr;}int calculateGradePoints(char g){ switch(g) { case 'A':gradepoints=10; return 10; break; case 'B': gradepoints=9; return 9; break; case 'C': gradepoints=8; return 8; break; case 'D': gradepoints=7; return 7; break; case 'E': gradepoints=6; return 6; break; case 'F': gradepoints=5; return 5; break; case 'a': gradepoints=10; return 10; break; case 'b': gradepoints=9; return 9; break; case 'c': gradepoints=8; return 8; break; case 'd': gradepoints=7; return 7; break; case 'e': gradepoints=6; return 6; break; case 'f': gradepoints=5; return 5; break; }}float calculateHonorPoints(int gp,int cr){ honorPoints= gp*cr; return honorPoints;}void display(){ cout<<gradepoints<<\" \"<<honorPoints<<endl;}};" }, { "code": null, "e": 5769, "s": 5744, "text": "// { Driver Code Starts." }, { "code": null, "e": 6137, "s": 5769, "text": "int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 6139, "s": 6137, "text": "0" }, { "code": null, "e": 6166, "s": 6139, "text": "tushargarg98684 months ago" }, { "code": null, "e": 6259, "s": 6166, "text": "// { Driver Code Starts//Initial Template for C++#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 6313, "s": 6259, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 7277, "s": 6313, "text": "// CollegeCourse Class class CollegeCourse{ //your code here string courseId; char grade; int credits; int gradePoints; float honarPoints; public: void set_CourseId(string CID){ courseId=CID; } void set_Grade(char g){ grade=g; } void set_Credit(int cr){ credits=cr; } int calculateGradePoints(char g){ if(g=='A' || g=='a'){ gradePoints=10; } else if(g=='b' || g=='B'){ gradePoints=9; } else if(g=='c' || g=='C'){ gradePoints=8; } else if(g=='d' || g=='D'){ gradePoints=7; } else if(g=='e' || g=='E'){ gradePoints=6; } else if(g=='f' || g=='F'){ gradePoints=5; } return gradePoints; } float calculateHonorPoints(int gp, int cr){ honarPoints=gradePoints*credits; return honarPoints; } void display(){ cout<<gradePoints<<\" \"<<honarPoints<<endl; } };" }, { "code": null, "e": 7302, "s": 7277, "text": "// { Driver Code Starts." }, { "code": null, "e": 7670, "s": 7302, "text": "int main(){ int t; cin>>t; while(t--) { CollegeCourse cc; string courseId; int gp; char grade; int credits; cin>>courseId>>grade>>credits; cc.set_CourseId(courseId); cc.set_Grade(grade); cc.set_Credit(credits); gp=cc.calculateGradePoints(grade); cc.calculateHonorPoints(gp,credits); cc.display(); } return 0;} // } Driver Code Ends" }, { "code": null, "e": 7672, "s": 7670, "text": "0" }, { "code": null, "e": 7699, "s": 7672, "text": "bhalgatshreya24 months ago" }, { "code": null, "e": 9536, "s": 7699, "text": "// { Driver Code Starts\n//Initial Template for C++\n#include<bits/stdc++.h>\nusing namespace std;\n\n\n // } Driver Code Ends\n//User function Template for C++\n\n// CollegeCourse Class \nclass CollegeCourse\n{\n public:\n string CID;\n char g;\n int cr;\n int gradePoints;\n float honorPoints;\n \n \n void set_CourseId(string courseId)\n {\n CID = courseId ;\n }\n void set_Grade(char grade)\n {\n g = grade;\n }\n void set_Credit(int credits)\n {\n cr = credits;\n }\n int calculateGradePoints(char g)\n {\n if(g == 'A' or g == 'a')\n {\n gradePoints = 10;\n }\n else if(g == 'B' or g == 'b')\n {\n gradePoints = 9;\n }\n else if(g == 'C' or g == 'c')\n {\n gradePoints = 8;\n }\n else if(g == 'D' or g == 'd')\n {\n gradePoints = 7;\n }\n else if(g == 'E' or g == 'e')\n {\n gradePoints = 6;\n }\n else if(g == 'F' or g == 'f')\n {\n gradePoints = 5;\n }\n \n return gradePoints;\n }\n\n int calculateHonorPoints(int gp,int cr)\n {\n honorPoints = gradePoints * cr;\n return honorPoints;\n }\n void display()\n {\n cout<<gradePoints<<\" \"<<honorPoints<<endl;\n }\n \n};\n\n// { Driver Code Starts.\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n CollegeCourse cc;\n string courseId;\n int gp;\n char grade;\n int credits;\n cin>>courseId>>grade>>credits;\n cc.set_CourseId(courseId);\n cc.set_Grade(grade);\n cc.set_Credit(credits);\n gp=cc.calculateGradePoints(grade);\n cc.calculateHonorPoints(gp,credits);\n cc.display();\n }\n return 0;\n}\n // } Driver Code Ends" }, { "code": null, "e": 9538, "s": 9536, "text": "0" }, { "code": null, "e": 9559, "s": 9538, "text": "priyam265 months ago" }, { "code": null, "e": 10892, "s": 9559, "text": "class CollegeCourse{ //why does this code is showing error? // prog.cpp: In function int main(): // prog.cpp:70:8: error: class CollegeCourse has no //member named set_CourseId // cc.set_CourseId(courseId); // ^ string courseID; char grade; int credits, gradePoints; float honorPoints; public: void set_CourseID(string CID) { courseID = CID; } void set_Grade(char g) { grade = g; } void set_Credit(int cr) { credits = cr; } int calculateGradePoints(char g) { if(g == 'A' or g == 'a') { gradePoints = 10; } else if(g == 'B' or g == 'b') { gradePoints = 9; } else if(g == 'C' or g == 'c') { gradePoints = 8; } else if(g == 'D' or g == 'd') { gradePoints = 7; } else if(g == 'E' or g == 'e') { gradePoints = 6; } else if(g == 'F' or g == 'f') { gradePoints = 5; } return gradePoints; } float calculateHonorPoints(int gp,int cr) { honorPoints = gradePoints * credits; return honorPoints; } void display() { cout << gradePoints << \" \" << honorPoints << endl; } }; " }, { "code": null, "e": 10894, "s": 10892, "text": "0" }, { "code": null, "e": 10903, "s": 10894, "text": "priyam26" }, { "code": null, "e": 10929, "s": 10903, "text": "This comment was deleted." }, { "code": null, "e": 11075, "s": 10929, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 11111, "s": 11075, "text": " Login to access your submissions. " }, { "code": null, "e": 11121, "s": 11111, "text": "\nProblem\n" }, { "code": null, "e": 11131, "s": 11121, "text": "\nContest\n" }, { "code": null, "e": 11194, "s": 11131, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11342, "s": 11194, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 11550, "s": 11342, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 11656, "s": 11550, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
HashSet iterator() Method in Java - GeeksforGeeks
26 Nov, 2018 The Java.util.HashSet.iterator() method is used to return an iterator of the same elements as the hash set. The elements are returned in random order from what present in the hash set. Syntax: Iterator iterate_value = Hash_Set.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the elements of the hash set and returns the values(iterators). Below program illustrate the Java.util.HashSet.iterator() method: // Java code to illustrate iterator()import java.util.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the HashSet System.out.println("HashSet: " + set); // Creating an iterator Iterator value = set.iterator(); // Displaying the values after iterating through the set System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }} HashSet: [4, Geeks, Welcome, To] The iterator values are: 4 Geeks Welcome To Java - util package Java-Collections Java-Functions java-hashset Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Multithreading in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 25439, "s": 25411, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25624, "s": 25439, "text": "The Java.util.HashSet.iterator() method is used to return an iterator of the same elements as the hash set. The elements are returned in random order from what present in the hash set." }, { "code": null, "e": 25632, "s": 25624, "text": "Syntax:" }, { "code": null, "e": 25679, "s": 25632, "text": "Iterator iterate_value = Hash_Set.iterator();\n" }, { "code": null, "e": 25733, "s": 25679, "text": "Parameters: The function does not take any parameter." }, { "code": null, "e": 25836, "s": 25733, "text": "Return Value: The method iterates over the elements of the hash set and returns the values(iterators)." }, { "code": null, "e": 25902, "s": 25836, "text": "Below program illustrate the Java.util.HashSet.iterator() method:" }, { "code": "// Java code to illustrate iterator()import java.util.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the HashSet System.out.println(\"HashSet: \" + set); // Creating an iterator Iterator value = set.iterator(); // Displaying the values after iterating through the set System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}", "e": 26694, "s": 25902, "text": null }, { "code": null, "e": 26773, "s": 26694, "text": "HashSet: [4, Geeks, Welcome, To]\nThe iterator values are: \n4\nGeeks\nWelcome\nTo\n" }, { "code": null, "e": 26793, "s": 26773, "text": "Java - util package" }, { "code": null, "e": 26810, "s": 26793, "text": "Java-Collections" }, { "code": null, "e": 26825, "s": 26810, "text": "Java-Functions" }, { "code": null, "e": 26838, "s": 26825, "text": "java-hashset" }, { "code": null, "e": 26843, "s": 26838, "text": "Java" }, { "code": null, "e": 26848, "s": 26843, "text": "Java" }, { "code": null, "e": 26865, "s": 26848, "text": "Java-Collections" }, { "code": null, "e": 26963, "s": 26865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26978, "s": 26963, "text": "Stream In Java" }, { "code": null, "e": 26997, "s": 26978, "text": "Interfaces in Java" }, { "code": null, "e": 27015, "s": 26997, "text": "ArrayList in Java" }, { "code": null, "e": 27047, "s": 27015, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27067, "s": 27047, "text": "Stack Class in Java" }, { "code": null, "e": 27091, "s": 27067, "text": "Singleton Class in Java" }, { "code": null, "e": 27123, "s": 27091, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27146, "s": 27123, "text": "Multithreading in Java" }, { "code": null, "e": 27166, "s": 27146, "text": "Collections in Java" } ]
MongoDB NOR operator ( $nor ) - GeeksforGeeks
22 Apr, 2020 MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements. Syntax: { $nor: [ { Expression1 }, { Expression2 }, ... { ExpressionN } ] } In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs. In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE. db.contributor.find({$nor: [{salary: 3000}, {branch: "ECE"}]}).pretty() In this example, we are retrieving only those employee’s documents whose age is not 24 and whose state is not AP. db.contributor.find({$nor: [{"personal.age": 24}, {"personal.state": "AP"}]}).pretty() In this example, we are retrieving only those employee’s documents that does not match the given array. db.contributor.find({$nor: [{language: {$in: ["Java", "C++"]}}]}).pretty() MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python An introduction to Machine Learning Principal Component Analysis with Python Basics of API Testing Using Postman ML | What is Machine Learning ? OpenCV - Overview Getting Started with System Design
[ { "code": null, "e": 25407, "s": 25379, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25794, "s": 25407, "text": "MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements." }, { "code": null, "e": 25802, "s": 25794, "text": "Syntax:" }, { "code": null, "e": 25871, "s": 25802, "text": "{ $nor: [ { Expression1 }, { Expression2 }, ... { ExpressionN } ] }" }, { "code": null, "e": 25919, "s": 25871, "text": "In the following examples, we are working with:" }, { "code": null, "e": 26070, "s": 25919, "text": "Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 26191, "s": 26070, "text": "In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE." }, { "code": "db.contributor.find({$nor: [{salary: 3000}, {branch: \"ECE\"}]}).pretty()", "e": 26263, "s": 26191, "text": null }, { "code": null, "e": 26377, "s": 26263, "text": "In this example, we are retrieving only those employee’s documents whose age is not 24 and whose state is not AP." }, { "code": "db.contributor.find({$nor: [{\"personal.age\": 24}, {\"personal.state\": \"AP\"}]}).pretty()", "e": 26491, "s": 26377, "text": null }, { "code": null, "e": 26595, "s": 26491, "text": "In this example, we are retrieving only those employee’s documents that does not match the given array." }, { "code": "db.contributor.find({$nor: [{language: {$in: [\"Java\", \"C++\"]}}]}).pretty()", "e": 26670, "s": 26595, "text": null }, { "code": null, "e": 26678, "s": 26670, "text": "MongoDB" }, { "code": null, "e": 26704, "s": 26678, "text": "Advanced Computer Subject" }, { "code": null, "e": 26802, "s": 26704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26846, "s": 26802, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 26870, "s": 26846, "text": "Markov Decision Process" }, { "code": null, "e": 26897, "s": 26870, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 26918, "s": 26897, "text": "Q-Learning in Python" }, { "code": null, "e": 26954, "s": 26918, "text": "An introduction to Machine Learning" }, { "code": null, "e": 26995, "s": 26954, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 27031, "s": 26995, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 27063, "s": 27031, "text": "ML | What is Machine Learning ?" }, { "code": null, "e": 27081, "s": 27063, "text": "OpenCV - Overview" } ]
ML - Different Regression types - GeeksforGeeks
22 Jul, 2021 Regression Analysis:It is a form of predictive modelling technique which investigates the relationship between a dependent (target) and independent variable (s) (predictor).To establish the possible relationship among different variables, various modes of statistical approaches are implemented, known as regression analysis. Basically, regression analysis sets up an equation to explain the significant relationship between one or more predictors and response variables and also to estimate current observations. Regression model comes under the supervised learning, where we are trying to predict results within a continuous output, meaning that we are trying to map input variables to some continuous function. Predicting prices of a house given the features of the house like size, price etc is one of the common examples of Regression Types of regression in ML Linear Regression :Linear regression attempts to model the relationship between two variables by fitting a linear equation to observed data. One variable is considered to be an explanatory variable, and the other is considered to be a dependent variable.It is represented by an equation: Y = a + b*X + ewhere a is intercept, b is slope of the line and e is error term. This equation can be used to predict the value of target variable based on given predictor variable(s).This can be written much more concisely using a vectorized form, as shown:where h? is the hypothesis function, using the model parameters ?. Y = a + b*X + e where a is intercept, b is slope of the line and e is error term. This equation can be used to predict the value of target variable based on given predictor variable(s).This can be written much more concisely using a vectorized form, as shown:where h? is the hypothesis function, using the model parameters ?. Logistic Regression: Some regression algorithm can also be used for classification.Logistic regression is commonly used to estimate the probability that an instance belongs to a particular class. For example, what is the probability that this email is spam?. If the estimated probability is greater than 50% then the instance belongs to that class called the positive class(1) or else it predicts that it does not then it belongs to the negative class(0). This makes it a binary classification.In order to map predicted values to probabilities, we use the sigmoid function. The function maps any real value into another value between 0 and 1. y = 1/(1 + e(-x)). This linear relationship can be written in the following mathematical form: y = 1/(1 + e(-x)). This linear relationship can be written in the following mathematical form: Polynomial Regression: What if our data is actually more complex than a simple straight line? Surprisingly, we can actually use a linear model to fit nonlinear data. A simple way to do this is to add powers of each feature as new features, then train a linear model on this extended set of features. This technique is called Polynomial Regression.The equation below represents a polynomial equation: Softmax Regression: The Logistic Regression model can be generalized to support multiple classes directly, without having to train and combine multiple binary classifiers . This is called Somax Regression, or Multinomial Logistic Regression.The idea is quite simple: when given an instance x, the Softmax Regression model first computes a score sk(x) for each class k, then estimates the probability of each class by applying the somax function (also called the normalized exponential) to the scores.Equation for softmax regression: Ridge Regression: Rigid Regression is a regularized version of Linear Regression where a regularized term is added to the cost function. This forces the learning algorithm to not only fit the data but also keep the model weights as small as possible. Note that the regularized term should not be added to the cost function during training. Once the model is trained, you want to evaluate the model’s performance using the unregularized performance measure. The formula for rigid regression is: Lasso Regression: Similar to Ridge Regression, Lasso (Least Absolute Shrinkage and Selection Operator) is another regularized version of Linera regression : it adds a regularized term to the cost function, but it uses the l1 norm of the weighted vector instead of half the square of the l2 term Lasso regression is given as: Elastic Net Regression: ElasticNet is middle ground between Lasso and Ridge Regression techniques.The regularization term is a simple mix of both Rigid and Lasso’s regularization term. when r=0, Elastic Net is equivalent to Rigid Regression and when r=1, Elastic Net is equivalent to Lasso Regression.The expression for Elastic Net Regression is given as:Need for regression:If we want to do any sort of data analysis on the given data, we need to establish a proper relationship between the dependent and independent variables to do predictions which forms the basis of our evaluation. And that relationships are given by the regression models and thus they form the core for any data analysis.Gradient Descent:Gradient Descent is a very generic optimization algorithm capable of finding optimal solutions to a wide range of problems. The general idea of Gradient Descent is to tweak parameters iteratively in order to minimize a cost function. Here that function is our Loss Function. The loss is the error in our predicted value of m(slope) and c(constant). Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function:Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X.Here y is the actual value and y’ is the predicted value. Lets substitute the value of y’:Now the above equation is minimized using the gradient descent algorithm by partially differentiating it w.r.t m and c.Then finally we update the values of m and c as follow:Code: simple demonstration of Gradient Descent# Making the imports % matplotlib inlineimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltX = np.arange(1, 7)Y = X**2plt.figure(figsize =(10, 10))plt.scatter(X, y, color ="yellow")plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')Output:scatter plotCode:m = 0c = 0 L = 0.0001 # The learning Rateepochs = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(epochs): # The current predicted value of Y Y_pred = m * X + c # Derivative wrt m D_m = (-2 / n) * sum(X * (Y - Y_pred)) # Derivative wrt c D_c = (-2 / n) * sum(Y - Y_pred) # Update m m = m - L * D_m # Update c c = c - L * D_c print (m, c)Output:4.471681318702568 0.6514172394787497 Code:Y_pred = m * X + cplt.figure(figsize =(10, 10))plt.scatter(X, Y, color ="yellow") # regression lineplt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color ='red') plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')plt.show()Output:final resultMy Personal Notes arrow_drop_upSave Need for regression:If we want to do any sort of data analysis on the given data, we need to establish a proper relationship between the dependent and independent variables to do predictions which forms the basis of our evaluation. And that relationships are given by the regression models and thus they form the core for any data analysis. Gradient Descent:Gradient Descent is a very generic optimization algorithm capable of finding optimal solutions to a wide range of problems. The general idea of Gradient Descent is to tweak parameters iteratively in order to minimize a cost function. Here that function is our Loss Function. The loss is the error in our predicted value of m(slope) and c(constant). Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function: Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X. Find the difference between the actual y and predicted y value(y = mx + c), for a given x. Square this difference. Find the mean of the squares for every value in X. Now the above equation is minimized using the gradient descent algorithm by partially differentiating it w.r.t m and c. Then finally we update the values of m and c as follow: Code: simple demonstration of Gradient Descent # Making the imports % matplotlib inlineimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltX = np.arange(1, 7)Y = X**2plt.figure(figsize =(10, 10))plt.scatter(X, y, color ="yellow")plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x') Output: scatter plot m = 0c = 0 L = 0.0001 # The learning Rateepochs = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(epochs): # The current predicted value of Y Y_pred = m * X + c # Derivative wrt m D_m = (-2 / n) * sum(X * (Y - Y_pred)) # Derivative wrt c D_c = (-2 / n) * sum(Y - Y_pred) # Update m m = m - L * D_m # Update c c = c - L * D_c print (m, c) Output: 4.471681318702568 0.6514172394787497 Code: Y_pred = m * X + cplt.figure(figsize =(10, 10))plt.scatter(X, Y, color ="yellow") # regression lineplt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color ='red') plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')plt.show() Output: final result Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Regression and Classification | Supervised Machine Learning ML - Content Based Recommender System Singular Value Decomposition (SVD) Recommendation System in Python Collaborative Filtering - ML Regularization in Machine Learning Expert Systems Intuition of Adam Optimizer Random Forest Classifier using Scikit-learn Gradient Descent in Linear Regression
[ { "code": null, "e": 25613, "s": 25585, "text": "\n22 Jul, 2021" }, { "code": null, "e": 26453, "s": 25613, "text": "Regression Analysis:It is a form of predictive modelling technique which investigates the relationship between a dependent (target) and independent variable (s) (predictor).To establish the possible relationship among different variables, various modes of statistical approaches are implemented, known as regression analysis. Basically, regression analysis sets up an equation to explain the significant relationship between one or more predictors and response variables and also to estimate current observations. Regression model comes under the supervised learning, where we are trying to predict results within a continuous output, meaning that we are trying to map input variables to some continuous function. Predicting prices of a house given the features of the house like size, price etc is one of the common examples of Regression" }, { "code": null, "e": 26479, "s": 26453, "text": "Types of regression in ML" }, { "code": null, "e": 27092, "s": 26479, "text": "Linear Regression :Linear regression attempts to model the relationship between two variables by fitting a linear equation to observed data. One variable is considered to be an explanatory variable, and the other is considered to be a dependent variable.It is represented by an equation: Y = a + b*X + ewhere a is intercept, b is slope of the line and e is error term. This equation can be used to predict the value of target variable based on given predictor variable(s).This can be written much more concisely using a vectorized form, as shown:where h? is the hypothesis function, using the model parameters ?." }, { "code": null, "e": 27109, "s": 27092, "text": " Y = a + b*X + e" }, { "code": null, "e": 27419, "s": 27109, "text": "where a is intercept, b is slope of the line and e is error term. This equation can be used to predict the value of target variable based on given predictor variable(s).This can be written much more concisely using a vectorized form, as shown:where h? is the hypothesis function, using the model parameters ?." }, { "code": null, "e": 28157, "s": 27419, "text": "Logistic Regression: Some regression algorithm can also be used for classification.Logistic regression is commonly used to estimate the probability that an instance belongs to a particular class. For example, what is the probability that this email is spam?. If the estimated probability is greater than 50% then the instance belongs to that class called the positive class(1) or else it predicts that it does not then it belongs to the negative class(0). This makes it a binary classification.In order to map predicted values to probabilities, we use the sigmoid function. The function maps any real value into another value between 0 and 1. y = 1/(1 + e(-x)). This linear relationship can be written in the following mathematical form:" }, { "code": null, "e": 28178, "s": 28157, "text": " y = 1/(1 + e(-x)). " }, { "code": null, "e": 28254, "s": 28178, "text": "This linear relationship can be written in the following mathematical form:" }, { "code": null, "e": 28655, "s": 28254, "text": "Polynomial Regression: What if our data is actually more complex than a simple straight line? Surprisingly, we can actually use a linear model to fit nonlinear data. A simple way to do this is to add powers of each feature as new features, then train a linear model on this extended set of features. This technique is called Polynomial Regression.The equation below represents a polynomial equation: " }, { "code": null, "e": 29191, "s": 28655, "text": "Softmax Regression: The Logistic Regression model can be generalized to support multiple classes directly, without having to train and combine multiple binary classifiers . This is called Somax Regression, or Multinomial Logistic Regression.The idea is quite simple: when given an instance x, the Softmax Regression model first computes a score sk(x) for each class k, then estimates the probability of each class by applying the somax function (also called the normalized exponential) to the scores.Equation for softmax regression: " }, { "code": null, "e": 29685, "s": 29191, "text": "Ridge Regression: Rigid Regression is a regularized version of Linear Regression where a regularized term is added to the cost function. This forces the learning algorithm to not only fit the data but also keep the model weights as small as possible. Note that the regularized term should not be added to the cost function during training. Once the model is trained, you want to evaluate the model’s performance using the unregularized performance measure. The formula for rigid regression is:" }, { "code": null, "e": 30010, "s": 29685, "text": "Lasso Regression: Similar to Ridge Regression, Lasso (Least Absolute Shrinkage and Selection Operator) is another regularized version of Linera regression : it adds a regularized term to the cost function, but it uses the l1 norm of the weighted vector instead of half the square of the l2 term Lasso regression is given as:" }, { "code": null, "e": 32968, "s": 30010, "text": "Elastic Net Regression: ElasticNet is middle ground between Lasso and Ridge Regression techniques.The regularization term is a simple mix of both Rigid and Lasso’s regularization term. when r=0, Elastic Net is equivalent to Rigid Regression and when r=1, Elastic Net is equivalent to Lasso Regression.The expression for Elastic Net Regression is given as:Need for regression:If we want to do any sort of data analysis on the given data, we need to establish a proper relationship between the dependent and independent variables to do predictions which forms the basis of our evaluation. And that relationships are given by the regression models and thus they form the core for any data analysis.Gradient Descent:Gradient Descent is a very generic optimization algorithm capable of finding optimal solutions to a wide range of problems. The general idea of Gradient Descent is to tweak parameters iteratively in order to minimize a cost function. Here that function is our Loss Function. The loss is the error in our predicted value of m(slope) and c(constant). Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function:Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X.Here y is the actual value and y’ is the predicted value. Lets substitute the value of y’:Now the above equation is minimized using the gradient descent algorithm by partially differentiating it w.r.t m and c.Then finally we update the values of m and c as follow:Code: simple demonstration of Gradient Descent# Making the imports % matplotlib inlineimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltX = np.arange(1, 7)Y = X**2plt.figure(figsize =(10, 10))plt.scatter(X, y, color =\"yellow\")plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')Output:scatter plotCode:m = 0c = 0 L = 0.0001 # The learning Rateepochs = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(epochs): # The current predicted value of Y Y_pred = m * X + c # Derivative wrt m D_m = (-2 / n) * sum(X * (Y - Y_pred)) # Derivative wrt c D_c = (-2 / n) * sum(Y - Y_pred) # Update m m = m - L * D_m # Update c c = c - L * D_c print (m, c)Output:4.471681318702568 0.6514172394787497\nCode:Y_pred = m * X + cplt.figure(figsize =(10, 10))plt.scatter(X, Y, color =\"yellow\") # regression lineplt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color ='red') plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')plt.show()Output:final resultMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33309, "s": 32968, "text": "Need for regression:If we want to do any sort of data analysis on the given data, we need to establish a proper relationship between the dependent and independent variables to do predictions which forms the basis of our evaluation. And that relationships are given by the regression models and thus they form the core for any data analysis." }, { "code": null, "e": 33862, "s": 33309, "text": "Gradient Descent:Gradient Descent is a very generic optimization algorithm capable of finding optimal solutions to a wide range of problems. The general idea of Gradient Descent is to tweak parameters iteratively in order to minimize a cost function. Here that function is our Loss Function. The loss is the error in our predicted value of m(slope) and c(constant). Our goal is to minimize this error to obtain the most accurate value of m and c.We will use the Mean Squared Error function to calculate the loss. There are three steps in this function:" }, { "code": null, "e": 34026, "s": 33862, "text": "Find the difference between the actual y and predicted y value(y = mx + c), for a given x.Square this difference.Find the mean of the squares for every value in X." }, { "code": null, "e": 34117, "s": 34026, "text": "Find the difference between the actual y and predicted y value(y = mx + c), for a given x." }, { "code": null, "e": 34141, "s": 34117, "text": "Square this difference." }, { "code": null, "e": 34192, "s": 34141, "text": "Find the mean of the squares for every value in X." }, { "code": null, "e": 34312, "s": 34192, "text": "Now the above equation is minimized using the gradient descent algorithm by partially differentiating it w.r.t m and c." }, { "code": null, "e": 34368, "s": 34312, "text": "Then finally we update the values of m and c as follow:" }, { "code": null, "e": 34415, "s": 34368, "text": "Code: simple demonstration of Gradient Descent" }, { "code": "# Making the imports % matplotlib inlineimport pandas as pdimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltX = np.arange(1, 7)Y = X**2plt.figure(figsize =(10, 10))plt.scatter(X, y, color =\"yellow\")plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')", "e": 34748, "s": 34415, "text": null }, { "code": null, "e": 34756, "s": 34748, "text": "Output:" }, { "code": null, "e": 34769, "s": 34756, "text": "scatter plot" }, { "code": "m = 0c = 0 L = 0.0001 # The learning Rateepochs = 1000 # The number of iterations to perform gradient descent n = float(len(X)) # Number of elements in X # Performing Gradient Descent for i in range(epochs): # The current predicted value of Y Y_pred = m * X + c # Derivative wrt m D_m = (-2 / n) * sum(X * (Y - Y_pred)) # Derivative wrt c D_c = (-2 / n) * sum(Y - Y_pred) # Update m m = m - L * D_m # Update c c = c - L * D_c print (m, c)", "e": 35259, "s": 34769, "text": null }, { "code": null, "e": 35267, "s": 35259, "text": "Output:" }, { "code": null, "e": 35305, "s": 35267, "text": "4.471681318702568 0.6514172394787497\n" }, { "code": null, "e": 35311, "s": 35305, "text": "Code:" }, { "code": "Y_pred = m * X + cplt.figure(figsize =(10, 10))plt.scatter(X, Y, color =\"yellow\") # regression lineplt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color ='red') plt.title('sample demonstration of gradient descent')plt.ylabel('squared value-y')plt.xlabel('linear value-x')plt.show()", "e": 35601, "s": 35311, "text": null }, { "code": null, "e": 35609, "s": 35601, "text": "Output:" }, { "code": null, "e": 35622, "s": 35609, "text": "final result" }, { "code": null, "e": 35639, "s": 35622, "text": "Machine Learning" }, { "code": null, "e": 35656, "s": 35639, "text": "Machine Learning" }, { "code": null, "e": 35754, "s": 35656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35814, "s": 35754, "text": "Regression and Classification | Supervised Machine Learning" }, { "code": null, "e": 35852, "s": 35814, "text": "ML - Content Based Recommender System" }, { "code": null, "e": 35887, "s": 35852, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 35919, "s": 35887, "text": "Recommendation System in Python" }, { "code": null, "e": 35948, "s": 35919, "text": "Collaborative Filtering - ML" }, { "code": null, "e": 35983, "s": 35948, "text": "Regularization in Machine Learning" }, { "code": null, "e": 35998, "s": 35983, "text": "Expert Systems" }, { "code": null, "e": 36026, "s": 35998, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 36070, "s": 36026, "text": "Random Forest Classifier using Scikit-learn" } ]
ffuf - Fast Web Fuzzer Linux Tool Written in Go - GeeksforGeeks
14 Sep, 2021 Fuzzing is the automatic process of giving random input to an application to look for any errors or any unexpected behavior. But finding any hidden directories and files on any web server can also be categorized under fuzzing. If we try to perform this process manually then it can take dozens of months to find the directories on the server. So the automation approach is the best for performing fuzzing. FFUF is the automated tool developed in the Golang language which is the fastest fuzzer tool in today’s date. It has various key features of manipulation the method from GET to POST and vice versa. We can use various wordlists for fuzzing the vhost as well. FFUF tool is an open-source and free-to-use tool. Note: As Ffuf is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command. go version Step 2: Get the Ffuf repository or clone the Ffuf tool from GitHub, use the following command. sudo GO111MODULE=on go get -u github.com/ffuf/ffuf Step 3: Check the version of the Ffuf tool using the following command. ffuf -V Step 4: Check the help menu page to get a better understanding of the Ffuf tool, use the following command. ffuf -h When the execution of the ffuf tool is started the tool firstly checks its default configuration file exits or not. Mostly the path of the configuration file is at ~/.ffufrc /$HOME/.ffufrc or can be at /home/gaurav/.ffufrc. In Windows OS this path can vary and mostly it can be at %USERPROFILE%\.ffufrc. There are configuration options provided on the terminal that override the ones loaded from the ~/.ffufrc file. For example, If you wish to use a bunch of configuration files for various scenarios, then you can define the configuration file path by using the -config tag which takes the file path to the configuration file as its parameter. Example 1: Typical directory discovery ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u https://geeksforgeeks.org/FUZZ In this example, We are fuzzing the directories of geeksforgeeks.org target domain. Example 2: Virtual host discovery (without DNS records) ffuf -w /usr/share/wordlists/vhost.txt -u https://geeksforgeeks.org -H “Host: FUZZ” -fs 4242 In this example, We are filtering out VHOST default port 4242 specified in the -fs tag. Example 3: GET parameter fuzzing ffuf -w /usr/share/wordlists/parameters.txt -u http://testphp.vulnweb.com/search.php?FUZZ=test_value -fs 4242 In this example, We are using the GET method for fuzzing the directories. Example 4: Maximum execution time ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u https://geeksforgeeks.org/FUZZ -maxtime 60 In this example, We are specifying the maximum request time. We have used -maxtime tag for specifying the time. Example 4: POST Data Fuzzing ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -X POST -d “username=admin\&password=FUZZ” -u https://testphp.vulnweb.com/login.php -fc 401 In this example, We are using the POST method for fuzzing the directories. Example 5: Using an external mutator to produce test cases ffuf –input-cmd ‘radamsa –seed $FFUF_NUM example1.txt example2.txt’ -H “Content-Type: application/json” -X POST -u https://testphp.vulnweb.com/ -mc all -fc 400 In this example, We’ll fuzz JSON data that’s sent over POST. Radamsa s used as the mutator. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26365, "s": 25651, "text": "Fuzzing is the automatic process of giving random input to an application to look for any errors or any unexpected behavior. But finding any hidden directories and files on any web server can also be categorized under fuzzing. If we try to perform this process manually then it can take dozens of months to find the directories on the server. So the automation approach is the best for performing fuzzing. FFUF is the automated tool developed in the Golang language which is the fastest fuzzer tool in today’s date. It has various key features of manipulation the method from GET to POST and vice versa. We can use various wordlists for fuzzing the vhost as well. FFUF tool is an open-source and free-to-use tool." }, { "code": null, "e": 26558, "s": 26365, "text": "Note: As Ffuf is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux" }, { "code": null, "e": 26698, "s": 26558, "text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command." }, { "code": null, "e": 26709, "s": 26698, "text": "go version" }, { "code": null, "e": 26804, "s": 26709, "text": "Step 2: Get the Ffuf repository or clone the Ffuf tool from GitHub, use the following command." }, { "code": null, "e": 26855, "s": 26804, "text": "sudo GO111MODULE=on go get -u github.com/ffuf/ffuf" }, { "code": null, "e": 26927, "s": 26855, "text": "Step 3: Check the version of the Ffuf tool using the following command." }, { "code": null, "e": 26935, "s": 26927, "text": "ffuf -V" }, { "code": null, "e": 27043, "s": 26935, "text": "Step 4: Check the help menu page to get a better understanding of the Ffuf tool, use the following command." }, { "code": null, "e": 27051, "s": 27043, "text": "ffuf -h" }, { "code": null, "e": 27696, "s": 27051, "text": "When the execution of the ffuf tool is started the tool firstly checks its default configuration file exits or not. Mostly the path of the configuration file is at ~/.ffufrc /$HOME/.ffufrc or can be at /home/gaurav/.ffufrc. In Windows OS this path can vary and mostly it can be at %USERPROFILE%\\.ffufrc. There are configuration options provided on the terminal that override the ones loaded from the ~/.ffufrc file. For example, If you wish to use a bunch of configuration files for various scenarios, then you can define the configuration file path by using the -config tag which takes the file path to the configuration file as its parameter." }, { "code": null, "e": 27735, "s": 27696, "text": "Example 1: Typical directory discovery" }, { "code": null, "e": 27838, "s": 27735, "text": "ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u https://geeksforgeeks.org/FUZZ" }, { "code": null, "e": 27922, "s": 27838, "text": "In this example, We are fuzzing the directories of geeksforgeeks.org target domain." }, { "code": null, "e": 27978, "s": 27922, "text": "Example 2: Virtual host discovery (without DNS records)" }, { "code": null, "e": 28071, "s": 27978, "text": "ffuf -w /usr/share/wordlists/vhost.txt -u https://geeksforgeeks.org -H “Host: FUZZ” -fs 4242" }, { "code": null, "e": 28159, "s": 28071, "text": "In this example, We are filtering out VHOST default port 4242 specified in the -fs tag." }, { "code": null, "e": 28192, "s": 28159, "text": "Example 3: GET parameter fuzzing" }, { "code": null, "e": 28302, "s": 28192, "text": "ffuf -w /usr/share/wordlists/parameters.txt -u http://testphp.vulnweb.com/search.php?FUZZ=test_value -fs 4242" }, { "code": null, "e": 28376, "s": 28302, "text": "In this example, We are using the GET method for fuzzing the directories." }, { "code": null, "e": 28410, "s": 28376, "text": "Example 4: Maximum execution time" }, { "code": null, "e": 28525, "s": 28410, "text": "ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u https://geeksforgeeks.org/FUZZ -maxtime 60" }, { "code": null, "e": 28637, "s": 28525, "text": "In this example, We are specifying the maximum request time. We have used -maxtime tag for specifying the time." }, { "code": null, "e": 28666, "s": 28637, "text": "Example 4: POST Data Fuzzing" }, { "code": null, "e": 28827, "s": 28666, "text": "ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -X POST -d “username=admin\\&password=FUZZ” -u https://testphp.vulnweb.com/login.php -fc 401" }, { "code": null, "e": 28902, "s": 28827, "text": "In this example, We are using the POST method for fuzzing the directories." }, { "code": null, "e": 28961, "s": 28902, "text": "Example 5: Using an external mutator to produce test cases" }, { "code": null, "e": 29121, "s": 28961, "text": "ffuf –input-cmd ‘radamsa –seed $FFUF_NUM example1.txt example2.txt’ -H “Content-Type: application/json” -X POST -u https://testphp.vulnweb.com/ -mc all -fc 400" }, { "code": null, "e": 29213, "s": 29121, "text": "In this example, We’ll fuzz JSON data that’s sent over POST. Radamsa s used as the mutator." }, { "code": null, "e": 29224, "s": 29213, "text": "Kali-Linux" }, { "code": null, "e": 29236, "s": 29224, "text": "Linux-Tools" }, { "code": null, "e": 29247, "s": 29236, "text": "Linux-Unix" }, { "code": null, "e": 29345, "s": 29247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29380, "s": 29345, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29414, "s": 29380, "text": "mv command in Linux with examples" }, { "code": null, "e": 29440, "s": 29414, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29469, "s": 29440, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29506, "s": 29469, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29543, "s": 29506, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29585, "s": 29543, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29611, "s": 29585, "text": "Thread functions in C/C++" }, { "code": null, "e": 29647, "s": 29611, "text": "uniq Command in LINUX with examples" } ]
JavaScript Basic Array Methods - GeeksforGeeks
28 Mar, 2022 It’s recommended to go through Arrays in JavaScript . We would be discussing the following array function: Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.Syntax :Array.push(item1, item2 ...) Parameters: Items to be added to an array. Description: This method is used add elements at the end of an array.JavaScriptJavaScript// Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ "piyush", "gourav", "smruti", "ritu" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// ["piyush", "gourav", "smruti", "ritu", "sumit", "amit"];string_arr.push("sumit", "amit"); // Printing both the array after performing push operationconsole.log("After push op " + number_arr);console.log("After push op " + string_arr);Array.unshift() : Adding elements at the front of an ArraySyntax :Array.unshift(item1, item2 ...) Parameters: Items to be added to the arrayDescription: This method is used to add elements at the beginning of an array.JavaScriptJavaScript// Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ "amit", "sumit" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// ["sunil", "anil", "amit", "sumit"]string_arr.unshift("sunil", "anil"); // Printing both the array after performing unshift operationconsole.log("After unshift op " + number_arr);console.log("After unshift op " + string_arr);Array.pop() : Removing elements from the end of an arraySyntax:Array.pop() Parameters: It takes no parameter Description: It is used to remove array elements from the end of an array.JavaScriptJavaScript// Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ "amit", "sumit", "anil" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// ["amit", "sumit"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log("After pop op " + number_arr);console.log("After popo op " + string_arr);Array.shift() : Removing elements at the beginning of an arraySyntax :Array.shift() Parameter : it takes no parameter Description : It is used to remove array at the beginning of an array.JavaScriptJavaScript// Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// ["sumit", "anil", "prateek"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log("After shift op " + number_arr);console.log("After shift op " + string_arr);Array.splice() : Insertion and Removal in between an ArraySyntax:Array.splice (start, deleteCount, item 1, item 2....) Parameters: Start : Location at which to perform operation deleteCount: Number of element to be deleted, if no element is to be deleted pass 0. Item1, item2 .....- this is an optional parameter . These are the elements to be inserted from location start Description: Splice is very useful method as it can remove and add elements from the particular location.JavaScriptJavaScript// Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];string_arr.splice(1, 2, "xyz", "geek 1", "geek 2"); // Printing both the array after performing splice operationconsole.log("After splice op " + number_arr);console.log("After splice op " + string_arr); Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.Syntax :Array.push(item1, item2 ...) Parameters: Items to be added to an array. Description: This method is used add elements at the end of an array.JavaScriptJavaScript// Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ "piyush", "gourav", "smruti", "ritu" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// ["piyush", "gourav", "smruti", "ritu", "sumit", "amit"];string_arr.push("sumit", "amit"); // Printing both the array after performing push operationconsole.log("After push op " + number_arr);console.log("After push op " + string_arr); Array.push(item1, item2 ...) Parameters: Items to be added to an array. Description: This method is used add elements at the end of an array. JavaScript // Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ "piyush", "gourav", "smruti", "ritu" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// ["piyush", "gourav", "smruti", "ritu", "sumit", "amit"];string_arr.push("sumit", "amit"); // Printing both the array after performing push operationconsole.log("After push op " + number_arr);console.log("After push op " + string_arr); Array.unshift() : Adding elements at the front of an ArraySyntax :Array.unshift(item1, item2 ...) Parameters: Items to be added to the arrayDescription: This method is used to add elements at the beginning of an array.JavaScriptJavaScript// Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ "amit", "sumit" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// ["sunil", "anil", "amit", "sumit"]string_arr.unshift("sunil", "anil"); // Printing both the array after performing unshift operationconsole.log("After unshift op " + number_arr);console.log("After unshift op " + string_arr); Array.unshift(item1, item2 ...) Parameters: Items to be added to the array Description: This method is used to add elements at the beginning of an array. JavaScript // Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ "amit", "sumit" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// ["sunil", "anil", "amit", "sumit"]string_arr.unshift("sunil", "anil"); // Printing both the array after performing unshift operationconsole.log("After unshift op " + number_arr);console.log("After unshift op " + string_arr); Array.pop() : Removing elements from the end of an arraySyntax:Array.pop() Parameters: It takes no parameter Description: It is used to remove array elements from the end of an array.JavaScriptJavaScript// Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ "amit", "sumit", "anil" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// ["amit", "sumit"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log("After pop op " + number_arr);console.log("After popo op " + string_arr); Array.pop() Parameters: It takes no parameter Description: It is used to remove array elements from the end of an array. JavaScript // Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ "amit", "sumit", "anil" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// ["amit", "sumit"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log("After pop op " + number_arr);console.log("After popo op " + string_arr); Array.shift() : Removing elements at the beginning of an arraySyntax :Array.shift() Parameter : it takes no parameter Description : It is used to remove array at the beginning of an array.JavaScriptJavaScript// Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// ["sumit", "anil", "prateek"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log("After shift op " + number_arr);console.log("After shift op " + string_arr); Array.shift() Parameter : it takes no parameter Description : It is used to remove array at the beginning of an array. JavaScript // Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// ["sumit", "anil", "prateek"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log("After shift op " + number_arr);console.log("After shift op " + string_arr); Array.splice() : Insertion and Removal in between an ArraySyntax:Array.splice (start, deleteCount, item 1, item 2....) Parameters: Start : Location at which to perform operation deleteCount: Number of element to be deleted, if no element is to be deleted pass 0. Item1, item2 .....- this is an optional parameter . These are the elements to be inserted from location start Description: Splice is very useful method as it can remove and add elements from the particular location.JavaScriptJavaScript// Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];string_arr.splice(1, 2, "xyz", "geek 1", "geek 2"); // Printing both the array after performing splice operationconsole.log("After splice op " + number_arr);console.log("After splice op " + string_arr); Array.splice (start, deleteCount, item 1, item 2....) Parameters: Start : Location at which to perform operation deleteCount: Number of element to be deleted, if no element is to be deleted pass 0. Item1, item2 .....- this is an optional parameter . These are the elements to be inserted from location start Description: Splice is very useful method as it can remove and add elements from the particular location. JavaScript // Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ "amit", "sumit", "anil", "prateek" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];string_arr.splice(1, 2, "xyz", "geek 1", "geek 2"); // Printing both the array after performing splice operationconsole.log("After splice op " + number_arr);console.log("After splice op " + string_arr); JavaScript provides various functions on array refer to the link below: Functions Part 1 Functions Part 2 Functions Part 3 Note :All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console. This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sarmisthadutta yogigoodman javascript-array JavaScript-Misc Articles JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis) Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 31327, "s": 31299, "text": "\n28 Mar, 2022" }, { "code": null, "e": 31434, "s": 31327, "text": "It’s recommended to go through Arrays in JavaScript . We would be discussing the following array function:" }, { "code": null, "e": 35773, "s": 31434, "text": "Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.Syntax :Array.push(item1, item2 ...)\nParameters: Items to be added to an array.\nDescription: This method is used add elements at the end of an array.JavaScriptJavaScript// Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ \"piyush\", \"gourav\", \"smruti\", \"ritu\" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// [\"piyush\", \"gourav\", \"smruti\", \"ritu\", \"sumit\", \"amit\"];string_arr.push(\"sumit\", \"amit\"); // Printing both the array after performing push operationconsole.log(\"After push op \" + number_arr);console.log(\"After push op \" + string_arr);Array.unshift() : Adding elements at the front of an ArraySyntax :Array.unshift(item1, item2 ...)\nParameters: Items to be added to the arrayDescription: This method is used to add elements at the beginning of an array.JavaScriptJavaScript// Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ \"amit\", \"sumit\" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// [\"sunil\", \"anil\", \"amit\", \"sumit\"]string_arr.unshift(\"sunil\", \"anil\"); // Printing both the array after performing unshift operationconsole.log(\"After unshift op \" + number_arr);console.log(\"After unshift op \" + string_arr);Array.pop() : Removing elements from the end of an arraySyntax:Array.pop()\nParameters: It takes no parameter\nDescription: It is used to remove array elements from the end of an array.JavaScriptJavaScript// Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ \"amit\", \"sumit\", \"anil\" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// [\"amit\", \"sumit\"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log(\"After pop op \" + number_arr);console.log(\"After popo op \" + string_arr);Array.shift() : Removing elements at the beginning of an arraySyntax :Array.shift()\nParameter : it takes no parameter\nDescription : It is used to remove array at the beginning of an array.JavaScriptJavaScript// Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// [\"sumit\", \"anil\", \"prateek\"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log(\"After shift op \" + number_arr);console.log(\"After shift op \" + string_arr);Array.splice() : Insertion and Removal in between an ArraySyntax:Array.splice (start, deleteCount, item 1, item 2....) \nParameters: \nStart : Location at which to perform operation\ndeleteCount: Number of element to be deleted, \nif no element is to be deleted pass 0.\nItem1, item2 .....- this is an optional parameter . \nThese are the elements to be inserted from location start Description: Splice is very useful method as it can remove and add elements from the particular location.JavaScriptJavaScript// Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains [\"amit\", \"xyz\", \"geek 1\", \"geek 2\", \"prateek\"];string_arr.splice(1, 2, \"xyz\", \"geek 1\", \"geek 2\"); // Printing both the array after performing splice operationconsole.log(\"After splice op \" + number_arr);console.log(\"After splice op \" + string_arr);" }, { "code": null, "e": 36815, "s": 35773, "text": "Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.Syntax :Array.push(item1, item2 ...)\nParameters: Items to be added to an array.\nDescription: This method is used add elements at the end of an array.JavaScriptJavaScript// Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ \"piyush\", \"gourav\", \"smruti\", \"ritu\" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// [\"piyush\", \"gourav\", \"smruti\", \"ritu\", \"sumit\", \"amit\"];string_arr.push(\"sumit\", \"amit\"); // Printing both the array after performing push operationconsole.log(\"After push op \" + number_arr);console.log(\"After push op \" + string_arr);" }, { "code": null, "e": 36888, "s": 36815, "text": "Array.push(item1, item2 ...)\nParameters: Items to be added to an array.\n" }, { "code": null, "e": 36958, "s": 36888, "text": "Description: This method is used add elements at the end of an array." }, { "code": null, "e": 36969, "s": 36958, "text": "JavaScript" }, { "code": "// Adding elements at the end of an array// Declaring and initializing arraysvar number_arr = [ 10, 20, 30, 40, 50 ];var string_arr = [ \"piyush\", \"gourav\", \"smruti\", \"ritu\" ]; // push()// number_arr contains [10, 20, 30, 40, 50, 60]number_arr.push(60); // We can pass multiple parameters to the push()// number_arr contains// [10, 20, 30, 40, 50, 60, 70, 80, 90]number_arr.push(70, 80, 90); // string_arr contains// [\"piyush\", \"gourav\", \"smruti\", \"ritu\", \"sumit\", \"amit\"];string_arr.push(\"sumit\", \"amit\"); // Printing both the array after performing push operationconsole.log(\"After push op \" + number_arr);console.log(\"After push op \" + string_arr);", "e": 37624, "s": 36969, "text": null }, { "code": null, "e": 38352, "s": 37624, "text": "Array.unshift() : Adding elements at the front of an ArraySyntax :Array.unshift(item1, item2 ...)\nParameters: Items to be added to the arrayDescription: This method is used to add elements at the beginning of an array.JavaScriptJavaScript// Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ \"amit\", \"sumit\" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// [\"sunil\", \"anil\", \"amit\", \"sumit\"]string_arr.unshift(\"sunil\", \"anil\"); // Printing both the array after performing unshift operationconsole.log(\"After unshift op \" + number_arr);console.log(\"After unshift op \" + string_arr);" }, { "code": null, "e": 38427, "s": 38352, "text": "Array.unshift(item1, item2 ...)\nParameters: Items to be added to the array" }, { "code": null, "e": 38506, "s": 38427, "text": "Description: This method is used to add elements at the beginning of an array." }, { "code": null, "e": 38517, "s": 38506, "text": "JavaScript" }, { "code": "// Adding element at the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40 ];var string_arr = [ \"amit\", \"sumit\" ]; // unshift()// number_arr contains// [10, 20, 20, 30, 40]number_arr.unshift(10, 20); // string_arr contains// [\"sunil\", \"anil\", \"amit\", \"sumit\"]string_arr.unshift(\"sunil\", \"anil\"); // Printing both the array after performing unshift operationconsole.log(\"After unshift op \" + number_arr);console.log(\"After unshift op \" + string_arr);", "e": 39007, "s": 38517, "text": null }, { "code": null, "e": 39644, "s": 39007, "text": "Array.pop() : Removing elements from the end of an arraySyntax:Array.pop()\nParameters: It takes no parameter\nDescription: It is used to remove array elements from the end of an array.JavaScriptJavaScript// Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ \"amit\", \"sumit\", \"anil\" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// [\"amit\", \"sumit\"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log(\"After pop op \" + number_arr);console.log(\"After popo op \" + string_arr);" }, { "code": null, "e": 39691, "s": 39644, "text": "Array.pop()\nParameters: It takes no parameter\n" }, { "code": null, "e": 39766, "s": 39691, "text": "Description: It is used to remove array elements from the end of an array." }, { "code": null, "e": 39777, "s": 39766, "text": "JavaScript" }, { "code": "// Removing elements from the end of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50 ];var string_arr = [ \"amit\", \"sumit\", \"anil\" ]; // pop()// number_arr contains// [ 20, 30, 40 ]number_arr.pop(); // string_arr contains// [\"amit\", \"sumit\"]string_arr.pop(); // Printing both the array after performing pop operationconsole.log(\"After pop op \" + number_arr);console.log(\"After popo op \" + string_arr);", "e": 40211, "s": 39777, "text": null }, { "code": null, "e": 40900, "s": 40211, "text": "Array.shift() : Removing elements at the beginning of an arraySyntax :Array.shift()\nParameter : it takes no parameter\nDescription : It is used to remove array at the beginning of an array.JavaScriptJavaScript// Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// [\"sumit\", \"anil\", \"prateek\"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log(\"After shift op \" + number_arr);console.log(\"After shift op \" + string_arr);" }, { "code": null, "e": 40949, "s": 40900, "text": "Array.shift()\nParameter : it takes no parameter\n" }, { "code": null, "e": 41020, "s": 40949, "text": "Description : It is used to remove array at the beginning of an array." }, { "code": null, "e": 41031, "s": 41020, "text": "JavaScript" }, { "code": "// Removing element from the beginning of an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // shift()// number_arr contains// [30, 40, 50, 60];number_arr.shift(); // string_arr contains// [\"sumit\", \"anil\", \"prateek\"]string_arr.shift(); // Printing both the array after performing shifts operationconsole.log(\"After shift op \" + number_arr);console.log(\"After shift op \" + string_arr);", "e": 41512, "s": 41031, "text": null }, { "code": null, "e": 42759, "s": 41512, "text": "Array.splice() : Insertion and Removal in between an ArraySyntax:Array.splice (start, deleteCount, item 1, item 2....) \nParameters: \nStart : Location at which to perform operation\ndeleteCount: Number of element to be deleted, \nif no element is to be deleted pass 0.\nItem1, item2 .....- this is an optional parameter . \nThese are the elements to be inserted from location start Description: Splice is very useful method as it can remove and add elements from the particular location.JavaScriptJavaScript// Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains [\"amit\", \"xyz\", \"geek 1\", \"geek 2\", \"prateek\"];string_arr.splice(1, 2, \"xyz\", \"geek 1\", \"geek 2\"); // Printing both the array after performing splice operationconsole.log(\"After splice op \" + number_arr);console.log(\"After splice op \" + string_arr);" }, { "code": null, "e": 43073, "s": 42759, "text": "Array.splice (start, deleteCount, item 1, item 2....) \nParameters: \nStart : Location at which to perform operation\ndeleteCount: Number of element to be deleted, \nif no element is to be deleted pass 0.\nItem1, item2 .....- this is an optional parameter . \nThese are the elements to be inserted from location start " }, { "code": null, "e": 43179, "s": 43073, "text": "Description: Splice is very useful method as it can remove and add elements from the particular location." }, { "code": null, "e": 43190, "s": 43179, "text": "JavaScript" }, { "code": "// Removing an adding element at a particular location// in an array// Declaring and initializing arraysvar number_arr = [ 20, 30, 40, 50, 60 ];var string_arr = [ \"amit\", \"sumit\", \"anil\", \"prateek\" ]; // splice()// deletes 3 elements starting from 1// number array contains [20, 60]number_arr.splice(1, 3); // doesn't delete but inserts 3, 4, 5// at starting location 1number_arr.splice(1, 0, 3, 4, 5); // deletes two elements starting from index 1// and add three elements.// It contains [\"amit\", \"xyz\", \"geek 1\", \"geek 2\", \"prateek\"];string_arr.splice(1, 2, \"xyz\", \"geek 1\", \"geek 2\"); // Printing both the array after performing splice operationconsole.log(\"After splice op \" + number_arr);console.log(\"After splice op \" + string_arr);", "e": 43934, "s": 43190, "text": null }, { "code": null, "e": 44006, "s": 43934, "text": "JavaScript provides various functions on array refer to the link below:" }, { "code": null, "e": 44023, "s": 44006, "text": "Functions Part 1" }, { "code": null, "e": 44040, "s": 44023, "text": "Functions Part 2" }, { "code": null, "e": 44057, "s": 44040, "text": "Functions Part 3" }, { "code": null, "e": 44185, "s": 44057, "text": "Note :All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console." }, { "code": null, "e": 44484, "s": 44185, "text": "This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 44609, "s": 44484, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 44624, "s": 44609, "text": "sarmisthadutta" }, { "code": null, "e": 44636, "s": 44624, "text": "yogigoodman" }, { "code": null, "e": 44653, "s": 44636, "text": "javascript-array" }, { "code": null, "e": 44669, "s": 44653, "text": "JavaScript-Misc" }, { "code": null, "e": 44678, "s": 44669, "text": "Articles" }, { "code": null, "e": 44689, "s": 44678, "text": "JavaScript" }, { "code": null, "e": 44787, "s": 44689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44837, "s": 44787, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 44884, "s": 44837, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 44920, "s": 44884, "text": "find command in Linux with examples" }, { "code": null, "e": 44948, "s": 44920, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 45001, "s": 44948, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 45041, "s": 45001, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 45086, "s": 45041, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45147, "s": 45086, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45219, "s": 45147, "text": "Differences between Functional Components and Class Components in React" } ]
Find Characteristic Polynomial of a Square Matrix - GeeksforGeeks
04 Apr, 2022 In linear algebra, the characteristic polynomial of a square matrix is a polynomial that is invariant under matrix similarity and has the eigenvalues as roots. It has the determinant and the trace of the matrix among its coefficients. The characteristic polynomial of the 3×3 matrix can be calculated using the formula x3 – (Trace of matrix)*x2 + (Sum of minors along diagonal)*x – determinant of matrix = 0 Example: Input: mat[][] = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }Output: x^3 – 6x + 4 Approach: Lets break up the formula and find the value of each term one by one: Trace of the matrix Trace of a Matrix the sum of elements along its diagonal. Trace of Matrix Minor of the matrix The minor of the matrix is for each element of the matrix and is equal to the part of the matrix remaining after excluding the row and the column containing that particular element. The new matrix formed with the minors of each element of the given matrix is called the minor of the matrix.Each new element of the minor matrix can be achieved as follows: The minor of the matrix is for each element of the matrix and is equal to the part of the matrix remaining after excluding the row and the column containing that particular element. The new matrix formed with the minors of each element of the given matrix is called the minor of the matrix. Each new element of the minor matrix can be achieved as follows: Determinant of a matrix Determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). The determinant is used at many places in calculus and another matrix-related algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of linear equations and finding the inverse of a matrix. Determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). The determinant is used at many places in calculus and another matrix-related algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of linear equations and finding the inverse of a matrix. Program to find Characteristic Polynomial of a Square Matrix C++ Java Python3 C# Javascript // C++ code to calculate// characteristic polynomial of 3x3 matrix#include <bits/stdc++.h>using namespace std;#define N 3 // Traceint findTrace(int mat[N][N], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += mat[i][i]; return sum;} // Sum of minors along diagonalint sum_of_minors(int mat[N][N], int n){ return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1]));} // Function to get cofactor of mat[p][q]// in temp[][]. n is current dimension of mat[][]// Cofactor will be used for calculating determinantvoid getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } }} // Function for calculating// determinant of matrixint determinantOfMatrix(int mat[N][N], int n){ // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int temp[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D;} // Driver Codeint main(){ // Given matrix int mat[N][N] = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); cout << "x^3"; if (trace != 0) { trace < 0 ? cout << " + " << trace * -1 << "x^2" : cout << " - " << trace << "x^2"; } if (s_o_m != 0) { s_o_m < 0 ? cout << " - " << s_o_m * -1 << "x" : cout << " + " << s_o_m << "x"; } if (det != 0) { det < 0 ? cout << " + " << det * -1 : cout << " - " << det; } return 0;} // Java code to calculate// characteristic polynomial of 3x3 matriximport java.util.*; class GFG{ static final int N =3; // Trace static int findTrace(int mat[][], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i][i]; return sum; } // Sum of minors along diagonal static int sum_of_minors(int mat[][], int n) { return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant static void getCofactor(int mat[][], int temp[][], int p, int q, int n) { int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix static int determinantOfMatrix(int mat[][], int n) { // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int [][]temp = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code public static void main(String[] args) { // Given matrix int [][]mat = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); System.out.print("x^3"); if (trace != 0) { if(trace < 0) System.out.print(" + " + trace * -1+ "x^2"); else System.out.print(" - " + trace+ "x^2"); } if (s_o_m != 0) { if(s_o_m < 0 ) System.out.print(" - " + s_o_m * -1+ "x"); else System.out.print(" + " + s_o_m+ "x"); } if (det != 0) { if(det < 0 ) System.out.print(" + " + det * -1); else System.out.print(" - " + det); } }} // This code is contributed by Rajput-Ji # JavaScript code for the above approachN = 3 # Tracedef findTrace(mat, n): sum = 0 for i in range(n): sum += mat[i][i] return sum # Sum of minors along diagonaldef sum_of_minors(mat, n): return ((mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])) # Function to get cofactor of mat[p][q]# in temp[][]. n is current dimension of mat[][]# Cofactor will be used for calculating determinantdef getCofactor(mat, temp, p, q, n): i,j = 0,0 # Looping for each element of the matrix for row in range(n): for col in range(n): # Copying into temporary matrix only those # element which are not in given row and # column if (row != p and col != q): temp[i][j] = mat[row][col] j += 1 # Row is filled, so increase row index # and reset col index if (j == n - 1): j = 0 i += 1 # Function for calculating# determinant of matrixdef determinantOfMatrix(mat, n): # Initialize result D = 0 # Base case : if matrix # contains single element if (n == 1): return mat[0][0] # To store cofactors temp = [[0 for i in range(n)] for j in range(n)] # To store sign multiplier sign = 1 # Iterate for each element of first row for f in range(n): # Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n) D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1) # Terms are to be added with alternate sign sign = -sign return D # Driver Code # Given matrixmat = [[0, 1, 2], [1, 0, -1], [2, -1, 0]]trace = findTrace(mat, 3)s_o_m = sum_of_minors(mat, 3)det = determinantOfMatrix(mat, 3) print("x^3",end="")if (trace != 0): print(f" {trace * -1}x^2",end="") if(trace < 0) else print(f" - {trace}x^2",end="") if (s_o_m != 0): print(f" - {s_o_m * -1}x",end="") if(s_o_m < 0) else print(f" + {s_o_m}x",end="") if (det != 0): print(f" + {det * -1}",end="") if (det < 0) else print(f" - {det}",end="") # This code is contributed by shinjanpatra // C# code to calculate// characteristic polynomial of 3x3 matrixusing System;class GFG { static int N = 3; // Trace static int findTrace(int[, ] mat, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i, i]; return sum; } // Sum of minors along diagonal static int sum_of_minors(int[, ] mat, int n) { return ( (mat[2, 2] * mat[1, 1] - mat[2, 1] * mat[1, 2]) + (mat[2, 2] * mat[0, 0] - mat[2, 0] * mat[0, 2]) + (mat[1, 1] * mat[0, 0] - mat[1, 0] * mat[0, 1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant static void getCofactor(int[, ] mat, int[, ] temp, int p, int q, int n) { int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i, j++] = mat[row, col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix static int determinantOfMatrix(int[, ] mat, int n) { // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0, 0]; // To store cofactors int[, ] temp = new int[N, N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0, f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code public static void Main() { // Given matrix int[, ] mat = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); Console.Write("x^3"); if (trace != 0) { if (trace < 0) Console.Write(" + " + trace * -1 + "x^2"); else Console.Write(" - " + trace + "x^2"); } if (s_o_m != 0) { if (s_o_m < 0) Console.Write(" - " + s_o_m * -1 + "x"); else Console.Write(" + " + s_o_m + "x"); } if (det != 0) { if (det < 0) Console.Write(" + " + det * -1); else Console.Write(" - " + det); } }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach let N = 3 // Trace function findTrace(mat, n) { let sum = 0; for (let i = 0; i < n; i++) sum += mat[i][i]; return sum; } // Sum of minors along diagonal function sum_of_minors(mat, n) { return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant function getCofactor(mat, temp, p, q, n) { let i = 0, j = 0; // Looping for each element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix function determinantOfMatrix(mat, n) { // Initialize result let D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors let temp = new Array(n) for (let i = 0; i < temp.length; i++) { temp[i] = new Array(n) } // To store sign multiplier let sign = 1; // Iterate for each element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code // Given matrix let mat = [[0, 1, 2], [1, 0, -1], [2, -1, 0]]; let trace = findTrace(mat, 3); let s_o_m = sum_of_minors(mat, 3); let det = determinantOfMatrix(mat, 3); document.write("x^3"); if (trace != 0) { trace < 0 ? document.write(" + " + trace * -1 + "x^2") : document.write(" - " + trace + "x^2"); } if (s_o_m != 0) { s_o_m < 0 ? document.write(" - " + s_o_m * -1 + "x") : document.write(" + " + s_o_m + "x"); } if (det != 0) { det < 0 ? document.write(" + " + det * -1) : document.write(" - " + det); } // This code is contributed by Potta Lokesh </script> x^3 - 6x + 4 Time complexity: O(N3), where N is the size of a square matrixAuxiliary Space: O(N) lokeshpotta20 simmytarika5 ukasp Rajput-Ji shinjanpatra Algo-Geek 2021 Algo Geek C++ Matrix Matrix CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Divide given number into two even parts Smallest set of vertices to visit all nodes of the given Graph Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 27535, "s": 27507, "text": "\n04 Apr, 2022" }, { "code": null, "e": 27771, "s": 27535, "text": "In linear algebra, the characteristic polynomial of a square matrix is a polynomial that is invariant under matrix similarity and has the eigenvalues as roots. It has the determinant and the trace of the matrix among its coefficients. " }, { "code": null, "e": 27856, "s": 27771, "text": "The characteristic polynomial of the 3×3 matrix can be calculated using the formula " }, { "code": null, "e": 27945, "s": 27856, "text": "x3 – (Trace of matrix)*x2 + (Sum of minors along diagonal)*x – determinant of matrix = 0" }, { "code": null, "e": 27954, "s": 27945, "text": "Example:" }, { "code": null, "e": 28035, "s": 27954, "text": "Input: mat[][] = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }Output: x^3 – 6x + 4" }, { "code": null, "e": 28115, "s": 28035, "text": "Approach: Lets break up the formula and find the value of each term one by one:" }, { "code": null, "e": 28136, "s": 28115, "text": "Trace of the matrix " }, { "code": null, "e": 28196, "s": 28138, "text": "Trace of a Matrix the sum of elements along its diagonal." }, { "code": null, "e": 28214, "s": 28198, "text": "Trace of Matrix" }, { "code": null, "e": 28235, "s": 28214, "text": "Minor of the matrix " }, { "code": null, "e": 28590, "s": 28235, "text": "The minor of the matrix is for each element of the matrix and is equal to the part of the matrix remaining after excluding the row and the column containing that particular element. The new matrix formed with the minors of each element of the given matrix is called the minor of the matrix.Each new element of the minor matrix can be achieved as follows:" }, { "code": null, "e": 28881, "s": 28590, "text": "The minor of the matrix is for each element of the matrix and is equal to the part of the matrix remaining after excluding the row and the column containing that particular element. The new matrix formed with the minors of each element of the given matrix is called the minor of the matrix." }, { "code": null, "e": 28946, "s": 28881, "text": "Each new element of the minor matrix can be achieved as follows:" }, { "code": null, "e": 28971, "s": 28946, "text": "Determinant of a matrix " }, { "code": null, "e": 29356, "s": 28971, "text": "Determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). The determinant is used at many places in calculus and another matrix-related algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of linear equations and finding the inverse of a matrix." }, { "code": null, "e": 29741, "s": 29356, "text": "Determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). The determinant is used at many places in calculus and another matrix-related algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of linear equations and finding the inverse of a matrix." }, { "code": null, "e": 29802, "s": 29741, "text": "Program to find Characteristic Polynomial of a Square Matrix" }, { "code": null, "e": 29806, "s": 29802, "text": "C++" }, { "code": null, "e": 29811, "s": 29806, "text": "Java" }, { "code": null, "e": 29819, "s": 29811, "text": "Python3" }, { "code": null, "e": 29822, "s": 29819, "text": "C#" }, { "code": null, "e": 29833, "s": 29822, "text": "Javascript" }, { "code": "// C++ code to calculate// characteristic polynomial of 3x3 matrix#include <bits/stdc++.h>using namespace std;#define N 3 // Traceint findTrace(int mat[N][N], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += mat[i][i]; return sum;} // Sum of minors along diagonalint sum_of_minors(int mat[N][N], int n){ return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1]));} // Function to get cofactor of mat[p][q]// in temp[][]. n is current dimension of mat[][]// Cofactor will be used for calculating determinantvoid getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } }} // Function for calculating// determinant of matrixint determinantOfMatrix(int mat[N][N], int n){ // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int temp[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D;} // Driver Codeint main(){ // Given matrix int mat[N][N] = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); cout << \"x^3\"; if (trace != 0) { trace < 0 ? cout << \" + \" << trace * -1 << \"x^2\" : cout << \" - \" << trace << \"x^2\"; } if (s_o_m != 0) { s_o_m < 0 ? cout << \" - \" << s_o_m * -1 << \"x\" : cout << \" + \" << s_o_m << \"x\"; } if (det != 0) { det < 0 ? cout << \" + \" << det * -1 : cout << \" - \" << det; } return 0;}", "e": 32451, "s": 29833, "text": null }, { "code": "// Java code to calculate// characteristic polynomial of 3x3 matriximport java.util.*; class GFG{ static final int N =3; // Trace static int findTrace(int mat[][], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i][i]; return sum; } // Sum of minors along diagonal static int sum_of_minors(int mat[][], int n) { return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant static void getCofactor(int mat[][], int temp[][], int p, int q, int n) { int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix static int determinantOfMatrix(int mat[][], int n) { // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors int [][]temp = new int[N][N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code public static void main(String[] args) { // Given matrix int [][]mat = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); System.out.print(\"x^3\"); if (trace != 0) { if(trace < 0) System.out.print(\" + \" + trace * -1+ \"x^2\"); else System.out.print(\" - \" + trace+ \"x^2\"); } if (s_o_m != 0) { if(s_o_m < 0 ) System.out.print(\" - \" + s_o_m * -1+ \"x\"); else System.out.print(\" + \" + s_o_m+ \"x\"); } if (det != 0) { if(det < 0 ) System.out.print(\" + \" + det * -1); else System.out.print(\" - \" + det); } }} // This code is contributed by Rajput-Ji", "e": 35198, "s": 32451, "text": null }, { "code": "# JavaScript code for the above approachN = 3 # Tracedef findTrace(mat, n): sum = 0 for i in range(n): sum += mat[i][i] return sum # Sum of minors along diagonaldef sum_of_minors(mat, n): return ((mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])) # Function to get cofactor of mat[p][q]# in temp[][]. n is current dimension of mat[][]# Cofactor will be used for calculating determinantdef getCofactor(mat, temp, p, q, n): i,j = 0,0 # Looping for each element of the matrix for row in range(n): for col in range(n): # Copying into temporary matrix only those # element which are not in given row and # column if (row != p and col != q): temp[i][j] = mat[row][col] j += 1 # Row is filled, so increase row index # and reset col index if (j == n - 1): j = 0 i += 1 # Function for calculating# determinant of matrixdef determinantOfMatrix(mat, n): # Initialize result D = 0 # Base case : if matrix # contains single element if (n == 1): return mat[0][0] # To store cofactors temp = [[0 for i in range(n)] for j in range(n)] # To store sign multiplier sign = 1 # Iterate for each element of first row for f in range(n): # Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n) D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1) # Terms are to be added with alternate sign sign = -sign return D # Driver Code # Given matrixmat = [[0, 1, 2], [1, 0, -1], [2, -1, 0]]trace = findTrace(mat, 3)s_o_m = sum_of_minors(mat, 3)det = determinantOfMatrix(mat, 3) print(\"x^3\",end=\"\")if (trace != 0): print(f\" {trace * -1}x^2\",end=\"\") if(trace < 0) else print(f\" - {trace}x^2\",end=\"\") if (s_o_m != 0): print(f\" - {s_o_m * -1}x\",end=\"\") if(s_o_m < 0) else print(f\" + {s_o_m}x\",end=\"\") if (det != 0): print(f\" + {det * -1}\",end=\"\") if (det < 0) else print(f\" - {det}\",end=\"\") # This code is contributed by shinjanpatra", "e": 37431, "s": 35198, "text": null }, { "code": "// C# code to calculate// characteristic polynomial of 3x3 matrixusing System;class GFG { static int N = 3; // Trace static int findTrace(int[, ] mat, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i, i]; return sum; } // Sum of minors along diagonal static int sum_of_minors(int[, ] mat, int n) { return ( (mat[2, 2] * mat[1, 1] - mat[2, 1] * mat[1, 2]) + (mat[2, 2] * mat[0, 0] - mat[2, 0] * mat[0, 2]) + (mat[1, 1] * mat[0, 0] - mat[1, 0] * mat[0, 1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant static void getCofactor(int[, ] mat, int[, ] temp, int p, int q, int n) { int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i, j++] = mat[row, col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix static int determinantOfMatrix(int[, ] mat, int n) { // Initialize result int D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0, 0]; // To store cofactors int[, ] temp = new int[N, N]; // To store sign multiplier int sign = 1; // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0, f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code public static void Main() { // Given matrix int[, ] mat = { { 0, 1, 2 }, { 1, 0, -1 }, { 2, -1, 0 } }; int trace = findTrace(mat, 3); int s_o_m = sum_of_minors(mat, 3); int det = determinantOfMatrix(mat, 3); Console.Write(\"x^3\"); if (trace != 0) { if (trace < 0) Console.Write(\" + \" + trace * -1 + \"x^2\"); else Console.Write(\" - \" + trace + \"x^2\"); } if (s_o_m != 0) { if (s_o_m < 0) Console.Write(\" - \" + s_o_m * -1 + \"x\"); else Console.Write(\" + \" + s_o_m + \"x\"); } if (det != 0) { if (det < 0) Console.Write(\" + \" + det * -1); else Console.Write(\" - \" + det); } }} // This code is contributed by ukasp.", "e": 40142, "s": 37431, "text": null }, { "code": "<script> // JavaScript code for the above approach let N = 3 // Trace function findTrace(mat, n) { let sum = 0; for (let i = 0; i < n; i++) sum += mat[i][i]; return sum; } // Sum of minors along diagonal function sum_of_minors(mat, n) { return ( (mat[2][2] * mat[1][1] - mat[2][1] * mat[1][2]) + (mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]) + (mat[1][1] * mat[0][0] - mat[1][0] * mat[0][1])); } // Function to get cofactor of mat[p][q] // in temp[][]. n is current dimension of mat[][] // Cofactor will be used for calculating determinant function getCofactor(mat, temp, p, q, n) { let i = 0, j = 0; // Looping for each element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix only those // element which are not in given row and // column if (row != p && col != q) { temp[i][j++] = mat[row][col]; // Row is filled, so increase row index // and reset col index if (j == n - 1) { j = 0; i++; } } } } } // Function for calculating // determinant of matrix function determinantOfMatrix(mat, n) { // Initialize result let D = 0; // Base case : if matrix // contains single element if (n == 1) return mat[0][0]; // To store cofactors let temp = new Array(n) for (let i = 0; i < temp.length; i++) { temp[i] = new Array(n) } // To store sign multiplier let sign = 1; // Iterate for each element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of mat[0][f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); // Terms are to be added with alternate sign sign = -sign; } return D; } // Driver Code // Given matrix let mat = [[0, 1, 2], [1, 0, -1], [2, -1, 0]]; let trace = findTrace(mat, 3); let s_o_m = sum_of_minors(mat, 3); let det = determinantOfMatrix(mat, 3); document.write(\"x^3\"); if (trace != 0) { trace < 0 ? document.write(\" + \" + trace * -1 + \"x^2\") : document.write(\" - \" + trace + \"x^2\"); } if (s_o_m != 0) { s_o_m < 0 ? document.write(\" - \" + s_o_m * -1 + \"x\") : document.write(\" + \" + s_o_m + \"x\"); } if (det != 0) { det < 0 ? document.write(\" + \" + det * -1) : document.write(\" - \" + det); } // This code is contributed by Potta Lokesh </script>", "e": 43209, "s": 40142, "text": null }, { "code": null, "e": 43225, "s": 43212, "text": "x^3 - 6x + 4" }, { "code": null, "e": 43310, "s": 43225, "text": "Time complexity: O(N3), where N is the size of a square matrixAuxiliary Space: O(N) " }, { "code": null, "e": 43326, "s": 43312, "text": "lokeshpotta20" }, { "code": null, "e": 43339, "s": 43326, "text": "simmytarika5" }, { "code": null, "e": 43345, "s": 43339, "text": "ukasp" }, { "code": null, "e": 43355, "s": 43345, "text": "Rajput-Ji" }, { "code": null, "e": 43368, "s": 43355, "text": "shinjanpatra" }, { "code": null, "e": 43383, "s": 43368, "text": "Algo-Geek 2021" }, { "code": null, "e": 43393, "s": 43383, "text": "Algo Geek" }, { "code": null, "e": 43397, "s": 43393, "text": "C++" }, { "code": null, "e": 43404, "s": 43397, "text": "Matrix" }, { "code": null, "e": 43411, "s": 43404, "text": "Matrix" }, { "code": null, "e": 43415, "s": 43411, "text": "CPP" }, { "code": null, "e": 43513, "s": 43415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43568, "s": 43513, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 43616, "s": 43568, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 43656, "s": 43616, "text": "Divide given number into two even parts" }, { "code": null, "e": 43719, "s": 43656, "text": "Smallest set of vertices to visit all nodes of the given Graph" }, { "code": null, "e": 43799, "s": 43719, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 43817, "s": 43799, "text": "Vector in C++ STL" }, { "code": null, "e": 43833, "s": 43817, "text": "Arrays in C/C++" }, { "code": null, "e": 43879, "s": 43833, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 43898, "s": 43879, "text": "Inheritance in C++" } ]
How to create Shopping Cart Button in ReactJS? - GeeksforGeeks
21 Mar, 2022 We can create a Shopping Cart-like button with the feature of adding items count and decreasing item count in ReactJS using the following approach. Material UI for React has this component available for us, and it is very easy to integrate. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/icons Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import ButtonGroup from "@material-ui/core/ButtonGroup";import Badge from "@material-ui/core/Badge";import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";import Button from "@material-ui/core/Button";import AddIcon from "@material-ui/icons/Add";import RemoveIcon from "@material-ui/icons/Remove"; export default function App() { const [itemCount, setItemCount] = React.useState(1); return ( <div style={{ display: "block", padding: 30 }}> <h4>How to create ShoppingCart Button in ReactJS?</h4> <div> <Badge color="secondary" badgeContent={itemCount}> <ShoppingCartIcon />{" "} </Badge> <ButtonGroup> <Button onClick={() => { setItemCount(Math.max(itemCount - 1, 0)); }} > {" "} <RemoveIcon fontSize="small" /> </Button> <Button onClick={() => { setItemCount(itemCount + 1); }} > {" "} <AddIcon fontSize="small" /> </Button> </ButtonGroup> </div> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/badges Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n21 Mar, 2022" }, { "code": null, "e": 26313, "s": 26071, "text": "We can create a Shopping Cart-like button with the feature of adding items count and decreasing item count in ReactJS using the following approach. Material UI for React has this component available for us, and it is very easy to integrate. " }, { "code": null, "e": 26363, "s": 26313, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26427, "s": 26363, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26459, "s": 26427, "text": "npx create-react-app foldername" }, { "code": null, "e": 26559, "s": 26459, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26573, "s": 26559, "text": "cd foldername" }, { "code": null, "e": 26682, "s": 26573, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 26743, "s": 26682, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 26795, "s": 26743, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26813, "s": 26795, "text": "Project Structure" }, { "code": null, "e": 26943, "s": 26813, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26950, "s": 26943, "text": "App.js" }, { "code": "import React from \"react\";import ButtonGroup from \"@material-ui/core/ButtonGroup\";import Badge from \"@material-ui/core/Badge\";import ShoppingCartIcon from \"@material-ui/icons/ShoppingCart\";import Button from \"@material-ui/core/Button\";import AddIcon from \"@material-ui/icons/Add\";import RemoveIcon from \"@material-ui/icons/Remove\"; export default function App() { const [itemCount, setItemCount] = React.useState(1); return ( <div style={{ display: \"block\", padding: 30 }}> <h4>How to create ShoppingCart Button in ReactJS?</h4> <div> <Badge color=\"secondary\" badgeContent={itemCount}> <ShoppingCartIcon />{\" \"} </Badge> <ButtonGroup> <Button onClick={() => { setItemCount(Math.max(itemCount - 1, 0)); }} > {\" \"} <RemoveIcon fontSize=\"small\" /> </Button> <Button onClick={() => { setItemCount(itemCount + 1); }} > {\" \"} <AddIcon fontSize=\"small\" /> </Button> </ButtonGroup> </div> </div> );}", "e": 28074, "s": 26950, "text": null }, { "code": null, "e": 28187, "s": 28074, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 28197, "s": 28187, "text": "npm start" }, { "code": null, "e": 28296, "s": 28197, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 28349, "s": 28296, "text": "Reference: https://material-ui.com/components/badges" }, { "code": null, "e": 28361, "s": 28349, "text": "Material-UI" }, { "code": null, "e": 28377, "s": 28361, "text": "React-Questions" }, { "code": null, "e": 28385, "s": 28377, "text": "ReactJS" }, { "code": null, "e": 28402, "s": 28385, "text": "Web Technologies" }, { "code": null, "e": 28500, "s": 28402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28527, "s": 28500, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28569, "s": 28527, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28607, "s": 28569, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28642, "s": 28607, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28700, "s": 28642, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28740, "s": 28700, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28773, "s": 28740, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28818, "s": 28773, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28868, "s": 28818, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Kotlin Collections - GeeksforGeeks
29 Jan, 2022 Similar to Java Collections, Kotlin also introduced the concept of collections. A collection usually contains a number of objects of the same type and these objects in the collection are called elements or items. Kotlin Standard Library provides a rich set of tools for managing collections. In Kotlin collections are categories into two forms. Immutable CollectionMutable Collection Immutable Collection Mutable Collection It means that it supports only read-only functionalities and can not be modified its elements. Immutable Collections and their corresponding methods are: List – listOf() and listOf<T>() Set – setOf() Map – mapOf() List – It is an ordered collection in which we can access elements or items by using indices – integer numbers that define a position for each element. Elements can be repeated in a list any number of times. We can not perform add or remove operations in the immutable list. Kotlin program to demonstrate the immutable list: Kotlin // An example for immutable listfun main(args: Array<String>) { val immutableList = listOf("Mahipal","Nikhil","Rahul") // gives compile time error // immutableList.add = "Praveen" for(item in immutableList){ println(item) }} Output: Mahipal Nikhil Rahul Set – It is a collection of unordered elements also it does not support duplicate elements. It is a collection of unique elements. Generally, the order of set elements does not have a significant effect. We can not perform add or remove operations because it is an immutable Set. Kotlin program to demonstrate the immutable set: Kotlin fun main(args: Array<String>) { // initialize with duplicate values // but output with no repetition var immutableSet = setOf(6,9,9,0,0,"Mahipal","Nikhil") // gives compile time error // immutableSet.add(7) for(item in immutableSet){ println(item) }} Output: 6 9 0 Mahipal Nikhil Map – Map keys are unique and hold only one value for each key, it is a set of key-value pairs. Each key maps to exactly one value. The values can be duplicates but keys should be unique. Maps are used to store logical connections between two objects, for example, a student ID and their name. As it is immutable its size is fixed and its methods support read-only access. Kotlin program to demonstrate the immutable map: Java // An example for immutable mapfun main(args : Array<String>) { var immutableMap = mapOf(9 to "Mahipal",8 to "Nikhil",7 to "Rahul") // gives compile time error // immutableMap.put(9,"Praveen") for(key in immutableMap.keys){ println(immutableMap[key]) }} Output: Mahipal Nikhil Rahul It supports both read and write functionalities. Mutable collections and their corresponding methods are: List – mutableListOf(),arrayListOf() and ArrayList Set – mutableSetOf(), hashSetOf() Map – mutableMapOf(), hashMapOf() and HashMap List – Since mutable list supports read and write operation, declared elements in the list can either be removed or added. Kotlin program to demonstrate the mutable list: Kotlin fun main(args : Array<String>) { var mutableList = mutableListOf("Mahipal","Nikhil","Rahul") // we can modify the element mutableList[0] = "Praveen" // add one more element in the list mutableList.add("Abhi") for(item in mutableList){ println(item) }} Output: Praveen Nikhil Rahul Abhi Set – The mutable Set supports both read and write functionality. We can access add or remove elements from the collections easily and it will preserve the order of the elements. Kotlin program to demonstrate the mutable set: Kotlin fun main(args: Array<String>) { var mutableSet = mutableSetOf<Int>(6,10) // adding elements in set mutableSet.add(2) mutableSet.add(5) for(item in mutableSet){ println(item) }} Output: 6 10 2 5 Map – It is mutable so it supports functionalities like put, remove, clear, etc. Kotlin program to demonstrate the mutable map. Kotlin fun main(args : Array<String>) { var mutableMap = mutableMapOf<Int,String>(1 to "Mahipal",2 to "Nikhil",3 to "Rahul") // we can modify the element mutableMap.put(1,"Praveen") // add one more element in the list mutableMap.put(4,"Abhi") for(item in mutableMap.values){ println(item) }} Output: Praveen Nikhil Rahul Abhi mishrashashank501 saurabh1990aror Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Android Tutorial How to Change the Color of Status Bar in an Android App? Kotlin when expression Android Menus ImageView in Android with Example
[ { "code": null, "e": 25261, "s": 25233, "text": "\n29 Jan, 2022" }, { "code": null, "e": 25553, "s": 25261, "text": "Similar to Java Collections, Kotlin also introduced the concept of collections. A collection usually contains a number of objects of the same type and these objects in the collection are called elements or items. Kotlin Standard Library provides a rich set of tools for managing collections." }, { "code": null, "e": 25607, "s": 25553, "text": "In Kotlin collections are categories into two forms. " }, { "code": null, "e": 25646, "s": 25607, "text": "Immutable CollectionMutable Collection" }, { "code": null, "e": 25667, "s": 25646, "text": "Immutable Collection" }, { "code": null, "e": 25686, "s": 25667, "text": "Mutable Collection" }, { "code": null, "e": 25842, "s": 25686, "text": "It means that it supports only read-only functionalities and can not be modified its elements. Immutable Collections and their corresponding methods are: " }, { "code": null, "e": 25874, "s": 25842, "text": "List – listOf() and listOf<T>()" }, { "code": null, "e": 25888, "s": 25874, "text": "Set – setOf()" }, { "code": null, "e": 25902, "s": 25888, "text": "Map – mapOf()" }, { "code": null, "e": 26228, "s": 25902, "text": "List – It is an ordered collection in which we can access elements or items by using indices – integer numbers that define a position for each element. Elements can be repeated in a list any number of times. We can not perform add or remove operations in the immutable list. Kotlin program to demonstrate the immutable list: " }, { "code": null, "e": 26235, "s": 26228, "text": "Kotlin" }, { "code": "// An example for immutable listfun main(args: Array<String>) { val immutableList = listOf(\"Mahipal\",\"Nikhil\",\"Rahul\") // gives compile time error // immutableList.add = \"Praveen\" for(item in immutableList){ println(item) }}", "e": 26482, "s": 26235, "text": null }, { "code": null, "e": 26491, "s": 26482, "text": "Output: " }, { "code": null, "e": 26512, "s": 26491, "text": "Mahipal\nNikhil\nRahul" }, { "code": null, "e": 26842, "s": 26512, "text": "Set – It is a collection of unordered elements also it does not support duplicate elements. It is a collection of unique elements. Generally, the order of set elements does not have a significant effect. We can not perform add or remove operations because it is an immutable Set. Kotlin program to demonstrate the immutable set: " }, { "code": null, "e": 26849, "s": 26842, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { // initialize with duplicate values // but output with no repetition var immutableSet = setOf(6,9,9,0,0,\"Mahipal\",\"Nikhil\") // gives compile time error // immutableSet.add(7) for(item in immutableSet){ println(item) }}", "e": 27130, "s": 26849, "text": null }, { "code": null, "e": 27140, "s": 27130, "text": "Output: " }, { "code": null, "e": 27161, "s": 27140, "text": "6\n9\n0\nMahipal\nNikhil" }, { "code": null, "e": 27583, "s": 27161, "text": "Map – Map keys are unique and hold only one value for each key, it is a set of key-value pairs. Each key maps to exactly one value. The values can be duplicates but keys should be unique. Maps are used to store logical connections between two objects, for example, a student ID and their name. As it is immutable its size is fixed and its methods support read-only access. Kotlin program to demonstrate the immutable map:" }, { "code": null, "e": 27588, "s": 27583, "text": "Java" }, { "code": "// An example for immutable mapfun main(args : Array<String>) { var immutableMap = mapOf(9 to \"Mahipal\",8 to \"Nikhil\",7 to \"Rahul\") // gives compile time error // immutableMap.put(9,\"Praveen\") for(key in immutableMap.keys){ println(immutableMap[key]) }}", "e": 27864, "s": 27588, "text": null }, { "code": null, "e": 27873, "s": 27864, "text": "Output: " }, { "code": null, "e": 27894, "s": 27873, "text": "Mahipal\nNikhil\nRahul" }, { "code": null, "e": 28002, "s": 27894, "text": "It supports both read and write functionalities. Mutable collections and their corresponding methods are: " }, { "code": null, "e": 28053, "s": 28002, "text": "List – mutableListOf(),arrayListOf() and ArrayList" }, { "code": null, "e": 28087, "s": 28053, "text": "Set – mutableSetOf(), hashSetOf()" }, { "code": null, "e": 28133, "s": 28087, "text": "Map – mutableMapOf(), hashMapOf() and HashMap" }, { "code": null, "e": 28304, "s": 28133, "text": "List – Since mutable list supports read and write operation, declared elements in the list can either be removed or added. Kotlin program to demonstrate the mutable list:" }, { "code": null, "e": 28311, "s": 28304, "text": "Kotlin" }, { "code": "fun main(args : Array<String>) { var mutableList = mutableListOf(\"Mahipal\",\"Nikhil\",\"Rahul\") // we can modify the element mutableList[0] = \"Praveen\" // add one more element in the list mutableList.add(\"Abhi\") for(item in mutableList){ println(item) }}", "e": 28591, "s": 28311, "text": null }, { "code": null, "e": 28601, "s": 28591, "text": "Output: " }, { "code": null, "e": 28627, "s": 28601, "text": "Praveen\nNikhil\nRahul\nAbhi" }, { "code": null, "e": 28854, "s": 28627, "text": "Set – The mutable Set supports both read and write functionality. We can access add or remove elements from the collections easily and it will preserve the order of the elements. Kotlin program to demonstrate the mutable set: " }, { "code": null, "e": 28861, "s": 28854, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var mutableSet = mutableSetOf<Int>(6,10) // adding elements in set mutableSet.add(2) mutableSet.add(5) for(item in mutableSet){ println(item) }}", "e": 29063, "s": 28861, "text": null }, { "code": null, "e": 29072, "s": 29063, "text": "Output: " }, { "code": null, "e": 29081, "s": 29072, "text": "6\n10\n2\n5" }, { "code": null, "e": 29210, "s": 29081, "text": "Map – It is mutable so it supports functionalities like put, remove, clear, etc. Kotlin program to demonstrate the mutable map. " }, { "code": null, "e": 29217, "s": 29210, "text": "Kotlin" }, { "code": "fun main(args : Array<String>) { var mutableMap = mutableMapOf<Int,String>(1 to \"Mahipal\",2 to \"Nikhil\",3 to \"Rahul\") // we can modify the element mutableMap.put(1,\"Praveen\") // add one more element in the list mutableMap.put(4,\"Abhi\") for(item in mutableMap.values){ println(item) }}", "e": 29530, "s": 29217, "text": null }, { "code": null, "e": 29540, "s": 29530, "text": "Output: " }, { "code": null, "e": 29566, "s": 29540, "text": "Praveen\nNikhil\nRahul\nAbhi" }, { "code": null, "e": 29584, "s": 29566, "text": "mishrashashank501" }, { "code": null, "e": 29600, "s": 29584, "text": "saurabh1990aror" }, { "code": null, "e": 29607, "s": 29600, "text": "Picked" }, { "code": null, "e": 29614, "s": 29607, "text": "Kotlin" }, { "code": null, "e": 29712, "s": 29614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29755, "s": 29712, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29786, "s": 29755, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29828, "s": 29786, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29870, "s": 29828, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29910, "s": 29870, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29934, "s": 29910, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29991, "s": 29934, "text": "How to Change the Color of Status Bar in an Android App?" }, { "code": null, "e": 30014, "s": 29991, "text": "Kotlin when expression" }, { "code": null, "e": 30028, "s": 30014, "text": "Android Menus" } ]
jQuery UI Dialog focus Event - GeeksforGeeks
02 Dec, 2021 The Dialog box is the way to inform the user about something. It is a nice way to popup on the user window to show the information that will happen in the next or any kind of information the developer wants to clarify to the user should know. jQueryUI dialog method is used to create a basic dialog window inside the page. It has a title bar and a content area and can be moved, resized, and closed with the ‘X’ icon by default. The focus event is triggered when the dialog box gains focus. Syntax: $(".selector").dialog ( focused: function( event, ui ) { console.log('focused') }, CDN Link: First, add jQuery Mobile scripts needed for your project. <link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel =”stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script> Example 1: ‘Open Dialog’ button will trigger the click function (#gfg) that will further open the ‘textarea’ in a dialog (#gfg2). focus( event, ui ) : Triggers box gains focus. There is callback function attached to this focus.event : Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘focused’)} ui : Type -> Object callback function : function( event, ui ) { console.log(‘focused’)} HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"/> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script type="text/javascript"> $(function () { $("#gfg2").dialog({ autoOpen: false, focus: function (event, ui) { console.log("focused"); }, }); $("#gfg").click(function () { $("#gfg2").dialog("open"); }); }); </script> </head> <body> <div id="gfg2" title="GeeksforGeeks"> <textarea>jQuery UI | focus(event, ui) Event</textarea> </div> <button id="gfg">Open Dialog</button> </body></html> Output: Reference:https://api.jqueryui.com/1.9/dialog/#event-focus Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-UI HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26392, "s": 26364, "text": "\n02 Dec, 2021" }, { "code": null, "e": 26883, "s": 26392, "text": "The Dialog box is the way to inform the user about something. It is a nice way to popup on the user window to show the information that will happen in the next or any kind of information the developer wants to clarify to the user should know. jQueryUI dialog method is used to create a basic dialog window inside the page. It has a title bar and a content area and can be moved, resized, and closed with the ‘X’ icon by default. The focus event is triggered when the dialog box gains focus." }, { "code": null, "e": 26891, "s": 26883, "text": "Syntax:" }, { "code": null, "e": 26988, "s": 26891, "text": "$(\".selector\").dialog (\n focused: function( event, ui ) {\n console.log('focused')\n }, " }, { "code": null, "e": 27056, "s": 26988, "text": "CDN Link: First, add jQuery Mobile scripts needed for your project." }, { "code": null, "e": 27299, "s": 27056, "text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel =”stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>" }, { "code": null, "e": 27310, "s": 27299, "text": "Example 1:" }, { "code": null, "e": 27429, "s": 27310, "text": "‘Open Dialog’ button will trigger the click function (#gfg) that will further open the ‘textarea’ in a dialog (#gfg2)." }, { "code": null, "e": 27634, "s": 27429, "text": "focus( event, ui ) : Triggers box gains focus. There is callback function attached to this focus.event : Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘focused’)}" }, { "code": null, "e": 27654, "s": 27634, "text": "ui : Type -> Object" }, { "code": null, "e": 27722, "s": 27654, "text": "callback function : function( event, ui ) { console.log(‘focused’)}" }, { "code": null, "e": 27727, "s": 27722, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"/> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script type=\"text/javascript\"> $(function () { $(\"#gfg2\").dialog({ autoOpen: false, focus: function (event, ui) { console.log(\"focused\"); }, }); $(\"#gfg\").click(function () { $(\"#gfg2\").dialog(\"open\"); }); }); </script> </head> <body> <div id=\"gfg2\" title=\"GeeksforGeeks\"> <textarea>jQuery UI | focus(event, ui) Event</textarea> </div> <button id=\"gfg\">Open Dialog</button> </body></html>", "e": 28551, "s": 27727, "text": null }, { "code": null, "e": 28559, "s": 28551, "text": "Output:" }, { "code": null, "e": 28618, "s": 28559, "text": "Reference:https://api.jqueryui.com/1.9/dialog/#event-focus" }, { "code": null, "e": 28755, "s": 28618, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28765, "s": 28755, "text": "jQuery-UI" }, { "code": null, "e": 28770, "s": 28765, "text": "HTML" }, { "code": null, "e": 28777, "s": 28770, "text": "JQuery" }, { "code": null, "e": 28794, "s": 28777, "text": "Web Technologies" }, { "code": null, "e": 28799, "s": 28794, "text": "HTML" }, { "code": null, "e": 28897, "s": 28799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28921, "s": 28897, "text": "REST API (Introduction)" }, { "code": null, "e": 28962, "s": 28921, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28999, "s": 28962, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29028, "s": 28999, "text": "Form validation using jQuery" }, { "code": null, "e": 29048, "s": 29028, "text": "Angular File Upload" }, { "code": null, "e": 29094, "s": 29048, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29123, "s": 29094, "text": "Form validation using jQuery" }, { "code": null, "e": 29186, "s": 29123, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29263, "s": 29186, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? - GeeksforGeeks
29 Jan, 2019 There are different ways for client-side to interact with the server-side in real time, i.e., Long-Polling, Websockets, Server-Sent Events (SSE) and Comet. These are explained as following below. 1. Long Polling:It is a technology where the client requests information from the server without expecting an immediate response or basically involves making an HTTP request to a server and then holding the connection open to allow the server to respond later. Using long polling the server allows approximately 6 parallel connections from the browser. Load balancing in this is easy compared to other ways. Long polling is the oldest ways and hence is supported on all web browsers. Though due to the fewer updates in this it does not provide re-connection handling. Long polling is a lot more intensive or heavy on the server, but more widely accepted for browsers. 2. Websockets:WebSocket is a computer communication protocol that enables us full-duplex communication channels over a single transfer control protocol (TCP) connection. The WebSocket protocol enables interaction between a web browser and a web server with low weight overheads, providing real-time data transfer from and to the server. This is done by defining a standard way for the server to send information to the client without being first requested by the client, and then allowing messages to be passed to and fro while keeping the connection open. In this way, a two-way advancing conversation can take place between the client and the server without any issue. Websockets are majorly accepted in web browsers such as google chrome, opera, edge, firefox, safari etc. WebSockets is light on the browser and it provides up to 1024 parallel connections from the browser. It has a complicated load balancing and proxying technique. It also supports dropped client detection which was absent in long polling but it also does not provide re-connection handling. 3. Server-Sent Events (SSE):It is a technology enabling a browser such that it receives automatic updates from any server using an HTTP connection. This technology was proposed by the WHATWG (web hypertext application technology working group) and was first implemented by the opera web browser in the year 2006. It is a standard that describes how servers initialize data transmission with the client once an initial client connection is set up. They send message updates or continuous updates to a client to increase cross-browser streaming through a javascript API called EventSource. SSE is supported by a few browsers such as Mozilla, Chrome, and Safari. Internet Explorer and Edge still don’t support this technique. It also supports up to 6 parallel connections from the browser. It supports easy load balancing and also provides reconnection handling supported by EventSource. 4. Comet:It is a web application model in which a long-held HTTPS request allows the server to push data to a client-server i.e. a web browser without the web browser explicitly requesting any data update. Comet is known as many other names such as Ajax Push, Reverse Ajax etc. The basic idea behind developing Comet was to make a single and regular HTTPS request and depend on a never ending response from the server. The web server takes new incoming request and starts a new response with the current data, but the server will not end the response and hence the browser keeps the connection open and waiting for new data, whenever new data arrives the server will write that to the response stream. The server sends a unique string at the end of that particular update. Eg. “ThisCometMessageEnded”.Comet ends the limitations of the page by page web model and polling by offering two-way communication. Specific methods of implementing Comet fall into two major categories: streaming and long polling. I. Streaming –Any application that uses streaming Comet opens a single constant connection from the client browser to the server for all the Comet events. Techniques for streaming Comet are-(a) Hidden iframe (b) XMLHttpRequest (a) Hidden iframe (b) XMLHttpRequest II. Long Polling –Specific technologies for accomplishing long-polling include:(a) XMLHttpRequest long polling (b) Script tag long polling (a) XMLHttpRequest long polling (b) Script tag long polling Picked Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Routing Information Protocol (RIP) Congestion Control in Computer Networks Wireless Sensor Network (WSN) Architecture of Internet of Things (IoT)
[ { "code": null, "e": 25781, "s": 25753, "text": "\n29 Jan, 2019" }, { "code": null, "e": 25977, "s": 25781, "text": "There are different ways for client-side to interact with the server-side in real time, i.e., Long-Polling, Websockets, Server-Sent Events (SSE) and Comet. These are explained as following below." }, { "code": null, "e": 26330, "s": 25977, "text": "1. Long Polling:It is a technology where the client requests information from the server without expecting an immediate response or basically involves making an HTTP request to a server and then holding the connection open to allow the server to respond later. Using long polling the server allows approximately 6 parallel connections from the browser." }, { "code": null, "e": 26645, "s": 26330, "text": "Load balancing in this is easy compared to other ways. Long polling is the oldest ways and hence is supported on all web browsers. Though due to the fewer updates in this it does not provide re-connection handling. Long polling is a lot more intensive or heavy on the server, but more widely accepted for browsers." }, { "code": null, "e": 27316, "s": 26645, "text": "2. Websockets:WebSocket is a computer communication protocol that enables us full-duplex communication channels over a single transfer control protocol (TCP) connection. The WebSocket protocol enables interaction between a web browser and a web server with low weight overheads, providing real-time data transfer from and to the server. This is done by defining a standard way for the server to send information to the client without being first requested by the client, and then allowing messages to be passed to and fro while keeping the connection open. In this way, a two-way advancing conversation can take place between the client and the server without any issue." }, { "code": null, "e": 27710, "s": 27316, "text": "Websockets are majorly accepted in web browsers such as google chrome, opera, edge, firefox, safari etc. WebSockets is light on the browser and it provides up to 1024 parallel connections from the browser. It has a complicated load balancing and proxying technique. It also supports dropped client detection which was absent in long polling but it also does not provide re-connection handling." }, { "code": null, "e": 28298, "s": 27710, "text": "3. Server-Sent Events (SSE):It is a technology enabling a browser such that it receives automatic updates from any server using an HTTP connection. This technology was proposed by the WHATWG (web hypertext application technology working group) and was first implemented by the opera web browser in the year 2006. It is a standard that describes how servers initialize data transmission with the client once an initial client connection is set up. They send message updates or continuous updates to a client to increase cross-browser streaming through a javascript API called EventSource." }, { "code": null, "e": 28595, "s": 28298, "text": "SSE is supported by a few browsers such as Mozilla, Chrome, and Safari. Internet Explorer and Edge still don’t support this technique. It also supports up to 6 parallel connections from the browser. It supports easy load balancing and also provides reconnection handling supported by EventSource." }, { "code": null, "e": 29014, "s": 28595, "text": "4. Comet:It is a web application model in which a long-held HTTPS request allows the server to push data to a client-server i.e. a web browser without the web browser explicitly requesting any data update. Comet is known as many other names such as Ajax Push, Reverse Ajax etc. The basic idea behind developing Comet was to make a single and regular HTTPS request and depend on a never ending response from the server." }, { "code": null, "e": 29500, "s": 29014, "text": "The web server takes new incoming request and starts a new response with the current data, but the server will not end the response and hence the browser keeps the connection open and waiting for new data, whenever new data arrives the server will write that to the response stream. The server sends a unique string at the end of that particular update. Eg. “ThisCometMessageEnded”.Comet ends the limitations of the page by page web model and polling by offering two-way communication." }, { "code": null, "e": 29599, "s": 29500, "text": "Specific methods of implementing Comet fall into two major categories: streaming and long polling." }, { "code": null, "e": 29827, "s": 29599, "text": "I. Streaming –Any application that uses streaming Comet opens a single constant connection from the client browser to the server for all the Comet events. Techniques for streaming Comet are-(a) Hidden iframe\n(b) XMLHttpRequest " }, { "code": null, "e": 29865, "s": 29827, "text": "(a) Hidden iframe\n(b) XMLHttpRequest " }, { "code": null, "e": 30005, "s": 29865, "text": "II. Long Polling –Specific technologies for accomplishing long-polling include:(a) XMLHttpRequest long polling\n(b) Script tag long polling " }, { "code": null, "e": 30066, "s": 30005, "text": "(a) XMLHttpRequest long polling\n(b) Script tag long polling " }, { "code": null, "e": 30073, "s": 30066, "text": "Picked" }, { "code": null, "e": 30091, "s": 30073, "text": "Computer Networks" }, { "code": null, "e": 30109, "s": 30091, "text": "Computer Networks" }, { "code": null, "e": 30207, "s": 30109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30242, "s": 30207, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 30275, "s": 30242, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 30313, "s": 30275, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 30339, "s": 30313, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 30366, "s": 30339, "text": "Cryptography and its Types" }, { "code": null, "e": 30412, "s": 30366, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 30447, "s": 30412, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 30487, "s": 30447, "text": "Congestion Control in Computer Networks" }, { "code": null, "e": 30517, "s": 30487, "text": "Wireless Sensor Network (WSN)" } ]
Count of array elements which are greater than all elements on its left - GeeksforGeeks
21 Apr, 2021 Given an array arr[] of size N, the task is to count the number of array elements such that all the elements to its left are strictly smaller than it.Note: The first element of the array will be considered to be always satisfying the condition. Examples : Input: arr[] = { 2, 4, 5, 6 }Output: 4Explanation:Since the array is in increasing order, all the array elements satisfy the condition.Hence, the count of such elements is equal to the size of the array, i.e. equal to 4. Input: { 3, 3, 3, 3, 3, 3 }Output: 1Explanation: The first array element is the only element satisfying the condition. Approach:Follow the steps below to solve the problem: Set count = 1, as the first array element will be considered to be satisfying the condition. Set the first array element(i.e. arr[0]) as the maximum. Traverse the array starting from i =1, and compare every array element with the current maximum. If an array element is found to be greater than the current maximum, that element satisfies the condition as all the elements on its left are smaller than it. Hence, increase the count, and update the maximum. Finally, print the count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement the//above approach#include<bits/stdc++.h>using namespace std; // Function to return the count// of array elements with all// elements to its left smaller// than itint count_elements(int arr[], int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 6, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (count_elements(arr, n));} // This code is contributed by chitranayal // Java program to implement the//above approachimport java.util.*; class GFG{ // Function to return the count// of array elements with all// elements to its left smaller// than itstatic int count_elements(int arr[], int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codepublic static void main(String s[]){ int arr[] = { 2, 1, 4, 6, 3 }; int n = arr.length; System.out.print(count_elements(arr, n));}} // This code is contributed by rutvik_56 # Python3 Program to implement# the above approach # Function to return the count# of array elements with all# elements to its left smaller# than it def count_elements(arr): # Stores the count count = 1 # Stores the maximum max = arr[0] # Iterate over the array for i in range(1, len(arr)): # If an element greater # than maximum is obtained if arr[i] > max: # Increase count count += 1 # Update maximum max = arr[i] return count # Driver Codearr = [2, 1, 4, 6, 3]print(count_elements(arr)) // C# program to implement the// above approachusing System; class GFG{ // Function to return the count// of array elements with all// elements to its left smaller// than itstatic int count_elements(int[] arr, int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codepublic static void Main(){ int[] arr = { 2, 1, 4, 6, 3 }; int n = arr.Length; Console.Write(count_elements(arr, n));}} // This code is contributed by jrishabh99 <script> // Javascript program to implement the// above approach // Function to return the count// of array elements with all// elements to its left smaller// than itfunction count_elements(arr, n){ // Stores the count let count = 1; // Stores the maximum let max = arr[0]; // Iterate over the array for(let i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codelet arr = [ 2, 1, 4, 6, 3 ];let n = arr.length; document.write(count_elements(arr, n)); // This code is contributed by rishavmahato348 </script> 3 Time Complexity: O(N)Auxiliary Space: O(1) ukasp rutvik_56 jrishabh99 rishavmahato348 Arrays Greedy Mathematical Searching Arrays Searching Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26163, "s": 26135, "text": "\n21 Apr, 2021" }, { "code": null, "e": 26408, "s": 26163, "text": "Given an array arr[] of size N, the task is to count the number of array elements such that all the elements to its left are strictly smaller than it.Note: The first element of the array will be considered to be always satisfying the condition." }, { "code": null, "e": 26419, "s": 26408, "text": "Examples :" }, { "code": null, "e": 26640, "s": 26419, "text": "Input: arr[] = { 2, 4, 5, 6 }Output: 4Explanation:Since the array is in increasing order, all the array elements satisfy the condition.Hence, the count of such elements is equal to the size of the array, i.e. equal to 4." }, { "code": null, "e": 26759, "s": 26640, "text": "Input: { 3, 3, 3, 3, 3, 3 }Output: 1Explanation: The first array element is the only element satisfying the condition." }, { "code": null, "e": 26813, "s": 26759, "text": "Approach:Follow the steps below to solve the problem:" }, { "code": null, "e": 26906, "s": 26813, "text": "Set count = 1, as the first array element will be considered to be satisfying the condition." }, { "code": null, "e": 26963, "s": 26906, "text": "Set the first array element(i.e. arr[0]) as the maximum." }, { "code": null, "e": 27060, "s": 26963, "text": "Traverse the array starting from i =1, and compare every array element with the current maximum." }, { "code": null, "e": 27270, "s": 27060, "text": "If an array element is found to be greater than the current maximum, that element satisfies the condition as all the elements on its left are smaller than it. Hence, increase the count, and update the maximum." }, { "code": null, "e": 27296, "s": 27270, "text": "Finally, print the count." }, { "code": null, "e": 27347, "s": 27296, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27351, "s": 27347, "text": "C++" }, { "code": null, "e": 27356, "s": 27351, "text": "Java" }, { "code": null, "e": 27364, "s": 27356, "text": "Python3" }, { "code": null, "e": 27367, "s": 27364, "text": "C#" }, { "code": null, "e": 27378, "s": 27367, "text": "Javascript" }, { "code": "// C++ program to implement the//above approach#include<bits/stdc++.h>using namespace std; // Function to return the count// of array elements with all// elements to its left smaller// than itint count_elements(int arr[], int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 6, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (count_elements(arr, n));} // This code is contributed by chitranayal", "e": 28215, "s": 27378, "text": null }, { "code": "// Java program to implement the//above approachimport java.util.*; class GFG{ // Function to return the count// of array elements with all// elements to its left smaller// than itstatic int count_elements(int arr[], int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codepublic static void main(String s[]){ int arr[] = { 2, 1, 4, 6, 3 }; int n = arr.length; System.out.print(count_elements(arr, n));}} // This code is contributed by rutvik_56", "e": 29065, "s": 28215, "text": null }, { "code": "# Python3 Program to implement# the above approach # Function to return the count# of array elements with all# elements to its left smaller# than it def count_elements(arr): # Stores the count count = 1 # Stores the maximum max = arr[0] # Iterate over the array for i in range(1, len(arr)): # If an element greater # than maximum is obtained if arr[i] > max: # Increase count count += 1 # Update maximum max = arr[i] return count # Driver Codearr = [2, 1, 4, 6, 3]print(count_elements(arr))", "e": 29650, "s": 29065, "text": null }, { "code": "// C# program to implement the// above approachusing System; class GFG{ // Function to return the count// of array elements with all// elements to its left smaller// than itstatic int count_elements(int[] arr, int n){ // Stores the count int count = 1; // Stores the maximum int max = arr[0]; // Iterate over the array for(int i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codepublic static void Main(){ int[] arr = { 2, 1, 4, 6, 3 }; int n = arr.Length; Console.Write(count_elements(arr, n));}} // This code is contributed by jrishabh99", "e": 30473, "s": 29650, "text": null }, { "code": "<script> // Javascript program to implement the// above approach // Function to return the count// of array elements with all// elements to its left smaller// than itfunction count_elements(arr, n){ // Stores the count let count = 1; // Stores the maximum let max = arr[0]; // Iterate over the array for(let i = 1; i < n; i++) { // If an element greater // than maximum is obtained if (arr[i] > max) { // Increase count count += 1; // Update maximum max = arr[i]; } } return count;} // Driver Codelet arr = [ 2, 1, 4, 6, 3 ];let n = arr.length; document.write(count_elements(arr, n)); // This code is contributed by rishavmahato348 </script>", "e": 31251, "s": 30473, "text": null }, { "code": null, "e": 31253, "s": 31251, "text": "3" }, { "code": null, "e": 31299, "s": 31253, "text": " Time Complexity: O(N)Auxiliary Space: O(1) " }, { "code": null, "e": 31305, "s": 31299, "text": "ukasp" }, { "code": null, "e": 31315, "s": 31305, "text": "rutvik_56" }, { "code": null, "e": 31326, "s": 31315, "text": "jrishabh99" }, { "code": null, "e": 31342, "s": 31326, "text": "rishavmahato348" }, { "code": null, "e": 31349, "s": 31342, "text": "Arrays" }, { "code": null, "e": 31356, "s": 31349, "text": "Greedy" }, { "code": null, "e": 31369, "s": 31356, "text": "Mathematical" }, { "code": null, "e": 31379, "s": 31369, "text": "Searching" }, { "code": null, "e": 31386, "s": 31379, "text": "Arrays" }, { "code": null, "e": 31396, "s": 31386, "text": "Searching" }, { "code": null, "e": 31403, "s": 31396, "text": "Greedy" }, { "code": null, "e": 31416, "s": 31403, "text": "Mathematical" }, { "code": null, "e": 31514, "s": 31416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31582, "s": 31514, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31626, "s": 31582, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31674, "s": 31626, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31697, "s": 31674, "text": "Introduction to Arrays" }, { "code": null, "e": 31729, "s": 31697, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31780, "s": 31729, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 31838, "s": 31780, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 31889, "s": 31838, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 31949, "s": 31889, "text": "Write a program to print all permutations of a given string" } ]
Difference between WCF and Web Service - GeeksforGeeks
03 Jun, 2021 WCF (Windows Communication Foundation): WCF, as the name suggests, is a unified .NET framework that is used to develop service-oriented applications. It allows you to develop applications that can communicate using different communication mechanisms. It is founded for other Microsoft Distributed Technologies and considered the future of distributed computing. Because of its flexibility, it makes the development of endpoints much easier. It supports various programming languages and platforms. It is SOAP-based and returns data in XML form. It can be hosted in different scenarios, and such scenarios include various services such as WAS, IIS, Managed Windows, etc. The following code will be used to build a service in WCF: [ServiceContract] public interface ITest { [OperationContract] string ShowMessage(string strMsg); } public class Service: ITest { public string ShowMessage(string strMsg) Web Service: Web Service, as the name suggests, is a client-server application that allows communication between client and server applications. It is basically a software module specially designed to execute a certain set of tasks. This service is specially used to make application platforms and technology independent. There are two types of web services include the SOAP web services and RESTful web services. Following code will be used to build a service in Web service: [WebService] public class Service: System.Web.Services.WebService { [WebMethod] public string Test(string strMsg) { return strMsg; } } WCF Web Service Difference Between Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26105, "s": 26077, "text": "\n03 Jun, 2021" }, { "code": null, "e": 26837, "s": 26105, "text": "WCF (Windows Communication Foundation): WCF, as the name suggests, is a unified .NET framework that is used to develop service-oriented applications. It allows you to develop applications that can communicate using different communication mechanisms. It is founded for other Microsoft Distributed Technologies and considered the future of distributed computing. Because of its flexibility, it makes the development of endpoints much easier. It supports various programming languages and platforms. It is SOAP-based and returns data in XML form. It can be hosted in different scenarios, and such scenarios include various services such as WAS, IIS, Managed Windows, etc. The following code will be used to build a service in WCF: " }, { "code": null, "e": 27037, "s": 26837, "text": "[ServiceContract] \npublic interface ITest \n{ \n [OperationContract] \n string ShowMessage(string strMsg); \n} \npublic class Service: ITest \n{ \n public string ShowMessage(string strMsg) " }, { "code": null, "e": 27516, "s": 27037, "text": "Web Service: Web Service, as the name suggests, is a client-server application that allows communication between client and server applications. It is basically a software module specially designed to execute a certain set of tasks. This service is specially used to make application platforms and technology independent. There are two types of web services include the SOAP web services and RESTful web services. Following code will be used to build a service in Web service: " }, { "code": null, "e": 27681, "s": 27516, "text": "[WebService] \npublic class Service: System.Web.Services.WebService \n{ \n [WebMethod] \n public string Test(string strMsg) \n { return strMsg; \n } \n} " }, { "code": null, "e": 27687, "s": 27681, "text": "WCF " }, { "code": null, "e": 27700, "s": 27687, "text": "Web Service " }, { "code": null, "e": 27719, "s": 27700, "text": "Difference Between" }, { "code": null, "e": 27736, "s": 27719, "text": "Web Technologies" }, { "code": null, "e": 27834, "s": 27736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27895, "s": 27834, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27963, "s": 27895, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28021, "s": 27963, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28076, "s": 28021, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28142, "s": 28076, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 28182, "s": 28142, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28215, "s": 28182, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28260, "s": 28215, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28303, "s": 28260, "text": "How to fetch data from an API in ReactJS ?" } ]
Geometric Median - GeeksforGeeks
13 May, 2021 In normal median, we find a point that has minimum sum of distances. Similar concept applies in 2-D space. Given N points in 2-D space, the task is to find out a single point (x, y) from which the sum of distances to the input points are minimized (also known as the centre of minimum distance).Examples: Input: (1, 1), (3, 3) Output: Geometric Median = (2, 2) with minimum distance = 2.82843Input: (0, 0), (0, 0), (0, 12) Output: Geometric Median = (0, 0) with minimum distance = 12 Approach: At first thought, it seems that the problem asks us to find the Midpoint of the Geometric Centre point (in other words, centroid) of the given input points. Since it is the “centre” point of the input, sum of distances from the centre to all the given input points should automatically be minimized. This process is analogous to finding the Centre of Gravity of discrete Mass particles. The first example test case even gives the correct answer. But what happens when we apply the same logic to the second example?We can clearly see that the Geometric Centre, or the Centroid of is at . So according to the Euclidean Distance formula, the total distance to travel from Centroid to all 3 of the input points is But the optimal point should be , giving us a total distance of So, where are we wrong?Intuitively, you can think that Centroid of input points gives us the Arithmetic Mean of the input points. But what we require is the Central Tendency of the input points such that the cost to reach that central tendency (or in other words, the Euclidean Distance) is minimized. This is called the Geometric Median of a set of points.It is kind of like how conceptually, a Median is drastically different from Mean of given inputs.There isn’t any defined correct algorithm for finding the Geometric Median. What we do to approach this kind of problems is approximating a solution and determining whether our solution is indeed the Geometric Median or not.Algorithm There are two important variables : current_point – stores the x and y coordinates of the point which could be the Geometric Median. minimum_distance – stores the sum of Euclidean distances from current_point to all input points. After every approximation, if we find a new point from which the sum of distances is lower, then we update both the values of current point and minimum distance to the new point and new distance.First, we find the Centroid of the given points, take it as the current_point (or the median) and store the sum of distances in minimum distance. Then, we iterate over the given input points, by turn assuming each input point to be the median, and then calculating the distance to other points. If this distance is lower than the minimum_distance, then we update the old values of current_point and minimum_distance to the new values. Else, the old values remains the same.Then we enter a while loop. Inside that loop, we move a distance of test_distance (we assume a test_distance of 1000 for this example) from the current_point in all directions (left, up, right, down). Hence we get new points. Then we calculate the distance from these new points to the given input points. If this sum of distances is lower than the previous minimum_distance then we update the old values of current_point and minimum_distance to the new values and repeat the while loop. Else, we divide the test_distance by and then repeat the while loop.The terminating condition for the while loop is a certain value called the “lower_limit”. Lower the value, higher the accuracy of our approximation. Loop terminates when lower_limit exceeds the test_distance.Below is the implementation of the above approach: CPP // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store a point in 2-D spacestruct Point { double x, y;}; // Test points. These points are the left,// up, right and down relative neighbours// (arranged circularly) to the// current_point at a distance of// test_distance from current_pointPoint test_point[] = { { -1.0, 0.0 }, { 0.0, 1.0 }, { 1.0, 0.0 }, { 0.0, -1.0 } }; // Lowest Limit till which we are going// to run the main while loop// Lower the Limit higher the accuracydouble lower_limit = 0.01; // Function to return the sum of Euclidean// Distancesdouble distSum(Point p, Point arr[], int n){ double sum = 0; for (int i = 0; i < n; i++) { double distx = abs(arr[i].x - p.x); double disty = abs(arr[i].y - p.y); sum += sqrt((distx * distx) + (disty * disty)); } // Return the sum of Euclidean Distances return sum;} // Function to calculate the required// geometric medianvoid geometricMedian(Point arr[], int n){ // Current x coordinate and y coordinate Point current_point; for (int i = 0; i < n; i++) { current_point.x += arr[i].x; current_point.y += arr[i].y; } // Here current_point becomes the // Geographic MidPoint // Or Center of Gravity of equal // discrete mass distributions current_point.x /= n; current_point.y /= n; // minimum_distance becomes sum of // all distances from MidPoint to // all given points double minimum_distance = distSum(current_point, arr, n); int k = 0; while (k < n) { for (int i = 0; i < n, i != k; i++) { Point newpoint; newpoint.x = arr[i].x; newpoint.y = arr[i].y; double newd = distSum(newpoint, arr, n); if (newd < minimum_distance) { minimum_distance = newd; current_point.x = newpoint.x; current_point.y = newpoint.y; } } k++; } // Assume test_distance to be 1000 double test_distance = 1000; int flag = 0; // Test loop for approximation starts here while (test_distance > lower_limit) { flag = 0; // Loop for iterating over all 4 neighbours for (int i = 0; i < 4; i++) { // Finding Neighbours done Point newpoint; newpoint.x = current_point.x + (double)test_distance * test_point[i].x; newpoint.y = current_point.y + (double)test_distance * test_point[i].y; // New sum of Euclidean distances // from the neighbor to the given // data points double newd = distSum(newpoint, arr, n); if (newd < minimum_distance) { // Approximating and changing // current_point minimum_distance = newd; current_point.x = newpoint.x; current_point.y = newpoint.y; flag = 1; break; } } // This means none of the 4 neighbours // has the new minimum distance, hence // we divide by 2 and reiterate while // loop for better approximation if (flag == 0) test_distance /= 2; } cout << "Geometric Median = (" << current_point.x << ", " << current_point.y << ")"; cout << " with minimum distance = " << minimum_distance;} // Driver codeint main(){ int n = 2; Point arr[n]; arr[0].x = 1; arr[0].y = 1; arr[1].x = 3; arr[1].y = 3; geometricMedian(arr, n); return 0;} Geometric Median = (2, 2) with minimum distance = 2.82843 References: Geometric Median, Center of minimum distance ysachin2314 median-finding C++ Programs Competitive Programming Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Shallow Copy and Deep Copy in C++ delete keyword in C++ Passing a function as a parameter in C++ cin in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26485, "s": 26457, "text": "\n13 May, 2021" }, { "code": null, "e": 26792, "s": 26485, "text": "In normal median, we find a point that has minimum sum of distances. Similar concept applies in 2-D space. Given N points in 2-D space, the task is to find out a single point (x, y) from which the sum of distances to the input points are minimized (also known as the centre of minimum distance).Examples: " }, { "code": null, "e": 26973, "s": 26792, "text": "Input: (1, 1), (3, 3) Output: Geometric Median = (2, 2) with minimum distance = 2.82843Input: (0, 0), (0, 0), (0, 12) Output: Geometric Median = (0, 0) with minimum distance = 12 " }, { "code": null, "e": 28485, "s": 26975, "text": "Approach: At first thought, it seems that the problem asks us to find the Midpoint of the Geometric Centre point (in other words, centroid) of the given input points. Since it is the “centre” point of the input, sum of distances from the centre to all the given input points should automatically be minimized. This process is analogous to finding the Centre of Gravity of discrete Mass particles. The first example test case even gives the correct answer. But what happens when we apply the same logic to the second example?We can clearly see that the Geometric Centre, or the Centroid of is at . So according to the Euclidean Distance formula, the total distance to travel from Centroid to all 3 of the input points is But the optimal point should be , giving us a total distance of So, where are we wrong?Intuitively, you can think that Centroid of input points gives us the Arithmetic Mean of the input points. But what we require is the Central Tendency of the input points such that the cost to reach that central tendency (or in other words, the Euclidean Distance) is minimized. This is called the Geometric Median of a set of points.It is kind of like how conceptually, a Median is drastically different from Mean of given inputs.There isn’t any defined correct algorithm for finding the Geometric Median. What we do to approach this kind of problems is approximating a solution and determining whether our solution is indeed the Geometric Median or not.Algorithm There are two important variables : " }, { "code": null, "e": 28582, "s": 28485, "text": "current_point – stores the x and y coordinates of the point which could be the Geometric Median." }, { "code": null, "e": 28679, "s": 28582, "text": "minimum_distance – stores the sum of Euclidean distances from current_point to all input points." }, { "code": null, "e": 30163, "s": 28679, "text": "After every approximation, if we find a new point from which the sum of distances is lower, then we update both the values of current point and minimum distance to the new point and new distance.First, we find the Centroid of the given points, take it as the current_point (or the median) and store the sum of distances in minimum distance. Then, we iterate over the given input points, by turn assuming each input point to be the median, and then calculating the distance to other points. If this distance is lower than the minimum_distance, then we update the old values of current_point and minimum_distance to the new values. Else, the old values remains the same.Then we enter a while loop. Inside that loop, we move a distance of test_distance (we assume a test_distance of 1000 for this example) from the current_point in all directions (left, up, right, down). Hence we get new points. Then we calculate the distance from these new points to the given input points. If this sum of distances is lower than the previous minimum_distance then we update the old values of current_point and minimum_distance to the new values and repeat the while loop. Else, we divide the test_distance by and then repeat the while loop.The terminating condition for the while loop is a certain value called the “lower_limit”. Lower the value, higher the accuracy of our approximation. Loop terminates when lower_limit exceeds the test_distance.Below is the implementation of the above approach: " }, { "code": null, "e": 30167, "s": 30163, "text": "CPP" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store a point in 2-D spacestruct Point { double x, y;}; // Test points. These points are the left,// up, right and down relative neighbours// (arranged circularly) to the// current_point at a distance of// test_distance from current_pointPoint test_point[] = { { -1.0, 0.0 }, { 0.0, 1.0 }, { 1.0, 0.0 }, { 0.0, -1.0 } }; // Lowest Limit till which we are going// to run the main while loop// Lower the Limit higher the accuracydouble lower_limit = 0.01; // Function to return the sum of Euclidean// Distancesdouble distSum(Point p, Point arr[], int n){ double sum = 0; for (int i = 0; i < n; i++) { double distx = abs(arr[i].x - p.x); double disty = abs(arr[i].y - p.y); sum += sqrt((distx * distx) + (disty * disty)); } // Return the sum of Euclidean Distances return sum;} // Function to calculate the required// geometric medianvoid geometricMedian(Point arr[], int n){ // Current x coordinate and y coordinate Point current_point; for (int i = 0; i < n; i++) { current_point.x += arr[i].x; current_point.y += arr[i].y; } // Here current_point becomes the // Geographic MidPoint // Or Center of Gravity of equal // discrete mass distributions current_point.x /= n; current_point.y /= n; // minimum_distance becomes sum of // all distances from MidPoint to // all given points double minimum_distance = distSum(current_point, arr, n); int k = 0; while (k < n) { for (int i = 0; i < n, i != k; i++) { Point newpoint; newpoint.x = arr[i].x; newpoint.y = arr[i].y; double newd = distSum(newpoint, arr, n); if (newd < minimum_distance) { minimum_distance = newd; current_point.x = newpoint.x; current_point.y = newpoint.y; } } k++; } // Assume test_distance to be 1000 double test_distance = 1000; int flag = 0; // Test loop for approximation starts here while (test_distance > lower_limit) { flag = 0; // Loop for iterating over all 4 neighbours for (int i = 0; i < 4; i++) { // Finding Neighbours done Point newpoint; newpoint.x = current_point.x + (double)test_distance * test_point[i].x; newpoint.y = current_point.y + (double)test_distance * test_point[i].y; // New sum of Euclidean distances // from the neighbor to the given // data points double newd = distSum(newpoint, arr, n); if (newd < minimum_distance) { // Approximating and changing // current_point minimum_distance = newd; current_point.x = newpoint.x; current_point.y = newpoint.y; flag = 1; break; } } // This means none of the 4 neighbours // has the new minimum distance, hence // we divide by 2 and reiterate while // loop for better approximation if (flag == 0) test_distance /= 2; } cout << \"Geometric Median = (\" << current_point.x << \", \" << current_point.y << \")\"; cout << \" with minimum distance = \" << minimum_distance;} // Driver codeint main(){ int n = 2; Point arr[n]; arr[0].x = 1; arr[0].y = 1; arr[1].x = 3; arr[1].y = 3; geometricMedian(arr, n); return 0;}", "e": 33857, "s": 30167, "text": null }, { "code": null, "e": 33915, "s": 33857, "text": "Geometric Median = (2, 2) with minimum distance = 2.82843" }, { "code": null, "e": 33975, "s": 33917, "text": "References: Geometric Median, Center of minimum distance " }, { "code": null, "e": 33987, "s": 33975, "text": "ysachin2314" }, { "code": null, "e": 34002, "s": 33987, "text": "median-finding" }, { "code": null, "e": 34015, "s": 34002, "text": "C++ Programs" }, { "code": null, "e": 34039, "s": 34015, "text": "Competitive Programming" }, { "code": null, "e": 34049, "s": 34039, "text": "Geometric" }, { "code": null, "e": 34059, "s": 34049, "text": "Geometric" }, { "code": null, "e": 34157, "s": 34059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34183, "s": 34157, "text": "C++ Program for QuickSort" }, { "code": null, "e": 34217, "s": 34183, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 34239, "s": 34217, "text": "delete keyword in C++" }, { "code": null, "e": 34280, "s": 34239, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 34291, "s": 34280, "text": "cin in C++" }, { "code": null, "e": 34334, "s": 34291, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 34377, "s": 34334, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 34418, "s": 34377, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34496, "s": 34418, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Pure Functions
29 May, 2017 A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions are printf(), rand(), time(), etc. If a function is known as pure to compiler then Loop optimization and subexpression elimination can be applied to it. In GCC, we can mark functions as pure using the “pure” attribute. __attribute__ ((pure)) return-type fun-name(arguments1, ...) { /* function body */ } Following is an example pure function that returns square of a passed integer. __attribute__ _((pure)) int my_square(int val){ return val*val;} Consider the below example for (len = 0; len < strlen(str); ++len) printf("%c", toupper(str[len])); If “strlen()” function is not marked as pure function then compiler will invoke the “strlen()” function with each iteration of the loop, and if function is marked as pure function then compiler knows that value of “strlen()” function will be same for each call, that’s why compiler optimizes the for loop and generates code like following. int len = strlen(str); for (i = 0; i < len; ++i) printf("%c", toupper((str[i])); Let us write our own pure function to calculate string length. __attribute__ ((pure)) size_t my_strlen(const char *str){ const char *ptr = str; while (*ptr) ++ptr; return (ptr – str);} Marking function as pure says that the hypothetical function “my_strlen()” is safe to call fewer times than the program says. This article is compiled by “Narendra Kangralkar” and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Articles C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures SQL | DROP, TRUNCATE Difference Between Object And Class Implementation of LinkedList in Javascript std::sort() in C++ STL Bitwise Operators in C/C++ Arrays in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2017" }, { "code": null, "e": 439, "s": 54, "text": "A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions are printf(), rand(), time(), etc." }, { "code": null, "e": 623, "s": 439, "text": "If a function is known as pure to compiler then Loop optimization and subexpression elimination can be applied to it. In GCC, we can mark functions as pure using the “pure” attribute." }, { "code": null, "e": 713, "s": 623, "text": "__attribute__ ((pure)) return-type fun-name(arguments1, ...)\n{\n /* function body */\n}\n" }, { "code": null, "e": 792, "s": 713, "text": "Following is an example pure function that returns square of a passed integer." }, { "code": "__attribute__ _((pure)) int my_square(int val){ return val*val;}", "e": 860, "s": 792, "text": null }, { "code": null, "e": 887, "s": 860, "text": "Consider the below example" }, { "code": "for (len = 0; len < strlen(str); ++len) printf(\"%c\", toupper(str[len]));", "e": 963, "s": 887, "text": null }, { "code": null, "e": 1303, "s": 963, "text": "If “strlen()” function is not marked as pure function then compiler will invoke the “strlen()” function with each iteration of the loop, and if function is marked as pure function then compiler knows that value of “strlen()” function will be same for each call, that’s why compiler optimizes the for loop and generates code like following." }, { "code": "int len = strlen(str); for (i = 0; i < len; ++i) printf(\"%c\", toupper((str[i]));", "e": 1388, "s": 1303, "text": null }, { "code": null, "e": 1451, "s": 1388, "text": "Let us write our own pure function to calculate string length." }, { "code": "__attribute__ ((pure)) size_t my_strlen(const char *str){ const char *ptr = str; while (*ptr) ++ptr; return (ptr – str);}", "e": 1590, "s": 1451, "text": null }, { "code": null, "e": 1716, "s": 1590, "text": "Marking function as pure says that the hypothetical function “my_strlen()” is safe to call fewer times than the program says." }, { "code": null, "e": 1927, "s": 1716, "text": "This article is compiled by “Narendra Kangralkar” and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1936, "s": 1927, "text": "Articles" }, { "code": null, "e": 1947, "s": 1936, "text": "C Language" }, { "code": null, "e": 1951, "s": 1947, "text": "C++" }, { "code": null, "e": 1955, "s": 1951, "text": "CPP" }, { "code": null, "e": 2053, "s": 1955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2079, "s": 2053, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2126, "s": 2079, "text": "Time complexities of different data structures" }, { "code": null, "e": 2147, "s": 2126, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 2183, "s": 2147, "text": "Difference Between Object And Class" }, { "code": null, "e": 2226, "s": 2183, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 2249, "s": 2226, "text": "std::sort() in C++ STL" }, { "code": null, "e": 2276, "s": 2249, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 2292, "s": 2276, "text": "Arrays in C/C++" }, { "code": null, "e": 2309, "s": 2292, "text": "Substring in C++" } ]
Python MongoDB – Find
20 Jun, 2022 MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of data in an enterprise application. MongoDB also provides the feature of Auto-Scaling. It uses JSON-like documents, which makes the database very flexible and scalable. In MongoDB, there are 2 functions that are used to find the data from the collection or the database. find_one() find() In MongoDB, to select data from the collection we use find_one() method. It returns the first occurred information in the selection and brings backs as an output. find_one() method accepts an optional parameter filter that specifies the query to be performed and returns the first occurrence of information from the database. Example 1: Find the first document from the student’s a collection/database. Let’s suppose the database looks like as follows: Python3 # Python program to demonstrate# find_one() import pymongo mystudent = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = mystudent["gfg"] # Name of the collectionmycol = mydb["names"] x = mycol.find_one() print(x) Output : find() method is used to select data from the database. It returns all the occurrences of the information stored in the collection. It has 2 types of parameters, The first parameter of the find() method is a query object. In the below example we will use an empty Query object, which will select all information from the collection. Note: It works the same as SELECT* without any parameter. Example: Python3 import pymongo # establishing connection# to the databasemy_client = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = my_client["gfg"] # Name of the collectionmynew = mydb["names"] for x in mycol.find(): print(x) Output : The second parameter to the find() method is that you can specify the field to include in the result. The second parameter passed in the find() method is of object type describing the field. Thus, this parameter is optional. If omitted then all the fields from the collection/database will be displayed in the result. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will be excluded from the result. Example: Return only the names and address, not the id: Output: saurabh1990aror khushb99 Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 571, "s": 53, "text": "MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of data in an enterprise application. MongoDB also provides the feature of Auto-Scaling. It uses JSON-like documents, which makes the database very flexible and scalable." }, { "code": null, "e": 673, "s": 571, "text": "In MongoDB, there are 2 functions that are used to find the data from the collection or the database." }, { "code": null, "e": 684, "s": 673, "text": "find_one()" }, { "code": null, "e": 691, "s": 684, "text": "find()" }, { "code": null, "e": 1018, "s": 691, "text": "In MongoDB, to select data from the collection we use find_one() method. It returns the first occurred information in the selection and brings backs as an output. find_one() method accepts an optional parameter filter that specifies the query to be performed and returns the first occurrence of information from the database. " }, { "code": null, "e": 1145, "s": 1018, "text": "Example 1: Find the first document from the student’s a collection/database. Let’s suppose the database looks like as follows:" }, { "code": null, "e": 1155, "s": 1147, "text": "Python3" }, { "code": "# Python program to demonstrate# find_one() import pymongo mystudent = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = mystudent[\"gfg\"] # Name of the collectionmycol = mydb[\"names\"] x = mycol.find_one() print(x)", "e": 1390, "s": 1155, "text": null }, { "code": null, "e": 1400, "s": 1390, "text": "Output : " }, { "code": null, "e": 1792, "s": 1400, "text": "find() method is used to select data from the database. It returns all the occurrences of the information stored in the collection. It has 2 types of parameters, The first parameter of the find() method is a query object. In the below example we will use an empty Query object, which will select all information from the collection. Note: It works the same as SELECT* without any parameter. " }, { "code": null, "e": 1802, "s": 1792, "text": "Example: " }, { "code": null, "e": 1810, "s": 1802, "text": "Python3" }, { "code": "import pymongo # establishing connection# to the databasemy_client = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = my_client[\"gfg\"] # Name of the collectionmynew = mydb[\"names\"] for x in mycol.find(): print(x)", "e": 2047, "s": 1810, "text": null }, { "code": null, "e": 2518, "s": 2047, "text": "Output : The second parameter to the find() method is that you can specify the field to include in the result. The second parameter passed in the find() method is of object type describing the field. Thus, this parameter is optional. If omitted then all the fields from the collection/database will be displayed in the result. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will be excluded from the result. " }, { "code": null, "e": 2575, "s": 2518, "text": "Example: Return only the names and address, not the id: " }, { "code": null, "e": 2584, "s": 2575, "text": "Output: " }, { "code": null, "e": 2600, "s": 2584, "text": "saurabh1990aror" }, { "code": null, "e": 2609, "s": 2600, "text": "khushb99" }, { "code": null, "e": 2624, "s": 2609, "text": "Python-mongoDB" }, { "code": null, "e": 2631, "s": 2624, "text": "Python" } ]
Python | Get the first key in dictionary
18 May, 2020 Many times, while working with Python, we can have a situation in which we require to get the initial key of the dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kinds. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list() + keys() The combination of the above methods can be used to perform this particular task. In this, we just convert the entire dictionaries’ keys extracted by keys() into a list and just access the first key. Just one thing you have to keep in mind while using this i.e it’s complexity. It will first convert the whole dictionary to list by iterating over each item and then extract its first element. Using this method complexity would be O(n). # Python3 code to demonstrate working of# Getting first key in dictionary# Using keys() + list() # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using keys() + list()# Getting first key in dictionaryres = list(test_dict.keys())[0] # printing initial keyprint("The first key of dictionary is : " + str(res)) The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2} The first key of dictionary is : best Method #2 : Using next() + iter()This task can also be performed using these functions. In this, we just take the first next key using next() and iter function is used to get the iterable conversion of dictionary items. So if you want only the first key then this method is more efficient. Its complexity would be O(1). # Python3 code to demonstrate working of# Getting first key in dictionary# Using next() + iter() # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using next() + iter()# Getting first key in dictionaryres = next(iter(test_dict)) # printing initial keyprint("The first key of dictionary is : " + str(res)) The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2} The first key of dictionary is : best ApoorvaSingh1 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Convert a list to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2020" }, { "code": null, "e": 319, "s": 28, "text": "Many times, while working with Python, we can have a situation in which we require to get the initial key of the dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kinds. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 353, "s": 319, "text": "Method #1 : Using list() + keys()" }, { "code": null, "e": 790, "s": 353, "text": "The combination of the above methods can be used to perform this particular task. In this, we just convert the entire dictionaries’ keys extracted by keys() into a list and just access the first key. Just one thing you have to keep in mind while using this i.e it’s complexity. It will first convert the whole dictionary to list by iterating over each item and then extract its first element. Using this method complexity would be O(n)." }, { "code": "# Python3 code to demonstrate working of# Getting first key in dictionary# Using keys() + list() # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using keys() + list()# Getting first key in dictionaryres = list(test_dict.keys())[0] # printing initial keyprint(\"The first key of dictionary is : \" + str(res))", "e": 1212, "s": 790, "text": null }, { "code": null, "e": 1311, "s": 1212, "text": "The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}\nThe first key of dictionary is : best\n" }, { "code": null, "e": 1633, "s": 1313, "text": "Method #2 : Using next() + iter()This task can also be performed using these functions. In this, we just take the first next key using next() and iter function is used to get the iterable conversion of dictionary items. So if you want only the first key then this method is more efficient. Its complexity would be O(1)." }, { "code": "# Python3 code to demonstrate working of# Getting first key in dictionary# Using next() + iter() # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using next() + iter()# Getting first key in dictionaryres = next(iter(test_dict)) # printing initial keyprint(\"The first key of dictionary is : \" + str(res))", "e": 2051, "s": 1633, "text": null }, { "code": null, "e": 2150, "s": 2051, "text": "The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}\nThe first key of dictionary is : best\n" }, { "code": null, "e": 2164, "s": 2150, "text": "ApoorvaSingh1" }, { "code": null, "e": 2191, "s": 2164, "text": "Python dictionary-programs" }, { "code": null, "e": 2198, "s": 2191, "text": "Python" }, { "code": null, "e": 2214, "s": 2198, "text": "Python Programs" }, { "code": null, "e": 2312, "s": 2214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2330, "s": 2312, "text": "Python Dictionary" }, { "code": null, "e": 2352, "s": 2330, "text": "Enumerate() in Python" }, { "code": null, "e": 2394, "s": 2352, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2429, "s": 2394, "text": "Read a file line by line in Python" }, { "code": null, "e": 2461, "s": 2429, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2504, "s": 2461, "text": "Python program to convert a list to string" }, { "code": null, "e": 2526, "s": 2504, "text": "Defaultdict in Python" }, { "code": null, "e": 2564, "s": 2526, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2601, "s": 2564, "text": "Python Program for Fibonacci numbers" } ]
Matplotlib.ticker.FuncFormatter class in Python
07 Oct, 2021 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.ticker.FuncFormatter class uses a user defined function for formatting. This user defined function must take two values as inputs for a tick value x and a position pos. Syntax: class matplotlib.ticker.FuncFormatter(func)Parameter: func: The user defined function for formatting of the plot. Example 1: Python3 import matplotlib.pyplot as pltimport matplotlib.ticker as tickimport numpy as np x = np.linspace(0, 10, 1000)y = 0.000001 * np.sin(10 * x) fig = plt.figure()ax = fig.add_subplot(111) ax.plot(x, y) def y_fmt(x, y): return '{:2.2e}'.format(x).replace('e', 'x10^') ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt)) plt.show() Output: Example 2: Python3 import matplotlib.pyplot as pltfrom matplotlib.ticker import FuncFormatter fig, ax = plt.subplots()ax.axis([0.01, 10000, 1, 1000000])ax.loglog() for axis in [ax.xaxis, ax.yaxis]: formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y)) axis.set_major_formatter(formatter) plt.show() Output: gabaa406 Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 241, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. " }, { "code": null, "e": 427, "s": 241, "text": "The matplotlib.ticker.FuncFormatter class uses a user defined function for formatting. This user defined function must take two values as inputs for a tick value x and a position pos. " }, { "code": null, "e": 491, "s": 427, "text": "Syntax: class matplotlib.ticker.FuncFormatter(func)Parameter: " }, { "code": null, "e": 553, "s": 491, "text": "func: The user defined function for formatting of the plot. " }, { "code": null, "e": 566, "s": 553, "text": "Example 1: " }, { "code": null, "e": 574, "s": 566, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport matplotlib.ticker as tickimport numpy as np x = np.linspace(0, 10, 1000)y = 0.000001 * np.sin(10 * x) fig = plt.figure()ax = fig.add_subplot(111) ax.plot(x, y) def y_fmt(x, y): return '{:2.2e}'.format(x).replace('e', 'x10^') ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt)) plt.show()", "e": 908, "s": 574, "text": null }, { "code": null, "e": 918, "s": 908, "text": "Output: " }, { "code": null, "e": 931, "s": 918, "text": "Example 2: " }, { "code": null, "e": 939, "s": 931, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltfrom matplotlib.ticker import FuncFormatter fig, ax = plt.subplots()ax.axis([0.01, 10000, 1, 1000000])ax.loglog() for axis in [ax.xaxis, ax.yaxis]: formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y)) axis.set_major_formatter(formatter) plt.show()", "e": 1232, "s": 939, "text": null }, { "code": null, "e": 1242, "s": 1232, "text": "Output: " }, { "code": null, "e": 1253, "s": 1244, "text": "gabaa406" }, { "code": null, "e": 1271, "s": 1253, "text": "Python-matplotlib" }, { "code": null, "e": 1278, "s": 1271, "text": "Python" }, { "code": null, "e": 1294, "s": 1278, "text": "Write From Home" } ]
Find all possible binary trees with given Inorder Traversal
20 Jan, 2022 Given an array that represents Inorder Traversal, find all possible Binary Trees with the given Inorder traversal and print their preorder traversals.Examples: Input: in[] = {3, 2}; Output: Preorder traversals of different possible Binary Trees are: 3 2 2 3 Below are different possible binary trees 3 2 \ / 2 3 Input: in[] = {4, 5, 7}; Output: Preorder traversals of different possible Binary Trees are: 4 5 7 4 7 5 5 4 7 7 4 5 7 5 4 Below are different possible binary trees 4 4 5 7 7 \ \ / \ / / 5 7 4 7 4 5 \ / \ / 7 5 5 4 We strongly recommend you to minimize your browser and try this yourself first.Let given inorder traversal be in[]. In the given traversal, all nodes in left subtree of in[i] must appear before it and in right subtree must appear after it. So when we consider in[i] as root, all elements from in[0] to in[i-1] will be in left subtree and in[i+1] to n-1 will be in right subtree. If in[0] to in[i-1] can form x different trees and in[i+1] to in[n-1] can from y different trees then we will have x*y total trees when in[i] as root. So we simply iterate from 0 to n-1 for root. For every node in[i], recursively find different left and right subtrees. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here.The idea is to maintain a list of roots of all Binary Trees. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. 1) Initialize list of Binary Trees as empty. 2) For every element in[i] where i varies from 0 to n-1, do following ......a) Create a new node with key as 'arr[i]', let this node be 'node' ......b) Recursively construct list of all left subtrees. ......c) Recursively construct list of all right subtrees. 3) Iterate for all left subtrees a) For current leftsubtree, iterate for all right subtrees Add current left and right subtrees to 'node' and add 'node' to list. C++ Java Python3 C# Javascript // C++ program to find binary tree with given inorder// traversal#include <bits/stdc++.h>using namespace std; // Node structurestruct Node{ int key; struct Node *left, *right;}; // A utility function to create a new tree Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do preorder traversal of BSTvoid preorder(Node *root){ if (root != NULL) { printf("%d ", root->key); preorder(root->left); preorder(root->right); }} // Function for constructing all possible trees with// given inorder traversal stored in an array from// arr[start] to arr[end]. This function returns a// vector of trees.vector<Node *> getTrees(int arr[], int start, int end){ // List to store all possible trees vector<Node *> trees; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.push_back(NULL); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ vector<Node *> ltrees = getTrees(arr, start, i-1); /* Constructing right subtree */ vector<Node *> rtrees = getTrees(arr, i+1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.size(); j++) { for (int k = 0; k < rtrees.size(); k++) { // Making arr[i] as root Node * node = newNode(arr[i]); // Connecting left subtree node->left = ltrees[j]; // Connecting right subtree node->right = rtrees[k]; // Adding this tree to list trees.push_back(node); } } } return trees;} // Driver Program to test above functionsint main(){ int in[] = {4, 5, 7}; int n = sizeof(in) / sizeof(in[0]); vector<Node *> trees = getTrees(in, 0, n-1); cout << "Preorder traversals of different " << "possible Binary Trees are \n"; for (int i = 0; i < trees.size(); i++) { preorder(trees[i]); printf("\n"); } return 0;} // Java program to find binary tree with given inorder// traversalimport java.util.Vector; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class BinaryTree { Node root; // A utility function to do preorder traversal of BST void preOrder(Node node) { if (node != null) { System.out.print(node.data + " " ); preOrder(node.left); preOrder(node.right); } } // Function for constructing all possible trees with // given inorder traversal stored in an array from // arr[start] to arr[end]. This function returns a // vector of trees. Vector<Node> getTrees(int arr[], int start, int end) { // List to store all possible trees Vector<Node> trees= new Vector<Node>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.add(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ Vector<Node> ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ Vector<Node> rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.size(); j++) { for (int k = 0; k < rtrees.size(); k++) { // Making arr[i] as root Node node = new Node(arr[i]); // Connecting left subtree node.left = ltrees.get(j); // Connecting right subtree node.right = rtrees.get(k); // Adding this tree to list trees.add(node); } } } return trees; } public static void main(String args[]) { int in[] = {4, 5, 7}; int n = in.length; BinaryTree tree = new BinaryTree(); Vector<Node> trees = tree.getTrees(in, 0, n - 1); System.out.println("Preorder traversal of different "+ " binary trees are:"); for (int i = 0; i < trees.size(); i++) { tree.preOrder(trees.get(i)); System.out.println(""); } }} # Python program to find binary tree with given# inorder traversal # Node Structureclass Node: # Utility to create a new node def __init__(self , item): self.key = item self.left = None self.right = None # A utility function to do preorder traversal of BSTdef preorder(root): if root is not None: print (root.key,end=" ") preorder(root.left) preorder(root.right) # Function for constructing all possible trees with# given inorder traversal stored in an array from# arr[start] to arr[end]. This function returns a# vector of trees.def getTrees(arr , start , end): # List to store all possible trees trees = [] """ if start > end then subtree will be empty so returning NULL in the list """ if start > end : trees.append(None) return trees """ Iterating through all values from start to end for constructing left and right subtree recursively """ for i in range(start , end+1): # Constructing left subtree ltrees = getTrees(arr , start , i-1) # Constructing right subtree rtrees = getTrees(arr , i+1 , end) """ Looping through all left and right subtrees and connecting to ith root below""" for j in ltrees : for k in rtrees : # Making arr[i] as root node = Node(arr[i]) # Connecting left subtree node.left = j # Connecting right subtree node.right = k # Adding this tree to list trees.append(node) return trees # Driver program to test above functioninp = [4 , 5, 7]n = len(inp) trees = getTrees(inp , 0 , n-1) print ("Preorder traversals of different possible\ Binary Trees are ")for i in trees : preorder(i); print ("") # This program is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to find binary tree// with given inorder traversalusing System;using System.Collections.Generic; /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class GFG{public Node root; // A utility function to do// preorder traversal of BSTpublic virtual void preOrder(Node node){ if (node != null) { Console.Write(node.data + " "); preOrder(node.left); preOrder(node.right); }} // Function for constructing all possible// trees with given inorder traversal// stored in an array from arr[start] to// arr[end]. This function returns a// vector of trees.public virtual List<Node> getTrees(int[] arr, int start, int end){ // List to store all possible trees List<Node> trees = new List<Node>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.Add(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ List<Node> ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ List<Node> rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.Count; j++) { for (int k = 0; k < rtrees.Count; k++) { // Making arr[i] as root Node node = new Node(arr[i]); // Connecting left subtree node.left = ltrees[j]; // Connecting right subtree node.right = rtrees[k]; // Adding this tree to list trees.Add(node); } } } return trees;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {4, 5, 7}; int n = arr.Length; GFG tree = new GFG(); List<Node> trees = tree.getTrees(arr, 0, n - 1); Console.WriteLine("Preorder traversal of different " + " binary trees are:"); for (int i = 0; i < trees.Count; i++) { tree.preOrder(trees[i]); Console.WriteLine(""); }}} // This code is contributed by Shrikant13 <script> // Javascript program to find binary tree// with given inorder traversal /* Class containing left and right child of current node and key value*/class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} /* Class to print Level Order Traversal */ var root = null; // A utility function to do// preorder traversal of BSTfunction preOrder(node){ if (node != null) { document.write(node.data + " "); preOrder(node.left); preOrder(node.right); }} // Function for constructing all possible// trees with given inorder traversal// stored in an array from arr[start] to// arr[end]. This function returns a// vector of trees.function getTrees(arr, start, end){ // List to store all possible trees var trees = []; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.push(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (var i = start; i <= end; i++) { /* Constructing left subtree */ var ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ var rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (var j = 0; j < ltrees.length; j++) { for (var k = 0; k < rtrees.length; k++) { // Making arr[i] as root var node = new Node(arr[i]); // Connecting left subtree node.left = ltrees[j]; // Connecting right subtree node.right = rtrees[k]; // Adding this tree to list trees.push(node); } } } return trees;} // Driver Codevar arr = [4, 5, 7];var n = arr.length;var trees = getTrees(arr, 0, n - 1);document.write("Preorder traversal of different " + " binary trees are:<br>");for(var i = 0; i < trees.length; i++){ preOrder(trees[i]); document.write("<br>");} // This code is contributed by rrrtnx. </script> Output: Preorder traversals of different possible Binary Trees are 4 5 7 4 7 5 5 4 7 7 4 5 7 5 4 Thanks to Utkarsh for suggesting above solution.This problem is similar to the problem discussed here.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 rrrtnx amartyaghoshgfg catalan Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2022" }, { "code": null, "e": 214, "s": 52, "text": "Given an array that represents Inorder Traversal, find all possible Binary Trees with the given Inorder traversal and print their preorder traversals.Examples: " }, { "code": null, "e": 852, "s": 214, "text": "Input: in[] = {3, 2};\nOutput: Preorder traversals of different possible Binary Trees are:\n 3 2\n 2 3\nBelow are different possible binary trees\n 3 2\n \\ /\n 2 3\n\nInput: in[] = {4, 5, 7};\nOutput: Preorder traversals of different possible Binary Trees are:\n 4 5 7 \n 4 7 5 \n 5 4 7 \n 7 4 5 \n 7 5 4 \nBelow are different possible binary trees\n 4 4 5 7 7\n \\ \\ / \\ / /\n 5 7 4 7 4 5\n \\ / \\ /\n 7 5 5 4 " }, { "code": null, "e": 1895, "s": 852, "text": "We strongly recommend you to minimize your browser and try this yourself first.Let given inorder traversal be in[]. In the given traversal, all nodes in left subtree of in[i] must appear before it and in right subtree must appear after it. So when we consider in[i] as root, all elements from in[0] to in[i-1] will be in left subtree and in[i+1] to n-1 will be in right subtree. If in[0] to in[i-1] can form x different trees and in[i+1] to in[n-1] can from y different trees then we will have x*y total trees when in[i] as root. So we simply iterate from 0 to n-1 for root. For every node in[i], recursively find different left and right subtrees. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here.The idea is to maintain a list of roots of all Binary Trees. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. " }, { "code": null, "e": 2401, "s": 1895, "text": "1) Initialize list of Binary Trees as empty. \n2) For every element in[i] where i varies from 0 to n-1,\n do following\n......a) Create a new node with key as 'arr[i]', \n let this node be 'node'\n......b) Recursively construct list of all left subtrees.\n......c) Recursively construct list of all right subtrees.\n3) Iterate for all left subtrees\n a) For current leftsubtree, iterate for all right subtrees\n Add current left and right subtrees to 'node' and add\n 'node' to list." }, { "code": null, "e": 2407, "s": 2403, "text": "C++" }, { "code": null, "e": 2412, "s": 2407, "text": "Java" }, { "code": null, "e": 2420, "s": 2412, "text": "Python3" }, { "code": null, "e": 2423, "s": 2420, "text": "C#" }, { "code": null, "e": 2434, "s": 2423, "text": "Javascript" }, { "code": "// C++ program to find binary tree with given inorder// traversal#include <bits/stdc++.h>using namespace std; // Node structurestruct Node{ int key; struct Node *left, *right;}; // A utility function to create a new tree Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do preorder traversal of BSTvoid preorder(Node *root){ if (root != NULL) { printf(\"%d \", root->key); preorder(root->left); preorder(root->right); }} // Function for constructing all possible trees with// given inorder traversal stored in an array from// arr[start] to arr[end]. This function returns a// vector of trees.vector<Node *> getTrees(int arr[], int start, int end){ // List to store all possible trees vector<Node *> trees; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.push_back(NULL); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ vector<Node *> ltrees = getTrees(arr, start, i-1); /* Constructing right subtree */ vector<Node *> rtrees = getTrees(arr, i+1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.size(); j++) { for (int k = 0; k < rtrees.size(); k++) { // Making arr[i] as root Node * node = newNode(arr[i]); // Connecting left subtree node->left = ltrees[j]; // Connecting right subtree node->right = rtrees[k]; // Adding this tree to list trees.push_back(node); } } } return trees;} // Driver Program to test above functionsint main(){ int in[] = {4, 5, 7}; int n = sizeof(in) / sizeof(in[0]); vector<Node *> trees = getTrees(in, 0, n-1); cout << \"Preorder traversals of different \" << \"possible Binary Trees are \\n\"; for (int i = 0; i < trees.size(); i++) { preorder(trees[i]); printf(\"\\n\"); } return 0;}", "e": 4802, "s": 2434, "text": null }, { "code": "// Java program to find binary tree with given inorder// traversalimport java.util.Vector; /* Class containing left and right child of current node and key value*/class Node { int data; Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class BinaryTree { Node root; // A utility function to do preorder traversal of BST void preOrder(Node node) { if (node != null) { System.out.print(node.data + \" \" ); preOrder(node.left); preOrder(node.right); } } // Function for constructing all possible trees with // given inorder traversal stored in an array from // arr[start] to arr[end]. This function returns a // vector of trees. Vector<Node> getTrees(int arr[], int start, int end) { // List to store all possible trees Vector<Node> trees= new Vector<Node>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.add(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ Vector<Node> ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ Vector<Node> rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.size(); j++) { for (int k = 0; k < rtrees.size(); k++) { // Making arr[i] as root Node node = new Node(arr[i]); // Connecting left subtree node.left = ltrees.get(j); // Connecting right subtree node.right = rtrees.get(k); // Adding this tree to list trees.add(node); } } } return trees; } public static void main(String args[]) { int in[] = {4, 5, 7}; int n = in.length; BinaryTree tree = new BinaryTree(); Vector<Node> trees = tree.getTrees(in, 0, n - 1); System.out.println(\"Preorder traversal of different \"+ \" binary trees are:\"); for (int i = 0; i < trees.size(); i++) { tree.preOrder(trees.get(i)); System.out.println(\"\"); } }}", "e": 7447, "s": 4802, "text": null }, { "code": "# Python program to find binary tree with given# inorder traversal # Node Structureclass Node: # Utility to create a new node def __init__(self , item): self.key = item self.left = None self.right = None # A utility function to do preorder traversal of BSTdef preorder(root): if root is not None: print (root.key,end=\" \") preorder(root.left) preorder(root.right) # Function for constructing all possible trees with# given inorder traversal stored in an array from# arr[start] to arr[end]. This function returns a# vector of trees.def getTrees(arr , start , end): # List to store all possible trees trees = [] \"\"\" if start > end then subtree will be empty so returning NULL in the list \"\"\" if start > end : trees.append(None) return trees \"\"\" Iterating through all values from start to end for constructing left and right subtree recursively \"\"\" for i in range(start , end+1): # Constructing left subtree ltrees = getTrees(arr , start , i-1) # Constructing right subtree rtrees = getTrees(arr , i+1 , end) \"\"\" Looping through all left and right subtrees and connecting to ith root below\"\"\" for j in ltrees : for k in rtrees : # Making arr[i] as root node = Node(arr[i]) # Connecting left subtree node.left = j # Connecting right subtree node.right = k # Adding this tree to list trees.append(node) return trees # Driver program to test above functioninp = [4 , 5, 7]n = len(inp) trees = getTrees(inp , 0 , n-1) print (\"Preorder traversals of different possible\\ Binary Trees are \")for i in trees : preorder(i); print (\"\") # This program is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 9367, "s": 7447, "text": null }, { "code": "// C# program to find binary tree// with given inorder traversalusing System;using System.Collections.Generic; /* Class containing left and right child of current node and key value*/public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = null; right = null; }} /* Class to print Level Order Traversal */class GFG{public Node root; // A utility function to do// preorder traversal of BSTpublic virtual void preOrder(Node node){ if (node != null) { Console.Write(node.data + \" \"); preOrder(node.left); preOrder(node.right); }} // Function for constructing all possible// trees with given inorder traversal// stored in an array from arr[start] to// arr[end]. This function returns a// vector of trees.public virtual List<Node> getTrees(int[] arr, int start, int end){ // List to store all possible trees List<Node> trees = new List<Node>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.Add(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* Constructing left subtree */ List<Node> ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ List<Node> rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < ltrees.Count; j++) { for (int k = 0; k < rtrees.Count; k++) { // Making arr[i] as root Node node = new Node(arr[i]); // Connecting left subtree node.left = ltrees[j]; // Connecting right subtree node.right = rtrees[k]; // Adding this tree to list trees.Add(node); } } } return trees;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {4, 5, 7}; int n = arr.Length; GFG tree = new GFG(); List<Node> trees = tree.getTrees(arr, 0, n - 1); Console.WriteLine(\"Preorder traversal of different \" + \" binary trees are:\"); for (int i = 0; i < trees.Count; i++) { tree.preOrder(trees[i]); Console.WriteLine(\"\"); }}} // This code is contributed by Shrikant13", "e": 11973, "s": 9367, "text": null }, { "code": "<script> // Javascript program to find binary tree// with given inorder traversal /* Class containing left and right child of current node and key value*/class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} /* Class to print Level Order Traversal */ var root = null; // A utility function to do// preorder traversal of BSTfunction preOrder(node){ if (node != null) { document.write(node.data + \" \"); preOrder(node.left); preOrder(node.right); }} // Function for constructing all possible// trees with given inorder traversal// stored in an array from arr[start] to// arr[end]. This function returns a// vector of trees.function getTrees(arr, start, end){ // List to store all possible trees var trees = []; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { trees.push(null); return trees; } /* Iterating through all values from start to end for constructing left and right subtree recursively */ for (var i = start; i <= end; i++) { /* Constructing left subtree */ var ltrees = getTrees(arr, start, i - 1); /* Constructing right subtree */ var rtrees = getTrees(arr, i + 1, end); /* Now looping through all left and right subtrees and connecting them to ith root below */ for (var j = 0; j < ltrees.length; j++) { for (var k = 0; k < rtrees.length; k++) { // Making arr[i] as root var node = new Node(arr[i]); // Connecting left subtree node.left = ltrees[j]; // Connecting right subtree node.right = rtrees[k]; // Adding this tree to list trees.push(node); } } } return trees;} // Driver Codevar arr = [4, 5, 7];var n = arr.length;var trees = getTrees(arr, 0, n - 1);document.write(\"Preorder traversal of different \" + \" binary trees are:<br>\");for(var i = 0; i < trees.length; i++){ preOrder(trees[i]); document.write(\"<br>\");} // This code is contributed by rrrtnx. </script>", "e": 14224, "s": 11973, "text": null }, { "code": null, "e": 14234, "s": 14224, "text": "Output: " }, { "code": null, "e": 14328, "s": 14234, "text": "Preorder traversals of different possible Binary Trees are \n4 5 7 \n4 7 5 \n5 4 7 \n7 4 5 \n7 5 4" }, { "code": null, "e": 14555, "s": 14328, "text": "Thanks to Utkarsh for suggesting above solution.This problem is similar to the problem discussed here.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 14567, "s": 14555, "text": "shrikanth13" }, { "code": null, "e": 14574, "s": 14567, "text": "rrrtnx" }, { "code": null, "e": 14590, "s": 14574, "text": "amartyaghoshgfg" }, { "code": null, "e": 14598, "s": 14590, "text": "catalan" }, { "code": null, "e": 14603, "s": 14598, "text": "Tree" }, { "code": null, "e": 14608, "s": 14603, "text": "Tree" } ]
How to Make a Custom Exit Dialog in Android?
06 Apr, 2021 In this tutorial, we are going to create a Custom Exit Dialog in Android. By default, android doesn’t provide any exit dialog, but we can create it using the dialog class in java. But most of the developers and also the user doesn’t like the default dialog box and also we can’t do any modification in the dialog box according to our needs, so in this article, we will create a simple custom exit dialog. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Creating a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as the language though we are going to implement this project in Java language. Step 2: Before going to the coding section first do some pre-task Go to app -> res -> values -> colors.xml file and set the colors for the app. XML <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F9D58</color> <color name="colorAccent">#05af9b</color> </resources> We also create a new drawable file (card_round.xml) and also refer to elasq, flaticon for an alert icon, and paste it into the drawable folder. card_round.xml code is shown below XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="8dp" /> <padding android:bottom="8dp" android:left="8dp" android:right="8dp" android:top="8dp" /></shape> Step 3: Designing the UI The activity_main.xml contains a default text and we change the text to “Press back to exit ” as shown below XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Press back to exit" android:textSize="40dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Now we create a new layout resource file (custom_exit_dialog.xml) inside it we add an ImageView, TextView, and LinearLayout as shown below XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/bottom_sheet_exit_linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/card_round" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- exit the app textview --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="00dp" android:fontFamily="sans-serif-medium" android:gravity="center" android:text="Exit The App ?" android:textSize="20dp" android:textStyle="bold" /> <!-- Alert Icon ImageView --> <ImageView android:layout_width="match_parent" android:layout_height="80dp" android:layout_marginTop="16dp" android:src="@drawable/alert_icon" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="0dp" android:orientation="horizontal" android:weightSum="2"> <!-- No Text View --> <TextView android:id="@+id/textViewNo" android:layout_width="match_parent" android:layout_height="48dp" android:layout_gravity="center" android:layout_margin="8dp" android:layout_weight="1" android:background="@drawable/card_round" android:backgroundTint="#2196F3" android:elevation="8dp" android:gravity="center" android:text="NO" android:textColor="@color/white" /> <!-- Yes Text View --> <TextView android:id="@+id/textViewYes" android:layout_width="match_parent" android:layout_height="48dp" android:layout_gravity="center" android:layout_margin="8dp" android:layout_weight="1" android:background="@drawable/card_round" android:backgroundTint="#FD0001" android:elevation="8dp" android:gravity="center" android:text="Yes" android:textColor="@color/white" /> </LinearLayout> </LinearLayout> </LinearLayout> Step 4: Coding Part Now Open the MainActivity.java file there within the class, first of all, create the function public void customExitDialog() as shown below Java public void customExitDialog() { // creating custom dialog final Dialog dialog = new Dialog(MainActivity.this); // setting content view to dialog dialog.setContentView(R.layout.custom_exit_dialog); // getting reference of TextView TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes); TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo); // click listener for No dialogButtonNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog dialog.dismiss(); } }); // click listener for Yes dialogButtonYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog and exit the exit dialog.dismiss(); finish(); } }); // show the exit dialog dialog.show();} Now we call the customExitDialog() method inside the onBackPressed() as shown below Java @Overridepublic void onBackPressed() { // calling the function customExitDialog();} Below is the complete code for the MainActivity.java file. Java import android.app.Dialog;import android.os.Bundle;import android.view.View;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void customExitDialog() { // creating custom dialog final Dialog dialog = new Dialog(MainActivity.this); // setting content view to dialog dialog.setContentView(R.layout.custom_exit_dialog); // getting reference of TextView TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes); TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo); // click listener for No dialogButtonNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //dismiss the dialog dialog.dismiss(); } }); // click listener for Yes dialogButtonYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog // and exit the exit dialog.dismiss(); finish(); } }); // show the exit dialog dialog.show(); } @Override public void onBackPressed() { // calling the function customExitDialog(); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Apr, 2021" }, { "code": null, "e": 623, "s": 53, "text": "In this tutorial, we are going to create a Custom Exit Dialog in Android. By default, android doesn’t provide any exit dialog, but we can create it using the dialog class in java. But most of the developers and also the user doesn’t like the default dialog box and also we can’t do any modification in the dialog box according to our needs, so in this article, we will create a simple custom exit dialog. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 654, "s": 623, "text": "Step 1: Creating a New Project" }, { "code": null, "e": 867, "s": 654, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as the language though we are going to implement this project in Java language." }, { "code": null, "e": 933, "s": 867, "text": "Step 2: Before going to the coding section first do some pre-task" }, { "code": null, "e": 1011, "s": 933, "text": "Go to app -> res -> values -> colors.xml file and set the colors for the app." }, { "code": null, "e": 1015, "s": 1011, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#0F9D58</color> <color name=\"colorAccent\">#05af9b</color> </resources>", "e": 1222, "s": 1015, "text": null }, { "code": null, "e": 1402, "s": 1222, "text": "We also create a new drawable file (card_round.xml) and also refer to elasq, flaticon for an alert icon, and paste it into the drawable folder. card_round.xml code is shown below" }, { "code": null, "e": 1406, "s": 1402, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:shape=\"rectangle\"> <corners android:radius=\"8dp\" /> <padding android:bottom=\"8dp\" android:left=\"8dp\" android:right=\"8dp\" android:top=\"8dp\" /></shape>", "e": 1705, "s": 1406, "text": null }, { "code": null, "e": 1730, "s": 1705, "text": "Step 3: Designing the UI" }, { "code": null, "e": 1839, "s": 1730, "text": "The activity_main.xml contains a default text and we change the text to “Press back to exit ” as shown below" }, { "code": null, "e": 1843, "s": 1839, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Press back to exit\" android:textSize=\"40dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2652, "s": 1843, "text": null }, { "code": null, "e": 2791, "s": 2652, "text": "Now we create a new layout resource file (custom_exit_dialog.xml) inside it we add an ImageView, TextView, and LinearLayout as shown below" }, { "code": null, "e": 2795, "s": 2791, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/bottom_sheet_exit_linear\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@drawable/card_round\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!-- exit the app textview --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"00dp\" android:fontFamily=\"sans-serif-medium\" android:gravity=\"center\" android:text=\"Exit The App ?\" android:textSize=\"20dp\" android:textStyle=\"bold\" /> <!-- Alert Icon ImageView --> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"80dp\" android:layout_marginTop=\"16dp\" android:src=\"@drawable/alert_icon\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"0dp\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <!-- No Text View --> <TextView android:id=\"@+id/textViewNo\" android:layout_width=\"match_parent\" android:layout_height=\"48dp\" android:layout_gravity=\"center\" android:layout_margin=\"8dp\" android:layout_weight=\"1\" android:background=\"@drawable/card_round\" android:backgroundTint=\"#2196F3\" android:elevation=\"8dp\" android:gravity=\"center\" android:text=\"NO\" android:textColor=\"@color/white\" /> <!-- Yes Text View --> <TextView android:id=\"@+id/textViewYes\" android:layout_width=\"match_parent\" android:layout_height=\"48dp\" android:layout_gravity=\"center\" android:layout_margin=\"8dp\" android:layout_weight=\"1\" android:background=\"@drawable/card_round\" android:backgroundTint=\"#FD0001\" android:elevation=\"8dp\" android:gravity=\"center\" android:text=\"Yes\" android:textColor=\"@color/white\" /> </LinearLayout> </LinearLayout> </LinearLayout>", "e": 5470, "s": 2795, "text": null }, { "code": null, "e": 5490, "s": 5470, "text": "Step 4: Coding Part" }, { "code": null, "e": 5631, "s": 5490, "text": "Now Open the MainActivity.java file there within the class, first of all, create the function public void customExitDialog() as shown below" }, { "code": null, "e": 5636, "s": 5631, "text": "Java" }, { "code": "public void customExitDialog() { // creating custom dialog final Dialog dialog = new Dialog(MainActivity.this); // setting content view to dialog dialog.setContentView(R.layout.custom_exit_dialog); // getting reference of TextView TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes); TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo); // click listener for No dialogButtonNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog dialog.dismiss(); } }); // click listener for Yes dialogButtonYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog and exit the exit dialog.dismiss(); finish(); } }); // show the exit dialog dialog.show();}", "e": 6699, "s": 5636, "text": null }, { "code": null, "e": 6783, "s": 6699, "text": "Now we call the customExitDialog() method inside the onBackPressed() as shown below" }, { "code": null, "e": 6788, "s": 6783, "text": "Java" }, { "code": "@Overridepublic void onBackPressed() { // calling the function customExitDialog();}", "e": 6886, "s": 6788, "text": null }, { "code": null, "e": 6945, "s": 6886, "text": "Below is the complete code for the MainActivity.java file." }, { "code": null, "e": 6950, "s": 6945, "text": "Java" }, { "code": "import android.app.Dialog;import android.os.Bundle;import android.view.View;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void customExitDialog() { // creating custom dialog final Dialog dialog = new Dialog(MainActivity.this); // setting content view to dialog dialog.setContentView(R.layout.custom_exit_dialog); // getting reference of TextView TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes); TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo); // click listener for No dialogButtonNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //dismiss the dialog dialog.dismiss(); } }); // click listener for Yes dialogButtonYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // dismiss the dialog // and exit the exit dialog.dismiss(); finish(); } }); // show the exit dialog dialog.show(); } @Override public void onBackPressed() { // calling the function customExitDialog(); }}", "e": 8536, "s": 6950, "text": null }, { "code": null, "e": 8544, "s": 8536, "text": "Output:" }, { "code": null, "e": 8552, "s": 8544, "text": "Android" }, { "code": null, "e": 8557, "s": 8552, "text": "Java" }, { "code": null, "e": 8562, "s": 8557, "text": "Java" }, { "code": null, "e": 8570, "s": 8562, "text": "Android" } ]